Merge branch 'MDL-31429_paypal_messages' of git://github.com/andyjdavis/moodle
[moodle.git] / course / lib.php
blob382ae358ceebaf8e04cfb9d65f7aeb3848d0b2f0
1 <?php
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.
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/>.
18 /**
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core
24 * @subpackage course
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
33 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
34 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
35 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
36 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
37 define('FRONTPAGENEWS', '0');
38 define('FRONTPAGECOURSELIST', '1');
39 define('FRONTPAGECATEGORYNAMES', '2');
40 define('FRONTPAGETOPICONLY', '3');
41 define('FRONTPAGECATEGORYCOMBO', '4');
42 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
43 define('EXCELROWS', 65535);
44 define('FIRSTUSEDEXCELROW', 3);
46 define('MOD_CLASS_ACTIVITY', 0);
47 define('MOD_CLASS_RESOURCE', 1);
49 function make_log_url($module, $url) {
50 switch ($module) {
51 case 'course':
52 if (strpos($url, 'report/') === 0) {
53 // there is only one report type, course reports are deprecated
54 $url = "/$url";
55 break;
57 case 'file':
58 case 'login':
59 case 'lib':
60 case 'admin':
61 case 'calendar':
62 case 'mnet course':
63 if (strpos($url, '../') === 0) {
64 $url = ltrim($url, '.');
65 } else {
66 $url = "/course/$url";
68 break;
69 case 'user':
70 case 'blog':
71 $url = "/$module/$url";
72 break;
73 case 'upload':
74 $url = $url;
75 break;
76 case 'coursetags':
77 $url = '/'.$url;
78 break;
79 case 'library':
80 case '':
81 $url = '/';
82 break;
83 case 'message':
84 $url = "/message/$url";
85 break;
86 case 'notes':
87 $url = "/notes/$url";
88 break;
89 case 'tag':
90 $url = "/tag/$url";
91 break;
92 case 'role':
93 $url = '/'.$url;
94 break;
95 default:
96 $url = "/mod/$module/$url";
97 break;
100 //now let's sanitise urls - there might be some ugly nasties:-(
101 $parts = explode('?', $url);
102 $script = array_shift($parts);
103 if (strpos($script, 'http') === 0) {
104 $script = clean_param($script, PARAM_URL);
105 } else {
106 $script = clean_param($script, PARAM_PATH);
109 $query = '';
110 if ($parts) {
111 $query = implode('', $parts);
112 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
113 $parts = explode('&', $query);
114 $eq = urlencode('=');
115 foreach ($parts as $key=>$part) {
116 $part = urlencode(urldecode($part));
117 $part = str_replace($eq, '=', $part);
118 $parts[$key] = $part;
120 $query = '?'.implode('&amp;', $parts);
123 return $script.$query;
127 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
128 $modname="", $modid=0, $modaction="", $groupid=0) {
129 global $CFG, $DB;
131 // It is assumed that $date is the GMT time of midnight for that day,
132 // and so the next 86400 seconds worth of logs are printed.
134 /// Setup for group handling.
136 // TODO: I don't understand group/context/etc. enough to be able to do
137 // something interesting with it here
138 // What is the context of a remote course?
140 /// If the group mode is separate, and this user does not have editing privileges,
141 /// then only the user's group can be viewed.
142 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
143 // $groupid = get_current_group($course->id);
145 /// If this course doesn't have groups, no groupid can be specified.
146 //else if (!$course->groupmode) {
147 // $groupid = 0;
150 $groupid = 0;
152 $joins = array();
153 $where = '';
155 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
156 FROM {mnet_log} l
157 LEFT JOIN {user} u ON l.userid = u.id
158 WHERE ";
159 $params = array();
161 $where .= "l.hostid = :hostid";
162 $params['hostid'] = $hostid;
164 // TODO: Is 1 really a magic number referring to the sitename?
165 if ($course != SITEID || $modid != 0) {
166 $where .= " AND l.course=:courseid";
167 $params['courseid'] = $course;
170 if ($modname) {
171 $where .= " AND l.module = :modname";
172 $params['modname'] = $modname;
175 if ('site_errors' === $modid) {
176 $where .= " AND ( l.action='error' OR l.action='infected' )";
177 } else if ($modid) {
178 //TODO: This assumes that modids are the same across sites... probably
179 //not true
180 $where .= " AND l.cmid = :modid";
181 $params['modid'] = $modid;
184 if ($modaction) {
185 $firstletter = substr($modaction, 0, 1);
186 if ($firstletter == '-') {
187 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
188 $params['modaction'] = '%'.substr($modaction, 1).'%';
189 } else {
190 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
191 $params['modaction'] = '%'.$modaction.'%';
195 if ($user) {
196 $where .= " AND l.userid = :user";
197 $params['user'] = $user;
200 if ($date) {
201 $enddate = $date + 86400;
202 $where .= " AND l.time > :date AND l.time < :enddate";
203 $params['date'] = $date;
204 $params['enddate'] = $enddate;
207 $result = array();
208 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
209 if(!empty($result['totalcount'])) {
210 $where .= " ORDER BY $order";
211 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
212 } else {
213 $result['logs'] = array();
215 return $result;
218 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
219 $modname="", $modid=0, $modaction="", $groupid=0) {
220 global $DB, $SESSION, $USER;
221 // It is assumed that $date is the GMT time of midnight for that day,
222 // and so the next 86400 seconds worth of logs are printed.
224 /// Setup for group handling.
226 /// If the group mode is separate, and this user does not have editing privileges,
227 /// then only the user's group can be viewed.
228 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
229 if (isset($SESSION->currentgroup[$course->id])) {
230 $groupid = $SESSION->currentgroup[$course->id];
231 } else {
232 $groupid = groups_get_all_groups($course->id, $USER->id);
233 if (is_array($groupid)) {
234 $groupid = array_shift(array_keys($groupid));
235 $SESSION->currentgroup[$course->id] = $groupid;
236 } else {
237 $groupid = 0;
241 /// If this course doesn't have groups, no groupid can be specified.
242 else if (!$course->groupmode) {
243 $groupid = 0;
246 $joins = array();
247 $params = array();
249 if ($course->id != SITEID || $modid != 0) {
250 $joins[] = "l.course = :courseid";
251 $params['courseid'] = $course->id;
254 if ($modname) {
255 $joins[] = "l.module = :modname";
256 $params['modname'] = $modname;
259 if ('site_errors' === $modid) {
260 $joins[] = "( l.action='error' OR l.action='infected' )";
261 } else if ($modid) {
262 $joins[] = "l.cmid = :modid";
263 $params['modid'] = $modid;
266 if ($modaction) {
267 $firstletter = substr($modaction, 0, 1);
268 if ($firstletter == '-') {
269 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
270 $params['modaction'] = '%'.substr($modaction, 1).'%';
271 } else {
272 $joins[] = $DB->sql_like('l.action', ':modaction', false);
273 $params['modaction'] = '%'.$modaction.'%';
278 /// Getting all members of a group.
279 if ($groupid and !$user) {
280 if ($gusers = groups_get_members($groupid)) {
281 $gusers = array_keys($gusers);
282 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
283 } else {
284 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
287 else if ($user) {
288 $joins[] = "l.userid = :userid";
289 $params['userid'] = $user;
292 if ($date) {
293 $enddate = $date + 86400;
294 $joins[] = "l.time > :date AND l.time < :enddate";
295 $params['date'] = $date;
296 $params['enddate'] = $enddate;
299 $selector = implode(' AND ', $joins);
301 $totalcount = 0; // Initialise
302 $result = array();
303 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
304 $result['totalcount'] = $totalcount;
305 return $result;
309 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
310 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
312 global $CFG, $DB, $OUTPUT;
314 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
315 $modname, $modid, $modaction, $groupid)) {
316 echo $OUTPUT->notification("No logs found!");
317 echo $OUTPUT->footer();
318 exit;
321 $courses = array();
323 if ($course->id == SITEID) {
324 $courses[0] = '';
325 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
326 foreach ($ccc as $cc) {
327 $courses[$cc->id] = $cc->shortname;
330 } else {
331 $courses[$course->id] = $course->shortname;
334 $totalcount = $logs['totalcount'];
335 $count=0;
336 $ldcache = array();
337 $tt = getdate(time());
338 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
340 $strftimedatetime = get_string("strftimedatetime");
342 echo "<div class=\"info\">\n";
343 print_string("displayingrecords", "", $totalcount);
344 echo "</div>\n";
346 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
348 $table = new html_table();
349 $table->classes = array('logtable','generalbox');
350 $table->align = array('right', 'left', 'left');
351 $table->head = array(
352 get_string('time'),
353 get_string('ip_address'),
354 get_string('fullnameuser'),
355 get_string('action'),
356 get_string('info')
358 $table->data = array();
360 if ($course->id == SITEID) {
361 array_unshift($table->align, 'left');
362 array_unshift($table->head, get_string('course'));
365 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
366 if (empty($logs['logs'])) {
367 $logs['logs'] = array();
370 foreach ($logs['logs'] as $log) {
372 if (isset($ldcache[$log->module][$log->action])) {
373 $ld = $ldcache[$log->module][$log->action];
374 } else {
375 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
376 $ldcache[$log->module][$log->action] = $ld;
378 if ($ld && is_numeric($log->info)) {
379 // ugly hack to make sure fullname is shown correctly
380 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
381 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
382 } else {
383 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
387 //Filter log->info
388 $log->info = format_string($log->info);
390 // If $log->url has been trimmed short by the db size restriction
391 // code in add_to_log, keep a note so we don't add a link to a broken url
392 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
394 $row = array();
395 if ($course->id == SITEID) {
396 if (empty($log->course)) {
397 $row[] = get_string('site');
398 } else {
399 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
403 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
405 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
406 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
408 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))));
410 $displayaction="$log->module $log->action";
411 if ($brokenurl) {
412 $row[] = $displayaction;
413 } else {
414 $link = make_log_url($log->module,$log->url);
415 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
417 $row[] = $log->info;
418 $table->data[] = $row;
421 echo html_writer::table($table);
422 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
426 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
427 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
429 global $CFG, $DB, $OUTPUT;
431 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
432 $modname, $modid, $modaction, $groupid)) {
433 echo $OUTPUT->notification("No logs found!");
434 echo $OUTPUT->footer();
435 exit;
438 if ($course->id == SITEID) {
439 $courses[0] = '';
440 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
441 foreach ($ccc as $cc) {
442 $courses[$cc->id] = $cc->shortname;
447 $totalcount = $logs['totalcount'];
448 $count=0;
449 $ldcache = array();
450 $tt = getdate(time());
451 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
453 $strftimedatetime = get_string("strftimedatetime");
455 echo "<div class=\"info\">\n";
456 print_string("displayingrecords", "", $totalcount);
457 echo "</div>\n";
459 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
461 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
462 echo "<tr>";
463 if ($course->id == SITEID) {
464 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
466 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
467 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
468 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
469 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
470 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
471 echo "</tr>\n";
473 if (empty($logs['logs'])) {
474 echo "</table>\n";
475 return;
478 $row = 1;
479 foreach ($logs['logs'] as $log) {
481 $log->info = $log->coursename;
482 $row = ($row + 1) % 2;
484 if (isset($ldcache[$log->module][$log->action])) {
485 $ld = $ldcache[$log->module][$log->action];
486 } else {
487 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
488 $ldcache[$log->module][$log->action] = $ld;
490 if (0 && $ld && !empty($log->info)) {
491 // ugly hack to make sure fullname is shown correctly
492 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
493 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
494 } else {
495 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
499 //Filter log->info
500 $log->info = format_string($log->info);
502 echo '<tr class="r'.$row.'">';
503 if ($course->id == SITEID) {
504 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
505 echo "<td class=\"r$row c0\" >\n";
506 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
507 echo "</td>\n";
509 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
510 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
511 echo "<td class=\"r$row c2\" >\n";
512 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
513 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
514 echo "</td>\n";
515 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
516 echo "<td class=\"r$row c3\" >\n";
517 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
518 echo "</td>\n";
519 echo "<td class=\"r$row c4\">\n";
520 echo $log->action .': '.$log->module;
521 echo "</td>\n";;
522 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
523 echo "</tr>\n";
525 echo "</table>\n";
527 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
531 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
532 $modid, $modaction, $groupid) {
533 global $DB;
535 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
536 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
538 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
539 $modname, $modid, $modaction, $groupid)) {
540 return false;
543 $courses = array();
545 if ($course->id == SITEID) {
546 $courses[0] = '';
547 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
548 foreach ($ccc as $cc) {
549 $courses[$cc->id] = $cc->shortname;
552 } else {
553 $courses[$course->id] = $course->shortname;
556 $count=0;
557 $ldcache = array();
558 $tt = getdate(time());
559 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
561 $strftimedatetime = get_string("strftimedatetime");
563 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
564 $filename .= '.txt';
565 header("Content-Type: application/download\n");
566 header("Content-Disposition: attachment; filename=$filename");
567 header("Expires: 0");
568 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
569 header("Pragma: public");
571 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
572 echo $text."\n";
574 if (empty($logs['logs'])) {
575 return true;
578 foreach ($logs['logs'] as $log) {
579 if (isset($ldcache[$log->module][$log->action])) {
580 $ld = $ldcache[$log->module][$log->action];
581 } else {
582 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
583 $ldcache[$log->module][$log->action] = $ld;
585 if ($ld && !empty($log->info)) {
586 // ugly hack to make sure fullname is shown correctly
587 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
588 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
589 } else {
590 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
594 //Filter log->info
595 $log->info = format_string($log->info);
596 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
598 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
599 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
600 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
601 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
602 $text = implode("\t", $row);
603 echo $text." \n";
605 return true;
609 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
610 $modid, $modaction, $groupid) {
612 global $CFG, $DB;
614 require_once("$CFG->libdir/excellib.class.php");
616 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
617 $modname, $modid, $modaction, $groupid)) {
618 return false;
621 $courses = array();
623 if ($course->id == SITEID) {
624 $courses[0] = '';
625 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
626 foreach ($ccc as $cc) {
627 $courses[$cc->id] = $cc->shortname;
630 } else {
631 $courses[$course->id] = $course->shortname;
634 $count=0;
635 $ldcache = array();
636 $tt = getdate(time());
637 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
639 $strftimedatetime = get_string("strftimedatetime");
641 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
642 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
643 $filename .= '.xls';
645 $workbook = new MoodleExcelWorkbook('-');
646 $workbook->send($filename);
648 $worksheet = array();
649 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
650 get_string('fullnameuser'), get_string('action'), get_string('info'));
652 // Creating worksheets
653 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
654 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
655 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
656 $worksheet[$wsnumber]->set_column(1, 1, 30);
657 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
658 userdate(time(), $strftimedatetime));
659 $col = 0;
660 foreach ($headers as $item) {
661 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
662 $col++;
666 if (empty($logs['logs'])) {
667 $workbook->close();
668 return true;
671 $formatDate =& $workbook->add_format();
672 $formatDate->set_num_format(get_string('log_excel_date_format'));
674 $row = FIRSTUSEDEXCELROW;
675 $wsnumber = 1;
676 $myxls =& $worksheet[$wsnumber];
677 foreach ($logs['logs'] as $log) {
678 if (isset($ldcache[$log->module][$log->action])) {
679 $ld = $ldcache[$log->module][$log->action];
680 } else {
681 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
682 $ldcache[$log->module][$log->action] = $ld;
684 if ($ld && !empty($log->info)) {
685 // ugly hack to make sure fullname is shown correctly
686 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
687 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
688 } else {
689 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
693 // Filter log->info
694 $log->info = format_string($log->info);
695 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
697 if ($nroPages>1) {
698 if ($row > EXCELROWS) {
699 $wsnumber++;
700 $myxls =& $worksheet[$wsnumber];
701 $row = FIRSTUSEDEXCELROW;
705 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
707 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
708 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
709 $myxls->write($row, 2, $log->ip, '');
710 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
711 $myxls->write($row, 3, $fullname, '');
712 $myxls->write($row, 4, $log->module.' '.$log->action, '');
713 $myxls->write($row, 5, $log->info, '');
715 $row++;
718 $workbook->close();
719 return true;
722 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
723 $modid, $modaction, $groupid) {
725 global $CFG, $DB;
727 require_once("$CFG->libdir/odslib.class.php");
729 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
730 $modname, $modid, $modaction, $groupid)) {
731 return false;
734 $courses = array();
736 if ($course->id == SITEID) {
737 $courses[0] = '';
738 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
739 foreach ($ccc as $cc) {
740 $courses[$cc->id] = $cc->shortname;
743 } else {
744 $courses[$course->id] = $course->shortname;
747 $count=0;
748 $ldcache = array();
749 $tt = getdate(time());
750 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
752 $strftimedatetime = get_string("strftimedatetime");
754 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
755 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
756 $filename .= '.ods';
758 $workbook = new MoodleODSWorkbook('-');
759 $workbook->send($filename);
761 $worksheet = array();
762 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
763 get_string('fullnameuser'), get_string('action'), get_string('info'));
765 // Creating worksheets
766 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
767 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
768 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
769 $worksheet[$wsnumber]->set_column(1, 1, 30);
770 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
771 userdate(time(), $strftimedatetime));
772 $col = 0;
773 foreach ($headers as $item) {
774 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
775 $col++;
779 if (empty($logs['logs'])) {
780 $workbook->close();
781 return true;
784 $formatDate =& $workbook->add_format();
785 $formatDate->set_num_format(get_string('log_excel_date_format'));
787 $row = FIRSTUSEDEXCELROW;
788 $wsnumber = 1;
789 $myxls =& $worksheet[$wsnumber];
790 foreach ($logs['logs'] as $log) {
791 if (isset($ldcache[$log->module][$log->action])) {
792 $ld = $ldcache[$log->module][$log->action];
793 } else {
794 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
795 $ldcache[$log->module][$log->action] = $ld;
797 if ($ld && !empty($log->info)) {
798 // ugly hack to make sure fullname is shown correctly
799 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
800 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
801 } else {
802 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
806 // Filter log->info
807 $log->info = format_string($log->info);
808 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
810 if ($nroPages>1) {
811 if ($row > EXCELROWS) {
812 $wsnumber++;
813 $myxls =& $worksheet[$wsnumber];
814 $row = FIRSTUSEDEXCELROW;
818 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
820 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
821 $myxls->write_date($row, 1, $log->time);
822 $myxls->write_string($row, 2, $log->ip);
823 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
824 $myxls->write_string($row, 3, $fullname);
825 $myxls->write_string($row, 4, $log->module.' '.$log->action);
826 $myxls->write_string($row, 5, $log->info);
828 $row++;
831 $workbook->close();
832 return true;
836 function print_overview($courses, array $remote_courses=array()) {
837 global $CFG, $USER, $DB, $OUTPUT;
839 $htmlarray = array();
840 if ($modules = $DB->get_records('modules')) {
841 foreach ($modules as $mod) {
842 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
843 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
844 $fname = $mod->name.'_print_overview';
845 if (function_exists($fname)) {
846 $fname($courses,$htmlarray);
851 foreach ($courses as $course) {
852 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
853 echo $OUTPUT->box_start('coursebox');
854 $attributes = array('title' => s($fullname));
855 if (empty($course->visible)) {
856 $attributes['class'] = 'dimmed';
858 echo $OUTPUT->heading(html_writer::link(
859 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
860 if (array_key_exists($course->id,$htmlarray)) {
861 foreach ($htmlarray[$course->id] as $modname => $html) {
862 echo $html;
865 echo $OUTPUT->box_end();
868 if (!empty($remote_courses)) {
869 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
871 foreach ($remote_courses as $course) {
872 echo $OUTPUT->box_start('coursebox');
873 $attributes = array('title' => s($course->fullname));
874 echo $OUTPUT->heading(html_writer::link(
875 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
876 format_string($course->shortname),
877 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
878 echo $OUTPUT->box_end();
884 * This function trawls through the logs looking for
885 * anything new since the user's last login
887 function print_recent_activity($course) {
888 // $course is an object
889 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
891 $context = get_context_instance(CONTEXT_COURSE, $course->id);
893 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
895 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
897 if (!isguestuser()) {
898 if (!empty($USER->lastcourseaccess[$course->id])) {
899 if ($USER->lastcourseaccess[$course->id] > $timestart) {
900 $timestart = $USER->lastcourseaccess[$course->id];
905 echo '<div class="activitydate">';
906 echo get_string('activitysince', '', userdate($timestart));
907 echo '</div>';
908 echo '<div class="activityhead">';
910 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
912 echo "</div>\n";
914 $content = false;
916 /// Firstly, have there been any new enrolments?
918 $users = get_recent_enrolments($course->id, $timestart);
920 //Accessibility: new users now appear in an <OL> list.
921 if ($users) {
922 echo '<div class="newusers">';
923 echo $OUTPUT->heading(get_string("newusers").':', 3);
924 $content = true;
925 echo "<ol class=\"list\">\n";
926 foreach ($users as $user) {
927 $fullname = fullname($user, $viewfullnames);
928 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
930 echo "</ol>\n</div>\n";
933 /// Next, have there been any modifications to the course structure?
935 $modinfo = get_fast_modinfo($course);
937 $changelist = array();
939 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
940 module = 'course' AND
941 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
942 array($timestart, $course->id), "id ASC");
944 if ($logs) {
945 $actions = array('add mod', 'update mod', 'delete mod');
946 $newgones = array(); // added and later deleted items
947 foreach ($logs as $key => $log) {
948 if (!in_array($log->action, $actions)) {
949 continue;
951 $info = explode(' ', $log->info);
953 // note: in most cases I replaced hardcoding of label with use of
954 // $cm->has_view() but it was not possible to do this here because
955 // we don't necessarily have the $cm for it
956 if ($info[0] == 'label') { // Labels are ignored in recent activity
957 continue;
960 if (count($info) != 2) {
961 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
962 continue;
965 $modname = $info[0];
966 $instanceid = $info[1];
968 if ($log->action == 'delete mod') {
969 // unfortunately we do not know if the mod was visible
970 if (!array_key_exists($log->info, $newgones)) {
971 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
972 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
974 } else {
975 if (!isset($modinfo->instances[$modname][$instanceid])) {
976 if ($log->action == 'add mod') {
977 // do not display added and later deleted activities
978 $newgones[$log->info] = true;
980 continue;
982 $cm = $modinfo->instances[$modname][$instanceid];
983 if (!$cm->uservisible) {
984 continue;
987 if ($log->action == 'add mod') {
988 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
989 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
991 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
992 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
993 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
999 if (!empty($changelist)) {
1000 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1001 $content = true;
1002 foreach ($changelist as $changeinfo => $change) {
1003 echo '<p class="activity">'.$change['text'].'</p>';
1007 /// Now display new things from each module
1009 $usedmodules = array();
1010 foreach($modinfo->cms as $cm) {
1011 if (isset($usedmodules[$cm->modname])) {
1012 continue;
1014 if (!$cm->uservisible) {
1015 continue;
1017 $usedmodules[$cm->modname] = $cm->modname;
1020 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1021 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1022 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1023 $print_recent_activity = $modname.'_print_recent_activity';
1024 if (function_exists($print_recent_activity)) {
1025 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1026 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1028 } else {
1029 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1033 if (! $content) {
1034 echo '<p class="message">'.get_string('nothingnew').'</p>';
1039 * For a given course, returns an array of course activity objects
1040 * Each item in the array contains he following properties:
1042 function get_array_of_activities($courseid) {
1043 // cm - course module id
1044 // mod - name of the module (eg forum)
1045 // section - the number of the section (eg week or topic)
1046 // name - the name of the instance
1047 // visible - is the instance visible or not
1048 // groupingid - grouping id
1049 // groupmembersonly - is this instance visible to group members only
1050 // extra - contains extra string to include in any link
1051 global $CFG, $DB;
1052 if(!empty($CFG->enableavailability)) {
1053 require_once($CFG->libdir.'/conditionlib.php');
1056 $course = $DB->get_record('course', array('id'=>$courseid));
1058 if (empty($course)) {
1059 throw new moodle_exception('courseidnotfound');
1062 $mod = array();
1064 $rawmods = get_course_mods($courseid);
1065 if (empty($rawmods)) {
1066 return $mod; // always return array
1069 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1070 foreach ($sections as $section) {
1071 if (!empty($section->sequence)) {
1072 $sequence = explode(",", $section->sequence);
1073 foreach ($sequence as $seq) {
1074 if (empty($rawmods[$seq])) {
1075 continue;
1077 $mod[$seq] = new stdClass();
1078 $mod[$seq]->id = $rawmods[$seq]->instance;
1079 $mod[$seq]->cm = $rawmods[$seq]->id;
1080 $mod[$seq]->mod = $rawmods[$seq]->modname;
1082 // Oh dear. Inconsistent names left here for backward compatibility.
1083 $mod[$seq]->section = $section->section;
1084 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1086 $mod[$seq]->module = $rawmods[$seq]->module;
1087 $mod[$seq]->added = $rawmods[$seq]->added;
1088 $mod[$seq]->score = $rawmods[$seq]->score;
1089 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1090 $mod[$seq]->visible = $rawmods[$seq]->visible;
1091 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1092 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1093 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1094 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1095 $mod[$seq]->indent = $rawmods[$seq]->indent;
1096 $mod[$seq]->completion = $rawmods[$seq]->completion;
1097 $mod[$seq]->extra = "";
1098 $mod[$seq]->completiongradeitemnumber =
1099 $rawmods[$seq]->completiongradeitemnumber;
1100 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1101 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1102 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1103 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1104 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1105 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1106 if (!empty($CFG->enableavailability)) {
1107 condition_info::fill_availability_conditions($rawmods[$seq]);
1108 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1109 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1112 $modname = $mod[$seq]->mod;
1113 $functionname = $modname."_get_coursemodule_info";
1115 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1116 continue;
1119 include_once("$CFG->dirroot/mod/$modname/lib.php");
1121 if ($hasfunction = function_exists($functionname)) {
1122 if ($info = $functionname($rawmods[$seq])) {
1123 if (!empty($info->icon)) {
1124 $mod[$seq]->icon = $info->icon;
1126 if (!empty($info->iconcomponent)) {
1127 $mod[$seq]->iconcomponent = $info->iconcomponent;
1129 if (!empty($info->name)) {
1130 $mod[$seq]->name = $info->name;
1132 if ($info instanceof cached_cm_info) {
1133 // When using cached_cm_info you can include three new fields
1134 // that aren't available for legacy code
1135 if (!empty($info->content)) {
1136 $mod[$seq]->content = $info->content;
1138 if (!empty($info->extraclasses)) {
1139 $mod[$seq]->extraclasses = $info->extraclasses;
1141 if (!empty($info->iconurl)) {
1142 $mod[$seq]->iconurl = $info->iconurl;
1144 if (!empty($info->onclick)) {
1145 $mod[$seq]->onclick = $info->onclick;
1147 if (!empty($info->customdata)) {
1148 $mod[$seq]->customdata = $info->customdata;
1150 } else {
1151 // When using a stdclass, the (horrible) deprecated ->extra field
1152 // is available for BC
1153 if (!empty($info->extra)) {
1154 $mod[$seq]->extra = $info->extra;
1159 // When there is no modname_get_coursemodule_info function,
1160 // but showdescriptions is enabled, then we use the 'intro'
1161 // and 'introformat' fields in the module table
1162 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1163 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1164 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1165 // Set content from intro and introformat. Filters are disabled
1166 // because we filter it with format_text at display time
1167 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1168 $modvalues, $rawmods[$seq]->id, false);
1170 // To save making another query just below, put name in here
1171 $mod[$seq]->name = $modvalues->name;
1174 if (!isset($mod[$seq]->name)) {
1175 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1178 // Minimise the database size by unsetting default options when they are
1179 // 'empty'. This list corresponds to code in the cm_info constructor.
1180 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1181 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1182 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1183 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1184 'completionview', 'completionexpected', 'score', 'showdescription')
1185 as $property) {
1186 if (property_exists($mod[$seq], $property) &&
1187 empty($mod[$seq]->{$property})) {
1188 unset($mod[$seq]->{$property});
1191 // Special case: this value is usually set to null, but may be 0
1192 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1193 is_null($mod[$seq]->completiongradeitemnumber)) {
1194 unset($mod[$seq]->completiongradeitemnumber);
1200 return $mod;
1205 * Returns a number of useful structures for course displays
1207 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1208 global $CFG, $DB, $COURSE;
1210 $mods = array(); // course modules indexed by id
1211 $modnames = array(); // all course module names (except resource!)
1212 $modnamesplural= array(); // all course module names (plural form)
1213 $modnamesused = array(); // course module names used
1215 if ($allmods = $DB->get_records("modules")) {
1216 foreach ($allmods as $mod) {
1217 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1218 continue;
1220 if ($mod->visible) {
1221 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1222 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1225 collatorlib::asort($modnames);
1226 } else {
1227 print_error("nomodules", 'debug');
1230 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1231 $modinfo = get_fast_modinfo($course);
1233 if ($rawmods=$modinfo->cms) {
1234 foreach($rawmods as $mod) { // Index the mods
1235 if (empty($modnames[$mod->modname])) {
1236 continue;
1238 $mods[$mod->id] = $mod;
1239 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1240 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1241 continue;
1243 // Check groupings
1244 if (!groups_course_module_visible($mod)) {
1245 continue;
1247 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1249 if ($modnamesused) {
1250 collatorlib::asort($modnamesused);
1256 * Returns an array of sections for the requested course id
1258 * This function stores the sections against the course id within a staticvar encase
1259 * of subsequent requests. This is used all over + in some standard libs and course
1260 * format callbacks so subsequent requests are a reality.
1262 * @staticvar array $coursesections
1263 * @param int $courseid
1264 * @return array Array of sections
1266 function get_all_sections($courseid) {
1267 global $DB;
1268 static $coursesections = array();
1269 if (!array_key_exists($courseid, $coursesections)) {
1270 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1271 "section, id, course, name, summary, summaryformat, sequence, visible");
1273 return $coursesections[$courseid];
1277 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1278 * It also sets the $USER->display cache to array($courseid=>return value)
1280 * @param int $courseid The course id
1281 * @return int Course section to display, 0 means all
1283 function course_get_display($courseid) {
1284 global $USER, $DB;
1286 if (!isloggedin() or isguestuser()) {
1287 //do not get settings in db for guests
1288 return 0; //return the implicit setting
1291 if (!isset($USER->display[$courseid])) {
1292 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1293 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1295 //use display cache for one course only - we need to keep session small
1296 $USER->display = array($courseid => $display);
1299 return $USER->display[$courseid];
1303 * Show one section only or all sections.
1305 * @param int $courseid The course id
1306 * @param mixed $display show only this section, 0 or 'all' means show all sections
1307 * @return int Course section to display, 0 means all
1309 function course_set_display($courseid, $display) {
1310 global $USER, $DB;
1312 if ($display === 'all' or empty($display)) {
1313 $display = 0;
1316 if (!isloggedin() or isguestuser()) {
1317 //do not store settings in db for guests
1318 return 0;
1321 if ($display == 0) {
1322 //show all, do not store anything in database
1323 $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1325 } else {
1326 if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1327 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
1328 } else {
1329 $record = new stdClass();
1330 $record->userid = $USER->id;
1331 $record->course = $courseid;
1332 $record->display = $display;
1333 $DB->insert_record('course_display', $record);
1337 //use display cache for one course only - we need to keep session small
1338 $USER->display = array($courseid => $display);
1340 return $display;
1344 * Set highlighted section. Only one section can be highlighted at the time.
1346 * @param int $courseid course id
1347 * @param int $marker highlight section with this number, 0 means remove higlightin
1348 * @return void
1350 function course_set_marker($courseid, $marker) {
1351 global $DB;
1352 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1356 * For a given course section, marks it visible or hidden,
1357 * and does the same for every activity in that section
1359 * @param int $courseid course id
1360 * @param int $sectionnumber The section number to adjust
1361 * @param int $visibility The new visibility
1362 * @return array A list of resources which were hidden in the section
1364 function set_section_visible($courseid, $sectionnumber, $visibility) {
1365 global $DB;
1367 $resourcestotoggle = array();
1368 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1369 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1370 if (!empty($section->sequence)) {
1371 $modules = explode(",", $section->sequence);
1372 foreach ($modules as $moduleid) {
1373 set_coursemodule_visible($moduleid, $visibility, true);
1376 rebuild_course_cache($courseid);
1378 // Determine which modules are visible for AJAX update
1379 if (!empty($modules)) {
1380 list($insql, $params) = $DB->get_in_or_equal($modules);
1381 $select = 'id ' . $insql . ' AND visible = ?';
1382 array_push($params, $visibility);
1383 if (!$visibility) {
1384 $select .= ' AND visibleold = 1';
1386 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1389 return $resourcestotoggle;
1393 * Obtains shared data that is used in print_section when displaying a
1394 * course-module entry.
1396 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1398 * This data is also used in other areas of the code.
1399 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1400 * @param object $course Moodle course object
1401 * @return array An array with the following values in this order:
1402 * $content (optional extra content for after link),
1403 * $instancename (text of link)
1405 function get_print_section_cm_text(cm_info $cm, $course) {
1406 global $OUTPUT;
1408 // Get content from modinfo if specified. Content displays either
1409 // in addition to the standard link (below), or replaces it if
1410 // the link is turned off by setting ->url to null.
1411 if (($content = $cm->get_content()) !== '') {
1412 // Improve filter performance by preloading filter setttings for all
1413 // activities on the course (this does nothing if called multiple
1414 // times)
1415 filter_preload_activities($cm->get_modinfo());
1417 // Get module context
1418 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1419 $labelformatoptions = new stdClass();
1420 $labelformatoptions->noclean = true;
1421 $labelformatoptions->overflowdiv = true;
1422 $labelformatoptions->context = $modulecontext;
1423 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1424 } else {
1425 $content = '';
1428 // Get course context
1429 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1430 $stringoptions = new stdClass;
1431 $stringoptions->context = $coursecontext;
1432 $instancename = format_string($cm->name, true, $stringoptions);
1433 return array($content, $instancename);
1437 * Prints a section full of activity modules
1439 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1440 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1442 static $initialised;
1444 static $groupbuttons;
1445 static $groupbuttonslink;
1446 static $isediting;
1447 static $ismoving;
1448 static $strmovehere;
1449 static $strmovefull;
1450 static $strunreadpostsone;
1451 static $groupings;
1452 static $modulenames;
1454 if (!isset($initialised)) {
1455 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1456 $groupbuttonslink = (!$course->groupmodeforce);
1457 $isediting = $PAGE->user_is_editing();
1458 $ismoving = $isediting && ismoving($course->id);
1459 if ($ismoving) {
1460 $strmovehere = get_string("movehere");
1461 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1463 $modulenames = array();
1464 $initialised = true;
1467 $modinfo = get_fast_modinfo($course);
1468 $completioninfo = new completion_info($course);
1470 //Accessibility: replace table with list <ul>, but don't output empty list.
1471 if (!empty($section->sequence)) {
1473 // Fix bug #5027, don't want style=\"width:$width\".
1474 echo "<ul class=\"section img-text\">\n";
1475 $sectionmods = explode(",", $section->sequence);
1477 foreach ($sectionmods as $modnumber) {
1478 if (empty($mods[$modnumber])) {
1479 continue;
1483 * @var cm_info
1485 $mod = $mods[$modnumber];
1487 if ($ismoving and $mod->id == $USER->activitycopy) {
1488 // do not display moving mod
1489 continue;
1492 if (isset($modinfo->cms[$modnumber])) {
1493 // We can continue (because it will not be displayed at all)
1494 // if:
1495 // 1) The activity is not visible to users
1496 // and
1497 // 2a) The 'showavailability' option is not set (if that is set,
1498 // we need to display the activity so we can show
1499 // availability info)
1500 // or
1501 // 2b) The 'availableinfo' is empty, i.e. the activity was
1502 // hidden in a way that leaves no info, such as using the
1503 // eye icon.
1504 if (!$modinfo->cms[$modnumber]->uservisible &&
1505 (empty($modinfo->cms[$modnumber]->showavailability) ||
1506 empty($modinfo->cms[$modnumber]->availableinfo))) {
1507 // visibility shortcut
1508 continue;
1510 } else {
1511 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1512 // module not installed
1513 continue;
1515 if (!coursemodule_visible_for_user($mod) &&
1516 empty($mod->showavailability)) {
1517 // full visibility check
1518 continue;
1522 if (!isset($modulenames[$mod->modname])) {
1523 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1525 $modulename = $modulenames[$mod->modname];
1527 // In some cases the activity is visible to user, but it is
1528 // dimmed. This is done if viewhiddenactivities is true and if:
1529 // 1. the activity is not visible, or
1530 // 2. the activity has dates set which do not include current, or
1531 // 3. the activity has any other conditions set (regardless of whether
1532 // current user meets them)
1533 $canviewhidden = has_capability(
1534 'moodle/course:viewhiddenactivities',
1535 get_context_instance(CONTEXT_MODULE, $mod->id));
1536 $accessiblebutdim = false;
1537 if ($canviewhidden) {
1538 $accessiblebutdim = !$mod->visible;
1539 if (!empty($CFG->enableavailability)) {
1540 $accessiblebutdim = $accessiblebutdim ||
1541 $mod->availablefrom > time() ||
1542 ($mod->availableuntil && $mod->availableuntil < time()) ||
1543 count($mod->conditionsgrade) > 0 ||
1544 count($mod->conditionscompletion) > 0;
1548 $liclasses = array();
1549 $liclasses[] = 'activity';
1550 $liclasses[] = $mod->modname;
1551 $liclasses[] = 'modtype_'.$mod->modname;
1552 $extraclasses = $mod->get_extra_classes();
1553 if ($extraclasses) {
1554 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1556 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1557 if ($ismoving) {
1558 echo '<a title="'.$strmovefull.'"'.
1559 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1560 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1561 ' alt="'.$strmovehere.'" /></a><br />
1565 $classes = array('mod-indent');
1566 if (!empty($mod->indent)) {
1567 $classes[] = 'mod-indent-'.$mod->indent;
1568 if ($mod->indent > 15) {
1569 $classes[] = 'mod-indent-huge';
1572 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1574 // Get data about this course-module
1575 list($content, $instancename) =
1576 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1578 //Accessibility: for files get description via icon, this is very ugly hack!
1579 $altname = '';
1580 $altname = $mod->modfullname;
1581 if (!empty($customicon)) {
1582 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1583 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1584 $mimetype = mimeinfo_from_icon('type', $customicon);
1585 $altname = get_mimetype_description($mimetype);
1588 // Avoid unnecessary duplication: if e.g. a forum name already
1589 // includes the word forum (or Forum, etc) then it is unhelpful
1590 // to include that in the accessible description that is added.
1591 if (false !== strpos(textlib::strtolower($instancename),
1592 textlib::strtolower($altname))) {
1593 $altname = '';
1595 // File type after name, for alphabetic lists (screen reader).
1596 if ($altname) {
1597 $altname = get_accesshide(' '.$altname);
1600 // We may be displaying this just in order to show information
1601 // about visibility, without the actual link
1602 $contentpart = '';
1603 if ($mod->uservisible) {
1604 // Nope - in this case the link is fully working for user
1605 $linkclasses = '';
1606 $textclasses = '';
1607 if ($accessiblebutdim) {
1608 $linkclasses .= ' dimmed';
1609 $textclasses .= ' dimmed_text';
1610 $accesstext = '<span class="accesshide">'.
1611 get_string('hiddenfromstudents').': </span>';
1612 } else {
1613 $accesstext = '';
1615 if ($linkclasses) {
1616 $linkcss = 'class="' . trim($linkclasses) . '" ';
1617 } else {
1618 $linkcss = '';
1620 if ($textclasses) {
1621 $textcss = 'class="' . trim($textclasses) . '" ';
1622 } else {
1623 $textcss = '';
1626 // Get on-click attribute value if specified
1627 $onclick = $mod->get_on_click();
1628 if ($onclick) {
1629 $onclick = ' onclick="' . $onclick . '"';
1632 if ($url = $mod->get_url()) {
1633 // Display link itself
1634 echo '<a ' . $linkcss . $mod->extra . $onclick .
1635 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1636 '" class="activityicon" alt="' .
1637 $modulename . '" /> ' .
1638 $accesstext . '<span class="instancename">' .
1639 $instancename . $altname . '</span></a>';
1641 // If specified, display extra content after link
1642 if ($content) {
1643 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1644 '">' . $content . '</div>';
1646 } else {
1647 // No link, so display only content
1648 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1649 $accesstext . $content . '</div>';
1652 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1653 if (!isset($groupings)) {
1654 $groupings = groups_get_all_groupings($course->id);
1656 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1658 } else {
1659 $textclasses = $extraclasses;
1660 $textclasses .= ' dimmed_text';
1661 if ($textclasses) {
1662 $textcss = 'class="' . trim($textclasses) . '" ';
1663 } else {
1664 $textcss = '';
1666 $accesstext = '<span class="accesshide">' .
1667 get_string('notavailableyet', 'condition') .
1668 ': </span>';
1670 if ($url = $mod->get_url()) {
1671 // Display greyed-out text of link
1672 echo '<div ' . $textcss . $mod->extra .
1673 ' >' . '<img src="' . $mod->get_icon_url() .
1674 '" class="activityicon" alt="' .
1675 $modulename .
1676 '" /> <span>'. $instancename . $altname .
1677 '</span></div>';
1679 // Do not display content after link when it is greyed out like this.
1680 } else {
1681 // No link, so display only content (also greyed)
1682 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1683 $accesstext . $content . '</div>';
1687 // Module can put text after the link (e.g. forum unread)
1688 echo $mod->get_after_link();
1690 // If there is content but NO link (eg label), then display the
1691 // content here (BEFORE any icons). In this case cons must be
1692 // displayed after the content so that it makes more sense visually
1693 // and for accessibility reasons, e.g. if you have a one-line label
1694 // it should work similarly (at least in terms of ordering) to an
1695 // activity.
1696 if (empty($url)) {
1697 echo $contentpart;
1700 if ($isediting) {
1701 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1702 if (! $mod->groupmodelink = $groupbuttonslink) {
1703 $mod->groupmode = $course->groupmode;
1706 } else {
1707 $mod->groupmode = false;
1709 echo '&nbsp;&nbsp;';
1710 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1711 echo $mod->get_after_edit_icons();
1714 // Completion
1715 $completion = $hidecompletion
1716 ? COMPLETION_TRACKING_NONE
1717 : $completioninfo->is_enabled($mod);
1718 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1719 !isguestuser() && $mod->uservisible) {
1720 $completiondata = $completioninfo->get_data($mod,true);
1721 $completionicon = '';
1722 if ($isediting) {
1723 switch ($completion) {
1724 case COMPLETION_TRACKING_MANUAL :
1725 $completionicon = 'manual-enabled'; break;
1726 case COMPLETION_TRACKING_AUTOMATIC :
1727 $completionicon = 'auto-enabled'; break;
1728 default: // wtf
1730 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1731 switch($completiondata->completionstate) {
1732 case COMPLETION_INCOMPLETE:
1733 $completionicon = 'manual-n'; break;
1734 case COMPLETION_COMPLETE:
1735 $completionicon = 'manual-y'; break;
1737 } else { // Automatic
1738 switch($completiondata->completionstate) {
1739 case COMPLETION_INCOMPLETE:
1740 $completionicon = 'auto-n'; break;
1741 case COMPLETION_COMPLETE:
1742 $completionicon = 'auto-y'; break;
1743 case COMPLETION_COMPLETE_PASS:
1744 $completionicon = 'auto-pass'; break;
1745 case COMPLETION_COMPLETE_FAIL:
1746 $completionicon = 'auto-fail'; break;
1749 if ($completionicon) {
1750 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1751 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion', $mod->name));
1752 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1753 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion', $mod->name));
1754 $newstate =
1755 $completiondata->completionstate==COMPLETION_COMPLETE
1756 ? COMPLETION_INCOMPLETE
1757 : COMPLETION_COMPLETE;
1758 // In manual mode the icon is a toggle form...
1760 // If this completion state is used by the
1761 // conditional activities system, we need to turn
1762 // off the JS.
1763 if (!empty($CFG->enableavailability) &&
1764 condition_info::completion_value_used_as_condition($course, $mod)) {
1765 $extraclass = ' preventjs';
1766 } else {
1767 $extraclass = '';
1769 echo "
1770 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1771 <input type='hidden' name='id' value='{$mod->id}' />
1772 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1773 <input type='hidden' name='sesskey' value='".sesskey()."' />
1774 <input type='hidden' name='completionstate' value='$newstate' />
1775 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1776 </div></form>";
1777 } else {
1778 // In auto mode, or when editing, the icon is just an image
1779 echo "<span class='autocompletion'>";
1780 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1785 // If there is content AND a link, then display the content here
1786 // (AFTER any icons). Otherwise it was displayed before
1787 if (!empty($url)) {
1788 echo $contentpart;
1791 // Show availability information (for someone who isn't allowed to
1792 // see the activity itself, or for staff)
1793 if (!$mod->uservisible) {
1794 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1795 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1796 $ci = new condition_info($mod);
1797 $fullinfo = $ci->get_full_information();
1798 if($fullinfo) {
1799 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1800 ? 'userrestriction_visible'
1801 : 'userrestriction_hidden','condition',
1802 $fullinfo).'</div>';
1806 echo html_writer::end_tag('div');
1807 echo html_writer::end_tag('li')."\n";
1810 } elseif ($ismoving) {
1811 echo "<ul class=\"section\">\n";
1814 if ($ismoving) {
1815 echo '<li><a title="'.$strmovefull.'"'.
1816 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1817 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1818 ' alt="'.$strmovehere.'" /></a></li>
1821 if (!empty($section->sequence) || $ismoving) {
1822 echo "</ul><!--class='section'-->\n\n";
1827 * Prints the menus to add activities and resources.
1829 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1830 global $CFG, $OUTPUT;
1832 // check to see if user can add menus
1833 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1834 return false;
1837 // Retrieve all modules with associated metadata
1838 $modules = get_module_metadata($course, $modnames);
1840 // We'll sort resources and activities into two lists
1841 $resources = array();
1842 $activities = array();
1844 // We need to add the section section to the link for each module
1845 $sectionlink = '&section=' . $section;
1847 foreach ($modules as $module) {
1848 if (isset($module->types)) {
1849 // This module has a subtype
1850 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1851 $subtypes = array();
1852 foreach ($module->types as $subtype) {
1853 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1856 // Sort module subtypes into the list
1857 if (!empty($module->title)) {
1858 // This grouping has a name
1859 if ($module->archetype == MOD_CLASS_RESOURCE) {
1860 $resources[] = array($module->title=>$subtypes);
1861 } else {
1862 $activities[] = array($module->title=>$subtypes);
1864 } else {
1865 // This grouping does not have a name
1866 if ($module->archetype == MOD_CLASS_RESOURCE) {
1867 $resources = array_merge($resources, $subtypes);
1868 } else {
1869 $activities = array_merge($activities, $subtypes);
1872 } else {
1873 // This module has no subtypes
1874 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1875 $resources[$module->link . $sectionlink] = $module->title;
1876 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1877 // System modules cannot be added by user, do not add to dropdown
1878 } else {
1879 $activities[$module->link . $sectionlink] = $module->title;
1884 $straddactivity = get_string('addactivity');
1885 $straddresource = get_string('addresource');
1887 $output = '<div class="section_add_menus">';
1889 if (!$vertical) {
1890 $output .= '<div class="horizontal">';
1893 if (!empty($resources)) {
1894 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1895 $select->set_help_icon('resources');
1896 $output .= $OUTPUT->render($select);
1899 if (!empty($activities)) {
1900 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1901 $select->set_help_icon('activities');
1902 $output .= $OUTPUT->render($select);
1905 if (!$vertical) {
1906 $output .= '</div>';
1909 $output .= '</div>';
1911 if ($return) {
1912 return $output;
1913 } else {
1914 echo $output;
1919 * Retrieve all metadata for the requested modules
1921 * @param object $course The Course
1922 * @param array $modnames An array containing the list of modules and their
1923 * names
1924 * @return array A list of stdClass objects containing metadata about each
1925 * module
1927 function get_module_metadata($course, $modnames) {
1928 global $CFG, $OUTPUT;
1930 // get_module_metadata will be called once per section on the page and courses may show
1931 // different modules to one another
1932 static $modlist = array();
1933 if (!isset($modlist[$course->id])) {
1934 $modlist[$course->id] = array();
1937 $return = array();
1938 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&add=';
1939 foreach($modnames as $modname => $modnamestr) {
1940 if (!course_allowed_module($course, $modname)) {
1941 continue;
1943 if (isset($modlist[$modname])) {
1944 // This module is already cached
1945 $return[$modname] = $modlist[$course->id][$modname];
1946 continue;
1949 // Include the module lib
1950 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1951 if (!file_exists($libfile)) {
1952 continue;
1954 include_once($libfile);
1956 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1957 $gettypesfunc = $modname.'_get_types';
1958 if (function_exists($gettypesfunc)) {
1959 if ($types = $gettypesfunc()) {
1960 $group = new stdClass();
1961 $group->name = $modname;
1962 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1963 foreach($types as $type) {
1964 if ($type->typestr === '--') {
1965 continue;
1967 if (strpos($type->typestr, '--') === 0) {
1968 $group->title = str_replace('--', '', $type->typestr);
1969 continue;
1971 // Set the Sub Type metadata
1972 $subtype = new stdClass();
1973 $subtype->title = $type->typestr;
1974 $subtype->type = str_replace('&amp;', '&', $type->type);
1975 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1976 $subtype->archetype = $type->modclass;
1978 // The group archetype should match the subtype archetypes and all subtypes
1979 // should have the same archetype
1980 $group->archetype = $subtype->archetype;
1982 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1983 $subtype->help = get_string('help' . $subtype->name, $modname);
1985 $subtype->link = $urlbase . $subtype->type;
1986 $group->types[] = $subtype;
1988 $modlist[$course->id][$modname] = $group;
1990 } else {
1991 $module = new stdClass();
1992 $module->title = get_string('modulename', $modname);
1993 $module->name = $modname;
1994 $module->link = $urlbase . $modname;
1995 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1996 if (get_string_manager()->string_exists('modulename_help', $modname)) {
1997 $module->help = get_string('modulename_help', $modname);
1999 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2000 $modlist[$course->id][$modname] = $module;
2002 $return[$modname] = $modlist[$course->id][$modname];
2005 return $return;
2009 * Return the course category context for the category with id $categoryid, except
2010 * that if $categoryid is 0, return the system context.
2012 * @param integer $categoryid a category id or 0.
2013 * @return object the corresponding context
2015 function get_category_or_system_context($categoryid) {
2016 if ($categoryid) {
2017 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
2018 } else {
2019 return get_context_instance(CONTEXT_SYSTEM);
2024 * Gets the child categories of a given courses category. Uses a static cache
2025 * to make repeat calls efficient.
2027 * @param int $parentid the id of a course category.
2028 * @return array all the child course categories.
2030 function get_child_categories($parentid) {
2031 static $allcategories = null;
2033 // only fill in this variable the first time
2034 if (null == $allcategories) {
2035 $allcategories = array();
2037 $categories = get_categories();
2038 foreach ($categories as $category) {
2039 if (empty($allcategories[$category->parent])) {
2040 $allcategories[$category->parent] = array();
2042 $allcategories[$category->parent][] = $category;
2046 if (empty($allcategories[$parentid])) {
2047 return array();
2048 } else {
2049 return $allcategories[$parentid];
2054 * This function recursively travels the categories, building up a nice list
2055 * for display. It also makes an array that list all the parents for each
2056 * category.
2058 * For example, if you have a tree of categories like:
2059 * Miscellaneous (id = 1)
2060 * Subcategory (id = 2)
2061 * Sub-subcategory (id = 4)
2062 * Other category (id = 3)
2063 * Then after calling this function you will have
2064 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2065 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2066 * 3 => 'Other category');
2067 * $parents = array(2 => array(1), 4 => array(1, 2));
2069 * If you specify $requiredcapability, then only categories where the current
2070 * user has that capability will be added to $list, although all categories
2071 * will still be added to $parents, and if you only have $requiredcapability
2072 * in a child category, not the parent, then the child catgegory will still be
2073 * included.
2075 * If you specify the option $excluded, then that category, and all its children,
2076 * are omitted from the tree. This is useful when you are doing something like
2077 * moving categories, where you do not want to allow people to move a category
2078 * to be the child of itself.
2080 * @param array $list For output, accumulates an array categoryid => full category path name
2081 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2082 * @param string/array $requiredcapability if given, only categories where the current
2083 * user has this capability will be added to $list. Can also be an array of capabilities,
2084 * in which case they are all required.
2085 * @param integer $excludeid Omit this category and its children from the lists built.
2086 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2087 * @param string $path For internal use, as part of recursive calls.
2089 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2090 $excludeid = 0, $category = NULL, $path = "") {
2092 // initialize the arrays if needed
2093 if (!is_array($list)) {
2094 $list = array();
2096 if (!is_array($parents)) {
2097 $parents = array();
2100 if (empty($category)) {
2101 // Start at the top level.
2102 $category = new stdClass;
2103 $category->id = 0;
2104 } else {
2105 // This is the excluded category, don't include it.
2106 if ($excludeid > 0 && $excludeid == $category->id) {
2107 return;
2110 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2111 $categoryname = format_string($category->name, true, array('context' => $context));
2113 // Update $path.
2114 if ($path) {
2115 $path = $path.' / '.$categoryname;
2116 } else {
2117 $path = $categoryname;
2120 // Add this category to $list, if the permissions check out.
2121 if (empty($requiredcapability)) {
2122 $list[$category->id] = $path;
2124 } else {
2125 $requiredcapability = (array)$requiredcapability;
2126 if (has_all_capabilities($requiredcapability, $context)) {
2127 $list[$category->id] = $path;
2132 // Add all the children recursively, while updating the parents array.
2133 if ($categories = get_child_categories($category->id)) {
2134 foreach ($categories as $cat) {
2135 if (!empty($category->id)) {
2136 if (isset($parents[$category->id])) {
2137 $parents[$cat->id] = $parents[$category->id];
2139 $parents[$cat->id][] = $category->id;
2141 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2147 * This function generates a structured array of courses and categories.
2149 * The depth of categories is limited by $CFG->maxcategorydepth however there
2150 * is no limit on the number of courses!
2152 * Suitable for use with the course renderers course_category_tree method:
2153 * $renderer = $PAGE->get_renderer('core','course');
2154 * echo $renderer->course_category_tree(get_course_category_tree());
2156 * @global moodle_database $DB
2157 * @param int $id
2158 * @param int $depth
2160 function get_course_category_tree($id = 0, $depth = 0) {
2161 global $DB, $CFG;
2162 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2163 $categories = get_child_categories($id);
2164 $categoryids = array();
2165 foreach ($categories as $key => &$category) {
2166 if (!$category->visible && !$viewhiddencats) {
2167 unset($categories[$key]);
2168 continue;
2170 $categoryids[$category->id] = $category;
2171 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2172 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2173 foreach ($subcategories as $subid=>$subcat) {
2174 $categoryids[$subid] = $subcat;
2176 $category->courses = array();
2180 if ($depth > 0) {
2181 // This is a recursive call so return the required array
2182 return array($categories, $categoryids);
2185 // The depth is 0 this function has just been called so we can finish it off
2187 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2188 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2189 $sql = "SELECT
2190 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2191 $ccselect
2192 FROM {course} c
2193 $ccjoin
2194 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2195 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2196 // loop throught them
2197 foreach ($courses as $course) {
2198 if ($course->id == SITEID) {
2199 continue;
2201 context_instance_preload($course);
2202 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2203 $categoryids[$course->category]->courses[$course->id] = $course;
2207 return $categories;
2211 * Recursive function to print out all the categories in a nice format
2212 * with or without courses included
2214 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2215 global $CFG;
2217 // maxcategorydepth == 0 meant no limit
2218 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2219 return;
2222 if (!$displaylist) {
2223 make_categories_list($displaylist, $parentslist);
2226 if ($category) {
2227 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2228 print_category_info($category, $depth, $showcourses);
2229 } else {
2230 return; // Don't bother printing children of invisible categories
2233 } else {
2234 $category = new stdClass();
2235 $category->id = "0";
2238 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2239 $countcats = count($categories);
2240 $count = 0;
2241 $first = true;
2242 $last = false;
2243 foreach ($categories as $cat) {
2244 $count++;
2245 if ($count == $countcats) {
2246 $last = true;
2248 $up = $first ? false : true;
2249 $down = $last ? false : true;
2250 $first = false;
2252 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2258 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2260 function make_categories_options() {
2261 make_categories_list($cats,$parents);
2262 foreach ($cats as $key => $value) {
2263 if (array_key_exists($key,$parents)) {
2264 if ($indent = count($parents[$key])) {
2265 for ($i = 0; $i < $indent; $i++) {
2266 $cats[$key] = '&nbsp;'.$cats[$key];
2271 return $cats;
2275 * Gets the name of a course to be displayed when showing a list of courses.
2276 * By default this is just $course->fullname but user can configure it. The
2277 * result of this function should be passed through print_string.
2278 * @param object $course Moodle course object
2279 * @return string Display name of course (either fullname or short + fullname)
2281 function get_course_display_name_for_list($course) {
2282 global $CFG;
2283 if (!empty($CFG->courselistshortnames)) {
2284 return $course->shortname . ' ' .$course->fullname;
2285 } else {
2286 return $course->fullname;
2291 * Prints the category info in indented fashion
2292 * This function is only used by print_whole_category_list() above
2294 function print_category_info($category, $depth=0, $showcourses = false) {
2295 global $CFG, $DB, $OUTPUT;
2297 $strsummary = get_string('summary');
2299 $catlinkcss = null;
2300 if (!$category->visible) {
2301 $catlinkcss = array('class'=>'dimmed');
2303 static $coursecount = null;
2304 if (null === $coursecount) {
2305 // only need to check this once
2306 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2309 if ($showcourses and $coursecount) {
2310 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2311 } else {
2312 $catimage = "&nbsp;";
2315 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2316 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2317 $fullname = format_string($category->name, true, array('context' => $context));
2319 if ($showcourses and $coursecount) {
2320 echo '<div class="categorylist clearfix">';
2321 $cat = '';
2322 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2323 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2324 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2326 $html = '';
2327 if ($depth > 0) {
2328 for ($i=0; $i< $depth; $i++) {
2329 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2330 $cat = '';
2332 } else {
2333 $html = $cat;
2335 echo html_writer::tag('div', $html, array('class'=>'category'));
2336 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2338 // does the depth exceed maxcategorydepth
2339 // maxcategorydepth == 0 or unset meant no limit
2340 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2341 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2342 foreach ($courses as $course) {
2343 $linkcss = null;
2344 if (!$course->visible) {
2345 $linkcss = array('class'=>'dimmed');
2348 $coursename = get_course_display_name_for_list($course);
2349 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2351 // print enrol info
2352 $courseicon = '';
2353 if ($icons = enrol_get_course_info_icons($course)) {
2354 foreach ($icons as $pix_icon) {
2355 $courseicon = $OUTPUT->render($pix_icon).' ';
2359 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2361 if ($course->summary) {
2362 $link = new moodle_url('/course/info.php?id='.$course->id);
2363 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2364 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2365 array('title'=>$strsummary));
2367 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2370 $html = '';
2371 for ($i=0; $i <= $depth; $i++) {
2372 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2373 $coursecontent = '';
2375 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2378 echo '</div>';
2379 } else {
2380 echo '<div class="categorylist">';
2381 $html = '';
2382 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2383 if (count($courses) > 0) {
2384 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2387 if ($depth > 0) {
2388 for ($i=0; $i< $depth; $i++) {
2389 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2390 $cat = '';
2392 } else {
2393 $html = $cat;
2396 echo html_writer::tag('div', $html, array('class'=>'category'));
2397 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2398 echo '</div>';
2403 * Print the buttons relating to course requests.
2405 * @param object $systemcontext the system context.
2407 function print_course_request_buttons($systemcontext) {
2408 global $CFG, $DB, $OUTPUT;
2409 if (empty($CFG->enablecourserequests)) {
2410 return;
2412 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2413 /// Print a button to request a new course
2414 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2416 /// Print a button to manage pending requests
2417 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2418 $disabled = !$DB->record_exists('course_request', array());
2419 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2424 * Does the user have permission to edit things in this category?
2426 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2427 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2429 function can_edit_in_category($categoryid = 0) {
2430 $context = get_category_or_system_context($categoryid);
2431 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2435 * Prints the turn editing on/off button on course/index.php or course/category.php.
2437 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2438 * @return string HTML of the editing button, or empty string, if this user is not allowed
2439 * to see it.
2441 function update_category_button($categoryid = 0) {
2442 global $CFG, $PAGE, $OUTPUT;
2444 // Check permissions.
2445 if (!can_edit_in_category($categoryid)) {
2446 return '';
2449 // Work out the appropriate action.
2450 if ($PAGE->user_is_editing()) {
2451 $label = get_string('turneditingoff');
2452 $edit = 'off';
2453 } else {
2454 $label = get_string('turneditingon');
2455 $edit = 'on';
2458 // Generate the button HTML.
2459 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2460 if ($categoryid) {
2461 $options['id'] = $categoryid;
2462 $page = 'category.php';
2463 } else {
2464 $page = 'index.php';
2466 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2470 * Category is 0 (for all courses) or an object
2472 function print_courses($category) {
2473 global $CFG, $OUTPUT;
2475 if (!is_object($category) && $category==0) {
2476 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2477 if (is_array($categories) && count($categories) == 1) {
2478 $category = array_shift($categories);
2479 $courses = get_courses_wmanagers($category->id,
2480 'c.sortorder ASC',
2481 array('summary','summaryformat'));
2482 } else {
2483 $courses = get_courses_wmanagers('all',
2484 'c.sortorder ASC',
2485 array('summary','summaryformat'));
2487 unset($categories);
2488 } else {
2489 $courses = get_courses_wmanagers($category->id,
2490 'c.sortorder ASC',
2491 array('summary','summaryformat'));
2494 if ($courses) {
2495 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2496 foreach ($courses as $course) {
2497 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2498 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2499 echo html_writer::start_tag('li');
2500 print_course($course);
2501 echo html_writer::end_tag('li');
2504 echo html_writer::end_tag('ul');
2505 } else {
2506 echo $OUTPUT->heading(get_string("nocoursesyet"));
2507 $context = get_context_instance(CONTEXT_SYSTEM);
2508 if (has_capability('moodle/course:create', $context)) {
2509 $options = array();
2510 if (!empty($category->id)) {
2511 $options['category'] = $category->id;
2512 } else {
2513 $options['category'] = $CFG->defaultrequestcategory;
2515 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2516 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2517 echo html_writer::end_tag('div');
2523 * Print a description of a course, suitable for browsing in a list.
2525 * @param object $course the course object.
2526 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2528 function print_course($course, $highlightterms = '') {
2529 global $CFG, $USER, $DB, $OUTPUT;
2531 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2533 // Rewrite file URLs so that they are correct
2534 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2536 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2537 echo html_writer::start_tag('div', array('class'=>'info'));
2538 echo html_writer::start_tag('h3', array('class'=>'name'));
2540 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2542 $coursename = get_course_display_name_for_list($course);
2543 $linktext = highlight($highlightterms, format_string($coursename));
2544 $linkparams = array('title'=>get_string('entercourse'));
2545 if (empty($course->visible)) {
2546 $linkparams['class'] = 'dimmed';
2548 echo html_writer::link($linkhref, $linktext, $linkparams);
2549 echo html_writer::end_tag('h3');
2551 /// first find all roles that are supposed to be displayed
2552 if (!empty($CFG->coursecontact)) {
2553 $managerroles = explode(',', $CFG->coursecontact);
2554 $namesarray = array();
2555 $rusers = array();
2557 if (!isset($course->managers)) {
2558 $rusers = get_role_users($managerroles, $context, true,
2559 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2560 r.name AS rolename, r.sortorder, r.id AS roleid',
2561 'r.sortorder ASC, u.lastname ASC');
2562 } else {
2563 // use the managers array if we have it for perf reasosn
2564 // populate the datastructure like output of get_role_users();
2565 foreach ($course->managers as $manager) {
2566 $u = new stdClass();
2567 $u = $manager->user;
2568 $u->roleid = $manager->roleid;
2569 $u->rolename = $manager->rolename;
2571 $rusers[] = $u;
2575 /// Rename some of the role names if needed
2576 if (isset($context)) {
2577 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2580 $namesarray = array();
2581 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2582 foreach ($rusers as $ra) {
2583 if (isset($namesarray[$ra->id])) {
2584 // only display a user once with the higest sortorder role
2585 continue;
2588 if (isset($aliasnames[$ra->roleid])) {
2589 $ra->rolename = $aliasnames[$ra->roleid]->name;
2592 $fullname = fullname($ra, $canviewfullnames);
2593 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2594 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2597 if (!empty($namesarray)) {
2598 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2599 foreach ($namesarray as $name) {
2600 echo html_writer::tag('li', $name);
2602 echo html_writer::end_tag('ul');
2605 echo html_writer::end_tag('div'); // End of info div
2607 echo html_writer::start_tag('div', array('class'=>'summary'));
2608 $options = new stdClass();
2609 $options->noclean = true;
2610 $options->para = false;
2611 $options->overflowdiv = true;
2612 if (!isset($course->summaryformat)) {
2613 $course->summaryformat = FORMAT_MOODLE;
2615 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2616 if ($icons = enrol_get_course_info_icons($course)) {
2617 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2618 foreach ($icons as $icon) {
2619 echo $OUTPUT->render($icon);
2621 echo html_writer::end_tag('div'); // End of enrolmenticons div
2623 echo html_writer::end_tag('div'); // End of summary div
2624 echo html_writer::end_tag('div'); // End of coursebox div
2628 * Prints custom user information on the home page.
2629 * Over time this can include all sorts of information
2631 function print_my_moodle() {
2632 global $USER, $CFG, $DB, $OUTPUT;
2634 if (!isloggedin() or isguestuser()) {
2635 print_error('nopermissions', '', '', 'See My Moodle');
2638 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2639 $rhosts = array();
2640 $rcourses = array();
2641 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2642 $rcourses = get_my_remotecourses($USER->id);
2643 $rhosts = get_my_remotehosts();
2646 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2648 if (!empty($courses)) {
2649 echo '<ul class="unlist">';
2650 foreach ($courses as $course) {
2651 if ($course->id == SITEID) {
2652 continue;
2654 echo '<li>';
2655 print_course($course);
2656 echo "</li>\n";
2658 echo "</ul>\n";
2661 // MNET
2662 if (!empty($rcourses)) {
2663 // at the IDP, we know of all the remote courses
2664 foreach ($rcourses as $course) {
2665 print_remote_course($course, "100%");
2667 } elseif (!empty($rhosts)) {
2668 // non-IDP, we know of all the remote servers, but not courses
2669 foreach ($rhosts as $host) {
2670 print_remote_host($host, "100%");
2673 unset($course);
2674 unset($host);
2676 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2677 echo "<table width=\"100%\"><tr><td align=\"center\">";
2678 print_course_search("", false, "short");
2679 echo "</td><td align=\"center\">";
2680 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2681 echo "</td></tr></table>\n";
2684 } else {
2685 if ($DB->count_records("course_categories") > 1) {
2686 echo $OUTPUT->box_start("categorybox");
2687 print_whole_category_list();
2688 echo $OUTPUT->box_end();
2689 } else {
2690 print_courses(0);
2696 function print_course_search($value="", $return=false, $format="plain") {
2697 global $CFG;
2698 static $count = 0;
2700 $count++;
2702 $id = 'coursesearch';
2704 if ($count > 1) {
2705 $id .= $count;
2708 $strsearchcourses= get_string("searchcourses");
2710 if ($format == 'plain') {
2711 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2712 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2713 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2714 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2715 $output .= '<input type="submit" value="'.get_string('go').'" />';
2716 $output .= '</fieldset></form>';
2717 } else if ($format == 'short') {
2718 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2719 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2720 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2721 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2722 $output .= '<input type="submit" value="'.get_string('go').'" />';
2723 $output .= '</fieldset></form>';
2724 } else if ($format == 'navbar') {
2725 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2726 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2727 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2728 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2729 $output .= '<input type="submit" value="'.get_string('go').'" />';
2730 $output .= '</fieldset></form>';
2733 if ($return) {
2734 return $output;
2736 echo $output;
2739 function print_remote_course($course, $width="100%") {
2740 global $CFG, $USER;
2742 $linkcss = '';
2744 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2746 echo '<div class="coursebox remotecoursebox clearfix">';
2747 echo '<div class="info">';
2748 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2749 $linkcss.' href="'.$url.'">'
2750 . format_string($course->fullname) .'</a><br />'
2751 . format_string($course->hostname) . ' : '
2752 . format_string($course->cat_name) . ' : '
2753 . format_string($course->shortname). '</div>';
2754 echo '</div><div class="summary">';
2755 $options = new stdClass();
2756 $options->noclean = true;
2757 $options->para = false;
2758 $options->overflowdiv = true;
2759 echo format_text($course->summary, $course->summaryformat, $options);
2760 echo '</div>';
2761 echo '</div>';
2764 function print_remote_host($host, $width="100%") {
2765 global $OUTPUT;
2767 $linkcss = '';
2769 echo '<div class="coursebox clearfix">';
2770 echo '<div class="info">';
2771 echo '<div class="name">';
2772 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2773 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2774 . s($host['name']).'</a> - ';
2775 echo $host['count'] . ' ' . get_string('courses');
2776 echo '</div>';
2777 echo '</div>';
2778 echo '</div>';
2782 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2784 function add_course_module($mod) {
2785 global $DB;
2787 $mod->added = time();
2788 unset($mod->id);
2790 return $DB->insert_record("course_modules", $mod);
2794 * Returns course section - creates new if does not exist yet.
2795 * @param int $relative section number
2796 * @param int $courseid
2797 * @return object $course_section object
2799 function get_course_section($section, $courseid) {
2800 global $DB;
2802 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2803 return $cw;
2805 $cw = new stdClass();
2806 $cw->course = $courseid;
2807 $cw->section = $section;
2808 $cw->summary = "";
2809 $cw->summaryformat = FORMAT_HTML;
2810 $cw->sequence = "";
2811 $id = $DB->insert_record("course_sections", $cw);
2812 return $DB->get_record("course_sections", array("id"=>$id));
2815 * Given a full mod object with section and course already defined, adds this module to that section.
2817 * @param object $mod
2818 * @param int $beforemod An existing ID which we will insert the new module before
2819 * @return int The course_sections ID where the mod is inserted
2821 function add_mod_to_section($mod, $beforemod=NULL) {
2822 global $DB;
2824 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2826 $section->sequence = trim($section->sequence);
2828 if (empty($section->sequence)) {
2829 $newsequence = "$mod->coursemodule";
2831 } else if ($beforemod) {
2832 $modarray = explode(",", $section->sequence);
2834 if ($key = array_keys($modarray, $beforemod->id)) {
2835 $insertarray = array($mod->id, $beforemod->id);
2836 array_splice($modarray, $key[0], 1, $insertarray);
2837 $newsequence = implode(",", $modarray);
2839 } else { // Just tack it on the end anyway
2840 $newsequence = "$section->sequence,$mod->coursemodule";
2843 } else {
2844 $newsequence = "$section->sequence,$mod->coursemodule";
2847 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2848 return $section->id; // Return course_sections ID that was used.
2850 } else { // Insert a new record
2851 $section = new stdClass();
2852 $section->course = $mod->course;
2853 $section->section = $mod->section;
2854 $section->summary = "";
2855 $section->summaryformat = FORMAT_HTML;
2856 $section->sequence = $mod->coursemodule;
2857 return $DB->insert_record("course_sections", $section);
2861 function set_coursemodule_groupmode($id, $groupmode) {
2862 global $DB;
2863 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2866 function set_coursemodule_idnumber($id, $idnumber) {
2867 global $DB;
2868 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2872 * $prevstateoverrides = true will set the visibility of the course module
2873 * to what is defined in visibleold. This enables us to remember the current
2874 * visibility when making a whole section hidden, so that when we toggle
2875 * that section back to visible, we are able to return the visibility of
2876 * the course module back to what it was originally.
2878 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2879 global $DB, $CFG;
2880 require_once($CFG->libdir.'/gradelib.php');
2882 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2883 return false;
2885 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2886 return false;
2888 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2889 foreach($events as $event) {
2890 if ($visible) {
2891 show_event($event);
2892 } else {
2893 hide_event($event);
2898 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2899 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2900 if ($grade_items) {
2901 foreach ($grade_items as $grade_item) {
2902 $grade_item->set_hidden(!$visible);
2906 if ($prevstateoverrides) {
2907 if ($visible == '0') {
2908 // Remember the current visible state so we can toggle this back.
2909 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2910 } else {
2911 // Get the previous saved visible states.
2912 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2915 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2919 * Delete a course module and any associated data at the course level (events)
2920 * Until 1.5 this function simply marked a deleted flag ... now it
2921 * deletes it completely.
2924 function delete_course_module($id) {
2925 global $CFG, $DB;
2926 require_once($CFG->libdir.'/gradelib.php');
2927 require_once($CFG->dirroot.'/blog/lib.php');
2929 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2930 return true;
2932 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2933 //delete events from calendar
2934 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2935 foreach($events as $event) {
2936 delete_event($event->id);
2939 //delete grade items, outcome items and grades attached to modules
2940 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2941 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2942 foreach ($grade_items as $grade_item) {
2943 $grade_item->delete('moddelete');
2946 // Delete completion and availability data; it is better to do this even if the
2947 // features are not turned on, in case they were turned on previously (these will be
2948 // very quick on an empty table)
2949 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2950 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2951 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2952 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2954 delete_context(CONTEXT_MODULE, $cm->id);
2955 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2958 function delete_mod_from_section($mod, $section) {
2959 global $DB;
2961 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2963 $modarray = explode(",", $section->sequence);
2965 if ($key = array_keys ($modarray, $mod)) {
2966 array_splice($modarray, $key[0], 1);
2967 $newsequence = implode(",", $modarray);
2968 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2969 } else {
2970 return false;
2974 return false;
2978 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2980 * @param object $course course object
2981 * @param int $section Section number (not id!!!)
2982 * @param int $move (-1 or 1)
2983 * @return boolean true if section moved successfully
2985 function move_section($course, $section, $move) {
2986 /// Moves a whole course section up and down within the course
2987 global $USER, $DB;
2989 if (!$move) {
2990 return true;
2993 $sectiondest = $section + $move;
2995 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2996 return false;
2999 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
3000 return false;
3003 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
3004 return false;
3007 // Three-step change ensures that the section always remains unique (there is
3008 // a unique index now)
3009 $DB->set_field("course_sections", "section", -$sectiondest, array("id"=>$sectionrecord->id));
3010 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
3011 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
3013 // Update highlighting if the move affects highlighted section
3014 if ($course->marker == $section) {
3015 course_set_marker($course->id, $sectiondest);
3016 } elseif ($course->marker == $sectiondest) {
3017 course_set_marker($course->id, $section);
3020 // if the focus is on the section that is being moved, then move the focus along
3021 if (course_get_display($course->id) == $section) {
3022 course_set_display($course->id, $sectiondest);
3025 // Fix order if needed. The database prevents duplicate sections, but it is
3026 // possible there could be a gap in the numbering.
3027 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
3028 $n = 0;
3029 foreach ($sections as $section) {
3030 if ($section->section != $n) {
3031 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
3033 $n++;
3035 return true;
3039 * Moves a section within a course, from a position to another.
3040 * Be very careful: $section and $destination refer to section number,
3041 * not id!.
3043 * @param object $course
3044 * @param int $section Section number (not id!!!)
3045 * @param int $destination
3046 * @return boolean Result
3048 function move_section_to($course, $section, $destination) {
3049 /// Moves a whole course section up and down within the course
3050 global $USER, $DB;
3052 if (!$destination && $destination != 0) {
3053 return true;
3056 if ($destination > $course->numsections) {
3057 return false;
3060 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3061 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3062 'section ASC, id ASC', 'id, section')) {
3063 return false;
3066 $movedsections = reorder_sections($sections, $section, $destination);
3068 // Update all sections. Do this in 2 steps to avoid breaking database
3069 // uniqueness constraint
3070 $transaction = $DB->start_delegated_transaction();
3071 foreach ($movedsections as $id => $position) {
3072 if ($sections[$id] !== $position) {
3073 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3076 foreach ($movedsections as $id => $position) {
3077 if ($sections[$id] !== $position) {
3078 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3082 // Adjust destination to reflect the actual section
3083 $moveup = false;
3084 if ($section > $destination) {
3085 $destination++;
3086 $moveup = true;
3089 // If we move the highlighted section itself, then just highlight the destination.
3090 // Adjust the higlighted section location if we move something over it either direction.
3091 if ($section == $course->marker) {
3092 course_set_marker($course, $destination);
3093 } elseif ($moveup && $section > $course->marker && $course->marker >= $destination) {
3094 course_set_marker($course, $course->marker+1);
3095 } elseif (!$moveup && $section < $course->marker && $course->marker <= $destination) {
3096 course_set_marker($course, $course->marker-1);
3099 // if the focus is on the section that is being moved, then move the focus along
3100 if (course_get_display($course->id) == $section) {
3101 course_set_display($course->id, $destination);
3103 $transaction->allow_commit();
3104 return true;
3108 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3109 * an original position number and a target position number, rebuilds the array so that the
3110 * move is made without any duplication of section positions.
3111 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3112 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3114 * @param array $sections
3115 * @param int $origin_position
3116 * @param int $target_position
3117 * @return array
3119 function reorder_sections($sections, $origin_position, $target_position) {
3120 if (!is_array($sections)) {
3121 return false;
3124 // We can't move section position 0
3125 if ($origin_position < 1) {
3126 echo "We can't move section position 0";
3127 return false;
3130 // Locate origin section in sections array
3131 if (!$origin_key = array_search($origin_position, $sections)) {
3132 echo "searched position not in sections array";
3133 return false; // searched position not in sections array
3136 // Extract origin section
3137 $origin_section = $sections[$origin_key];
3138 unset($sections[$origin_key]);
3140 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3141 $found = false;
3142 $append_array = array();
3143 foreach ($sections as $id => $position) {
3144 if ($found) {
3145 $append_array[$id] = $position;
3146 unset($sections[$id]);
3148 if ($position == $target_position) {
3149 $found = true;
3153 // Append moved section
3154 $sections[$origin_key] = $origin_section;
3156 // Append rest of array (if applicable)
3157 if (!empty($append_array)) {
3158 foreach ($append_array as $id => $position) {
3159 $sections[$id] = $position;
3163 // Renumber positions
3164 $position = 0;
3165 foreach ($sections as $id => $p) {
3166 $sections[$id] = $position;
3167 $position++;
3170 return $sections;
3175 * Move the module object $mod to the specified $section
3176 * If $beforemod exists then that is the module
3177 * before which $modid should be inserted
3178 * All parameters are objects
3180 function moveto_module($mod, $section, $beforemod=NULL) {
3181 global $DB, $OUTPUT;
3183 /// Remove original module from original section
3184 if (! delete_mod_from_section($mod->id, $mod->section)) {
3185 echo $OUTPUT->notification("Could not delete module from existing section");
3188 /// Update module itself if necessary
3190 if ($mod->section != $section->id) {
3191 $mod->section = $section->id;
3192 $DB->update_record("course_modules", $mod);
3193 // if moving to a hidden section then hide module
3194 if (!$section->visible) {
3195 set_coursemodule_visible($mod->id, 0);
3199 /// Add the module into the new section
3201 $mod->course = $section->course;
3202 $mod->section = $section->section; // need relative reference
3203 $mod->coursemodule = $mod->id;
3205 if (! add_mod_to_section($mod, $beforemod)) {
3206 return false;
3209 return true;
3213 * Produces the editing buttons for a module
3215 * @global core_renderer $OUTPUT
3216 * @staticvar type $str
3217 * @param stdClass $mod The module to produce editing buttons for
3218 * @param bool $absolute_ignored ignored - all links are absolute
3219 * @param bool $moveselect If true a move seleciton process is used (default true)
3220 * @param int $indent The current indenting
3221 * @param int $section The section to link back to
3222 * @return string XHTML for the editing buttons
3224 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3225 global $CFG, $OUTPUT;
3227 static $str;
3229 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3230 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3232 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3233 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3235 // no permission to edit anything
3236 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3237 return false;
3240 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3242 if (!isset($str)) {
3243 $str = new stdClass;
3244 $str->assign = get_string("assignroles", 'role');
3245 $str->delete = get_string("delete");
3246 $str->move = get_string("move");
3247 $str->moveup = get_string("moveup");
3248 $str->movedown = get_string("movedown");
3249 $str->moveright = get_string("moveright");
3250 $str->moveleft = get_string("moveleft");
3251 $str->update = get_string("update");
3252 $str->duplicate = get_string("duplicate");
3253 $str->hide = get_string("hide");
3254 $str->show = get_string("show");
3255 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3256 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3257 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3258 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3259 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3260 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3263 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3265 if ($section >= 0) {
3266 $baseurl->param('sr', $section);
3268 $actions = array();
3270 // leftright
3271 if ($hasmanageactivities) {
3272 if (right_to_left()) { // Exchange arrows on RTL
3273 $rightarrow = 't/left';
3274 $leftarrow = 't/right';
3275 } else {
3276 $rightarrow = 't/right';
3277 $leftarrow = 't/left';
3280 if ($indent > 0) {
3281 $actions[] = new action_link(
3282 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3283 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3284 null,
3285 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3288 if ($indent >= 0) {
3289 $actions[] = new action_link(
3290 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3291 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3292 null,
3293 array('class' => 'editing_moveright', 'title' => $str->moveright)
3298 // move
3299 if ($hasmanageactivities) {
3300 if ($moveselect) {
3301 $actions[] = new action_link(
3302 new moodle_url($baseurl, array('copy' => $mod->id)),
3303 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3304 null,
3305 array('class' => 'editing_move', 'title' => $str->move)
3307 } else {
3308 $actions[] = new action_link(
3309 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3310 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3311 null,
3312 array('class' => 'editing_moveup', 'title' => $str->moveup)
3314 $actions[] = new action_link(
3315 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3316 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3317 null,
3318 array('class' => 'editing_movedown', 'title' => $str->movedown)
3323 // Update
3324 if ($hasmanageactivities) {
3325 $actions[] = new action_link(
3326 new moodle_url($baseurl, array('update' => $mod->id)),
3327 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3328 null,
3329 array('class' => 'editing_update', 'title' => $str->update)
3333 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3334 if (has_all_capabilities($dupecaps, $coursecontext)) {
3335 $actions[] = new action_link(
3336 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3337 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3338 null,
3339 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3343 // Delete
3344 if ($hasmanageactivities) {
3345 $actions[] = new action_link(
3346 new moodle_url($baseurl, array('delete' => $mod->id)),
3347 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3348 null,
3349 array('class' => 'editing_delete', 'title' => $str->delete)
3353 // hideshow
3354 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3355 if ($mod->visible) {
3356 $actions[] = new action_link(
3357 new moodle_url($baseurl, array('hide' => $mod->id)),
3358 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3359 null,
3360 array('class' => 'editing_hide', 'title' => $str->hide)
3362 } else {
3363 $actions[] = new action_link(
3364 new moodle_url($baseurl, array('show' => $mod->id)),
3365 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3366 null,
3367 array('class' => 'editing_show', 'title' => $str->show)
3372 // groupmode
3373 if ($hasmanageactivities and $mod->groupmode !== false) {
3374 if ($mod->groupmode == SEPARATEGROUPS) {
3375 $groupmode = 0;
3376 $grouptitle = $str->groupsseparate;
3377 $forcedgrouptitle = $str->forcedgroupsseparate;
3378 $groupclass = 'editing_groupsseparate';
3379 $groupimage = 't/groups';
3380 } else if ($mod->groupmode == VISIBLEGROUPS) {
3381 $groupmode = 1;
3382 $grouptitle = $str->groupsvisible;
3383 $forcedgrouptitle = $str->forcedgroupsvisible;
3384 $groupclass = 'editing_groupsvisible';
3385 $groupimage = 't/groupv';
3386 } else {
3387 $groupmode = 2;
3388 $grouptitle = $str->groupsnone;
3389 $forcedgrouptitle = $str->forcedgroupsnone;
3390 $groupclass = 'editing_groupsnone';
3391 $groupimage = 't/groupn';
3393 if ($mod->groupmodelink) {
3394 $actions[] = new action_link(
3395 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3396 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3397 null,
3398 array('class' => $groupclass, 'title' => $grouptitle)
3400 } else {
3401 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3405 // Assign
3406 if (has_capability('moodle/role:assign', $modcontext)){
3407 $actions[] = new action_link(
3408 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3409 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3410 null,
3411 array('class' => 'editing_assign', 'title' => $str->assign)
3415 $output = html_writer::start_tag('span', array('class' => 'commands'));
3416 foreach ($actions as $action) {
3417 if ($action instanceof renderable) {
3418 $output .= $OUTPUT->render($action);
3419 } else {
3420 $output .= $action;
3423 $output .= html_writer::end_tag('span');
3424 return $output;
3428 * given a course object with shortname & fullname, this function will
3429 * truncate the the number of chars allowed and add ... if it was too long
3431 function course_format_name ($course,$max=100) {
3433 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3434 $shortname = format_string($course->shortname, true, array('context' => $context));
3435 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3436 $str = $shortname.': '. $fullname;
3437 if (textlib::strlen($str) <= $max) {
3438 return $str;
3440 else {
3441 return textlib::substr($str,0,$max-3).'...';
3446 * Is the user allowed to add this type of module to this course?
3447 * @param object $course the course settings. Only $course->id is used.
3448 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3449 * @return bool whether the current user is allowed to add this type of module to this course.
3451 function course_allowed_module($course, $modname) {
3452 global $DB;
3454 if (is_numeric($modname)) {
3455 throw new coding_exception('Function course_allowed_module no longer
3456 supports numeric module ids. Please update your code to pass the module name.');
3459 $capability = 'mod/' . $modname . ':addinstance';
3460 if (!get_capability_info($capability)) {
3461 // Debug warning that the capability does not exist, but no more than once per page.
3462 static $warned = array();
3463 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3464 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3465 debugging('The module ' . $modname . ' does not define the standard capability ' .
3466 $capability , DEBUG_DEVELOPER);
3467 $warned[$modname] = 1;
3470 // If the capability does not exist, the module can always be added.
3471 return true;
3474 $coursecontext = context_course::instance($course->id);
3475 return has_capability($capability, $coursecontext);
3479 * Recursively delete category including all subcategories and courses.
3480 * @param stdClass $category
3481 * @param boolean $showfeedback display some notices
3482 * @return array return deleted courses
3484 function category_delete_full($category, $showfeedback=true) {
3485 global $CFG, $DB;
3486 require_once($CFG->libdir.'/gradelib.php');
3487 require_once($CFG->libdir.'/questionlib.php');
3488 require_once($CFG->dirroot.'/cohort/lib.php');
3490 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3491 foreach ($children as $childcat) {
3492 category_delete_full($childcat, $showfeedback);
3496 $deletedcourses = array();
3497 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3498 foreach ($courses as $course) {
3499 if (!delete_course($course, false)) {
3500 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3502 $deletedcourses[] = $course;
3506 // move or delete cohorts in this context
3507 cohort_delete_category($category);
3509 // now delete anything that may depend on course category context
3510 grade_course_category_delete($category->id, 0, $showfeedback);
3511 if (!question_delete_course_category($category, 0, $showfeedback)) {
3512 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3515 // finally delete the category and it's context
3516 $DB->delete_records('course_categories', array('id'=>$category->id));
3517 delete_context(CONTEXT_COURSECAT, $category->id);
3519 events_trigger('course_category_deleted', $category);
3521 return $deletedcourses;
3525 * Delete category, but move contents to another category.
3526 * @param object $ccategory
3527 * @param int $newparentid category id
3528 * @return bool status
3530 function category_delete_move($category, $newparentid, $showfeedback=true) {
3531 global $CFG, $DB, $OUTPUT;
3532 require_once($CFG->libdir.'/gradelib.php');
3533 require_once($CFG->libdir.'/questionlib.php');
3534 require_once($CFG->dirroot.'/cohort/lib.php');
3536 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3537 return false;
3540 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3541 foreach ($children as $childcat) {
3542 move_category($childcat, $newparentcat);
3546 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3547 if (!move_courses(array_keys($courses), $newparentid)) {
3548 echo $OUTPUT->notification("Error moving courses");
3549 return false;
3551 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3554 // move or delete cohorts in this context
3555 cohort_delete_category($category);
3557 // now delete anything that may depend on course category context
3558 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3559 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3560 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3561 return false;
3564 // finally delete the category and it's context
3565 $DB->delete_records('course_categories', array('id'=>$category->id));
3566 delete_context(CONTEXT_COURSECAT, $category->id);
3568 events_trigger('course_category_deleted', $category);
3570 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3572 return true;
3576 * Efficiently moves many courses around while maintaining
3577 * sortorder in order.
3579 * @param array $courseids is an array of course ids
3580 * @param int $categoryid
3581 * @return bool success
3583 function move_courses($courseids, $categoryid) {
3584 global $CFG, $DB, $OUTPUT;
3586 if (empty($courseids)) {
3587 // nothing to do
3588 return;
3591 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3592 return false;
3595 $courseids = array_reverse($courseids);
3596 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3597 $i = 1;
3599 foreach ($courseids as $courseid) {
3600 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3601 $course = new stdClass();
3602 $course->id = $courseid;
3603 $course->category = $category->id;
3604 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3605 if ($category->visible == 0) {
3606 // hide the course when moving into hidden category,
3607 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3608 $course->visible = 0;
3611 $DB->update_record('course', $course);
3613 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3614 context_moved($context, $newparent);
3617 fix_course_sortorder();
3619 return true;
3623 * Hide course category and child course and subcategories
3624 * @param stdClass $category
3625 * @return void
3627 function course_category_hide($category) {
3628 global $DB;
3630 $category->visible = 0;
3631 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3632 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3633 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
3634 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3635 // get all child categories and hide too
3636 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3637 foreach ($subcats as $cat) {
3638 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3639 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3640 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3641 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3647 * Show course category and child course and subcategories
3648 * @param stdClass $category
3649 * @return void
3651 function course_category_show($category) {
3652 global $DB;
3654 $category->visible = 1;
3655 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3656 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3657 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3658 // get all child categories and unhide too
3659 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3660 foreach ($subcats as $cat) {
3661 if ($cat->visibleold) {
3662 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3664 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3670 * Efficiently moves a category - NOTE that this can have
3671 * a huge impact access-control-wise...
3673 function move_category($category, $newparentcat) {
3674 global $CFG, $DB;
3676 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3678 $hidecat = false;
3679 if (empty($newparentcat->id)) {
3680 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3682 $newparent = get_context_instance(CONTEXT_SYSTEM);
3684 } else {
3685 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3686 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3688 if (!$newparentcat->visible and $category->visible) {
3689 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3690 $hidecat = true;
3694 context_moved($context, $newparent);
3696 // now make it last in new category
3697 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3699 // and fix the sortorders
3700 fix_course_sortorder();
3702 if ($hidecat) {
3703 course_category_hide($category);
3708 * Returns the display name of the given section that the course prefers.
3710 * This function utilizes a callback that can be implemented within the course
3711 * formats lib.php file to customize the display name that is used to reference
3712 * the section.
3714 * By default (if callback is not defined) the method
3715 * {@see get_numeric_section_name} is called instead.
3717 * @param stdClass $course The course to get the section name for
3718 * @param stdClass $section Section object from database
3719 * @return Display name that the course format prefers, e.g. "Week 2"
3721 * @see get_generic_section_name
3723 function get_section_name(stdClass $course, stdClass $section) {
3724 global $CFG;
3726 /// Inelegant hack for bug 3408
3727 if ($course->format == 'site') {
3728 return get_string('site');
3731 // Use course formatter callback if it exists
3732 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3733 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3734 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3735 require_once $namingfile;
3737 if (function_exists($namingfunction)) {
3738 return $namingfunction($course, $section);
3741 // else, default behavior:
3742 return get_generic_section_name($course->format, $section);
3746 * Gets the generic section name for a courses section.
3748 * @param string $format Course format ID e.g. 'weeks' $course->format
3749 * @param stdClass $section Section object from database
3750 * @return Display name that the course format prefers, e.g. "Week 2"
3752 function get_generic_section_name($format, stdClass $section) {
3753 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3757 function course_format_uses_sections($format) {
3758 global $CFG;
3760 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3761 $featurefunction = 'callback_'.$format.'_uses_sections';
3762 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3763 require_once $featurefile;
3765 if (function_exists($featurefunction)) {
3766 return $featurefunction();
3769 return false;
3773 * Returns the information about the ajax support in the given source format
3775 * The returned object's property (boolean)capable indicates that
3776 * the course format supports Moodle course ajax features.
3777 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3779 * @param string $format
3780 * @return stdClass
3782 function course_format_ajax_support($format) {
3783 global $CFG;
3785 // set up default values
3786 $ajaxsupport = new stdClass();
3787 $ajaxsupport->capable = false;
3788 $ajaxsupport->testedbrowsers = array();
3790 // get the information from the course format library
3791 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3792 $featurefunction = 'callback_'.$format.'_ajax_support';
3793 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3794 require_once $featurefile;
3796 if (function_exists($featurefunction)) {
3797 $formatsupport = $featurefunction();
3798 if (isset($formatsupport->capable)) {
3799 $ajaxsupport->capable = $formatsupport->capable;
3801 if (is_array($formatsupport->testedbrowsers)) {
3802 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3806 return $ajaxsupport;
3810 * Can the current user delete this course?
3811 * Course creators have exception,
3812 * 1 day after the creation they can sill delete the course.
3813 * @param int $courseid
3814 * @return boolean
3816 function can_delete_course($courseid) {
3817 global $USER, $DB;
3819 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3821 if (has_capability('moodle/course:delete', $context)) {
3822 return true;
3825 // hack: now try to find out if creator created this course recently (1 day)
3826 if (!has_capability('moodle/course:create', $context)) {
3827 return false;
3830 $since = time() - 60*60*24;
3832 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3833 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3835 return $DB->record_exists_select('log', $select, $params);
3839 * Save the Your name for 'Some role' strings.
3841 * @param integer $courseid the id of this course.
3842 * @param array $data the data that came from the course settings form.
3844 function save_local_role_names($courseid, $data) {
3845 global $DB;
3846 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3848 foreach ($data as $fieldname => $value) {
3849 if (strpos($fieldname, 'role_') !== 0) {
3850 continue;
3852 list($ignored, $roleid) = explode('_', $fieldname);
3854 // make up our mind whether we want to delete, update or insert
3855 if (!$value) {
3856 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3858 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3859 $rolename->name = $value;
3860 $DB->update_record('role_names', $rolename);
3862 } else {
3863 $rolename = new stdClass;
3864 $rolename->contextid = $context->id;
3865 $rolename->roleid = $roleid;
3866 $rolename->name = $value;
3867 $DB->insert_record('role_names', $rolename);
3873 * Create a course and either return a $course object
3875 * Please note this functions does not verify any access control,
3876 * the calling code is responsible for all validation (usually it is the form definition).
3878 * @param array $editoroptions course description editor options
3879 * @param object $data - all the data needed for an entry in the 'course' table
3880 * @return object new course instance
3882 function create_course($data, $editoroptions = NULL) {
3883 global $CFG, $DB;
3885 //check the categoryid - must be given for all new courses
3886 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3888 //check if the shortname already exist
3889 if (!empty($data->shortname)) {
3890 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3891 throw new moodle_exception('shortnametaken');
3895 //check if the id number already exist
3896 if (!empty($data->idnumber)) {
3897 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3898 throw new moodle_exception('idnumbertaken');
3902 $data->timecreated = time();
3903 $data->timemodified = $data->timecreated;
3905 // place at beginning of any category
3906 $data->sortorder = 0;
3908 if ($editoroptions) {
3909 // summary text is updated later, we need context to store the files first
3910 $data->summary = '';
3911 $data->summary_format = FORMAT_HTML;
3914 if (!isset($data->visible)) {
3915 // data not from form, add missing visibility info
3916 $data->visible = $category->visible;
3918 $data->visibleold = $data->visible;
3920 $newcourseid = $DB->insert_record('course', $data);
3921 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3923 if ($editoroptions) {
3924 // Save the files used in the summary editor and store
3925 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3926 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3927 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3930 $course = $DB->get_record('course', array('id'=>$newcourseid));
3932 // Setup the blocks
3933 blocks_add_default_course_blocks($course);
3935 $section = new stdClass();
3936 $section->course = $course->id; // Create a default section.
3937 $section->section = 0;
3938 $section->summaryformat = FORMAT_HTML;
3939 $DB->insert_record('course_sections', $section);
3941 fix_course_sortorder();
3943 // new context created - better mark it as dirty
3944 mark_context_dirty($context->path);
3946 // Save any custom role names.
3947 save_local_role_names($course->id, (array)$data);
3949 // set up enrolments
3950 enrol_course_updated(true, $course, $data);
3952 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3954 // Trigger events
3955 events_trigger('course_created', $course);
3957 return $course;
3961 * Update a course.
3963 * Please note this functions does not verify any access control,
3964 * the calling code is responsible for all validation (usually it is the form definition).
3966 * @param object $data - all the data needed for an entry in the 'course' table
3967 * @param array $editoroptions course description editor options
3968 * @return void
3970 function update_course($data, $editoroptions = NULL) {
3971 global $CFG, $DB;
3973 $data->timemodified = time();
3975 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3976 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
3978 if ($editoroptions) {
3979 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3982 if (!isset($data->category) or empty($data->category)) {
3983 // prevent nulls and 0 in category field
3984 unset($data->category);
3986 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3988 if (!isset($data->visible)) {
3989 // data not from form, add missing visibility info
3990 $data->visible = $oldcourse->visible;
3993 if ($data->visible != $oldcourse->visible) {
3994 // reset the visibleold flag when manually hiding/unhiding course
3995 $data->visibleold = $data->visible;
3996 } else {
3997 if ($movecat) {
3998 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3999 if (empty($newcategory->visible)) {
4000 // make sure when moving into hidden category the course is hidden automatically
4001 $data->visible = 0;
4006 // Update with the new data
4007 $DB->update_record('course', $data);
4009 $course = $DB->get_record('course', array('id'=>$data->id));
4011 if ($movecat) {
4012 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
4013 context_moved($context, $newparent);
4016 fix_course_sortorder();
4018 // Test for and remove blocks which aren't appropriate anymore
4019 blocks_remove_inappropriate($course);
4021 // Save any custom role names.
4022 save_local_role_names($course->id, $data);
4024 // update enrol settings
4025 enrol_course_updated(false, $course, $data);
4027 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4029 // Trigger events
4030 events_trigger('course_updated', $course);
4034 * Average number of participants
4035 * @return integer
4037 function average_number_of_participants() {
4038 global $DB, $SITE;
4040 //count total of enrolments for visible course (except front page)
4041 $sql = 'SELECT COUNT(*) FROM (
4042 SELECT DISTINCT ue.userid, e.courseid
4043 FROM {user_enrolments} ue, {enrol} e, {course} c
4044 WHERE ue.enrolid = e.id
4045 AND e.courseid <> :siteid
4046 AND c.id = e.courseid
4047 AND c.visible = 1) as total';
4048 $params = array('siteid' => $SITE->id);
4049 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4052 //count total of visible courses (minus front page)
4053 $coursetotal = $DB->count_records('course', array('visible' => 1));
4054 $coursetotal = $coursetotal - 1 ;
4056 //average of enrolment
4057 if (empty($coursetotal)) {
4058 $participantaverage = 0;
4059 } else {
4060 $participantaverage = $enrolmenttotal / $coursetotal;
4063 return $participantaverage;
4067 * Average number of course modules
4068 * @return integer
4070 function average_number_of_courses_modules() {
4071 global $DB, $SITE;
4073 //count total of visible course module (except front page)
4074 $sql = 'SELECT COUNT(*) FROM (
4075 SELECT cm.course, cm.module
4076 FROM {course} c, {course_modules} cm
4077 WHERE c.id = cm.course
4078 AND c.id <> :siteid
4079 AND cm.visible = 1
4080 AND c.visible = 1) as total';
4081 $params = array('siteid' => $SITE->id);
4082 $moduletotal = $DB->count_records_sql($sql, $params);
4085 //count total of visible courses (minus front page)
4086 $coursetotal = $DB->count_records('course', array('visible' => 1));
4087 $coursetotal = $coursetotal - 1 ;
4089 //average of course module
4090 if (empty($coursetotal)) {
4091 $coursemoduleaverage = 0;
4092 } else {
4093 $coursemoduleaverage = $moduletotal / $coursetotal;
4096 return $coursemoduleaverage;
4100 * This class pertains to course requests and contains methods associated with
4101 * create, approving, and removing course requests.
4103 * Please note we do not allow embedded images here because there is no context
4104 * to store them with proper access control.
4106 * @copyright 2009 Sam Hemelryk
4107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4108 * @since Moodle 2.0
4110 * @property-read int $id
4111 * @property-read string $fullname
4112 * @property-read string $shortname
4113 * @property-read string $summary
4114 * @property-read int $summaryformat
4115 * @property-read int $summarytrust
4116 * @property-read string $reason
4117 * @property-read int $requester
4119 class course_request {
4122 * This is the stdClass that stores the properties for the course request
4123 * and is externally accessed through the __get magic method
4124 * @var stdClass
4126 protected $properties;
4129 * An array of options for the summary editor used by course request forms.
4130 * This is initially set by {@link summary_editor_options()}
4131 * @var array
4132 * @static
4134 protected static $summaryeditoroptions;
4137 * Static function to prepare the summary editor for working with a course
4138 * request.
4140 * @static
4141 * @param null|stdClass $data Optional, an object containing the default values
4142 * for the form, these may be modified when preparing the
4143 * editor so this should be called before creating the form
4144 * @return stdClass An object that can be used to set the default values for
4145 * an mforms form
4147 public static function prepare($data=null) {
4148 if ($data === null) {
4149 $data = new stdClass;
4151 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4152 return $data;
4156 * Static function to create a new course request when passed an array of properties
4157 * for it.
4159 * This function also handles saving any files that may have been used in the editor
4161 * @static
4162 * @param stdClass $data
4163 * @return course_request The newly created course request
4165 public static function create($data) {
4166 global $USER, $DB, $CFG;
4167 $data->requester = $USER->id;
4169 // Summary is a required field so copy the text over
4170 $data->summary = $data->summary_editor['text'];
4171 $data->summaryformat = $data->summary_editor['format'];
4173 $data->id = $DB->insert_record('course_request', $data);
4175 // Create a new course_request object and return it
4176 $request = new course_request($data);
4178 // Notify the admin if required.
4179 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4181 $a = new stdClass;
4182 $a->link = "$CFG->wwwroot/course/pending.php";
4183 $a->user = fullname($USER);
4184 $subject = get_string('courserequest');
4185 $message = get_string('courserequestnotifyemail', 'admin', $a);
4186 foreach ($users as $user) {
4187 $request->notify($user, $USER, 'courserequested', $subject, $message);
4191 return $request;
4195 * Returns an array of options to use with a summary editor
4197 * @uses course_request::$summaryeditoroptions
4198 * @return array An array of options to use with the editor
4200 public static function summary_editor_options() {
4201 global $CFG;
4202 if (self::$summaryeditoroptions === null) {
4203 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4205 return self::$summaryeditoroptions;
4209 * Loads the properties for this course request object. Id is required and if
4210 * only id is provided then we load the rest of the properties from the database
4212 * @param stdClass|int $properties Either an object containing properties
4213 * or the course_request id to load
4215 public function __construct($properties) {
4216 global $DB;
4217 if (empty($properties->id)) {
4218 if (empty($properties)) {
4219 throw new coding_exception('You must provide a course request id when creating a course_request object');
4221 $id = $properties;
4222 $properties = new stdClass;
4223 $properties->id = (int)$id;
4224 unset($id);
4226 if (empty($properties->requester)) {
4227 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4228 print_error('unknowncourserequest');
4230 } else {
4231 $this->properties = $properties;
4233 $this->properties->collision = null;
4237 * Returns the requested property
4239 * @param string $key
4240 * @return mixed
4242 public function __get($key) {
4243 return $this->properties->$key;
4247 * Override this to ensure empty($request->blah) calls return a reliable answer...
4249 * This is required because we define the __get method
4251 * @param mixed $key
4252 * @return bool True is it not empty, false otherwise
4254 public function __isset($key) {
4255 return (!empty($this->properties->$key));
4259 * Returns the user who requested this course
4261 * Uses a static var to cache the results and cut down the number of db queries
4263 * @staticvar array $requesters An array of cached users
4264 * @return stdClass The user who requested the course
4266 public function get_requester() {
4267 global $DB;
4268 static $requesters= array();
4269 if (!array_key_exists($this->properties->requester, $requesters)) {
4270 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4272 return $requesters[$this->properties->requester];
4276 * Checks that the shortname used by the course does not conflict with any other
4277 * courses that exist
4279 * @param string|null $shortnamemark The string to append to the requests shortname
4280 * should a conflict be found
4281 * @return bool true is there is a conflict, false otherwise
4283 public function check_shortname_collision($shortnamemark = '[*]') {
4284 global $DB;
4286 if ($this->properties->collision !== null) {
4287 return $this->properties->collision;
4290 if (empty($this->properties->shortname)) {
4291 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4292 $this->properties->collision = false;
4293 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4294 if (!empty($shortnamemark)) {
4295 $this->properties->shortname .= ' '.$shortnamemark;
4297 $this->properties->collision = true;
4298 } else {
4299 $this->properties->collision = false;
4301 return $this->properties->collision;
4305 * This function approves the request turning it into a course
4307 * This function converts the course request into a course, at the same time
4308 * transferring any files used in the summary to the new course and then removing
4309 * the course request and the files associated with it.
4311 * @return int The id of the course that was created from this request
4313 public function approve() {
4314 global $CFG, $DB, $USER;
4316 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4318 $category = get_course_category($CFG->defaultrequestcategory);
4319 $courseconfig = get_config('moodlecourse');
4321 // Transfer appropriate settings
4322 $data = clone($this->properties);
4323 unset($data->id);
4324 unset($data->reason);
4325 unset($data->requester);
4327 // Set category
4328 $data->category = $category->id;
4329 $data->sortorder = $category->sortorder; // place as the first in category
4331 // Set misc settings
4332 $data->requested = 1;
4334 // Apply course default settings
4335 $data->format = $courseconfig->format;
4336 $data->numsections = $courseconfig->numsections;
4337 $data->hiddensections = $courseconfig->hiddensections;
4338 $data->newsitems = $courseconfig->newsitems;
4339 $data->showgrades = $courseconfig->showgrades;
4340 $data->showreports = $courseconfig->showreports;
4341 $data->maxbytes = $courseconfig->maxbytes;
4342 $data->groupmode = $courseconfig->groupmode;
4343 $data->groupmodeforce = $courseconfig->groupmodeforce;
4344 $data->visible = $courseconfig->visible;
4345 $data->visibleold = $data->visible;
4346 $data->lang = $courseconfig->lang;
4348 $course = create_course($data);
4349 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
4351 // add enrol instances
4352 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4353 if ($manual = enrol_get_plugin('manual')) {
4354 $manual->add_default_instance($course);
4358 // enrol the requester as teacher if necessary
4359 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4360 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4363 $this->delete();
4365 $a = new stdClass();
4366 $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
4367 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4368 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4370 return $course->id;
4374 * Reject a course request
4376 * This function rejects a course request, emailing the requesting user the
4377 * provided notice and then removing the request from the database
4379 * @param string $notice The message to display to the user
4381 public function reject($notice) {
4382 global $USER, $DB;
4383 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4384 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4385 $this->delete();
4389 * Deletes the course request and any associated files
4391 public function delete() {
4392 global $DB;
4393 $DB->delete_records('course_request', array('id' => $this->properties->id));
4397 * Send a message from one user to another using events_trigger
4399 * @param object $touser
4400 * @param object $fromuser
4401 * @param string $name
4402 * @param string $subject
4403 * @param string $message
4405 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4406 $eventdata = new stdClass();
4407 $eventdata->component = 'moodle';
4408 $eventdata->name = $name;
4409 $eventdata->userfrom = $fromuser;
4410 $eventdata->userto = $touser;
4411 $eventdata->subject = $subject;
4412 $eventdata->fullmessage = $message;
4413 $eventdata->fullmessageformat = FORMAT_PLAIN;
4414 $eventdata->fullmessagehtml = '';
4415 $eventdata->smallmessage = '';
4416 $eventdata->notification = 1;
4417 message_send($eventdata);
4422 * Return a list of page types
4423 * @param string $pagetype current page type
4424 * @param stdClass $parentcontext Block's parent context
4425 * @param stdClass $currentcontext Current context of block
4427 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4428 // if above course context ,display all course fomats
4429 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4430 if ($course->id == SITEID) {
4431 return array('*'=>get_string('page-x', 'pagetype'));
4432 } else {
4433 return array('*'=>get_string('page-x', 'pagetype'),
4434 'course-*'=>get_string('page-course-x', 'pagetype'),
4435 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4441 * Include the relevant javascript and language strings for the resource
4442 * toolbox YUI module
4444 * @param integer $id The ID of the course being applied to
4445 * @param array $modules An array containing the names of the modules in
4446 * use on the page
4447 * @param object $config An object containing configuration parameters for ajax modules including:
4448 * * resourceurl The URL to post changes to for resource changes
4449 * * sectionurl The URL to post changes to for section changes
4450 * * pageparams Additional parameters to pass through in the post
4451 * @return void
4453 function include_course_ajax($course, $modules = array(), $config = null) {
4454 global $PAGE, $CFG, $USER;
4456 // Ensure that ajax should be included
4457 $courseformatajaxsupport = course_format_ajax_support($course->format);
4458 if (!$CFG->enablecourseajax
4459 || !$PAGE->theme->enablecourseajax
4460 || !$CFG->enableajax
4461 || empty($USER->editing)
4462 || !$PAGE->user_is_editing()
4463 || ($course->id != SITEID && !$courseformatajaxsupport->capable)) {
4464 return;
4467 if (!$config) {
4468 $config = new stdClass();
4471 // The URL to use for resource changes
4472 if (!isset($config->resourceurl)) {
4473 $config->resourceurl = '/course/rest.php';
4476 // The URL to use for section changes
4477 if (!isset($config->sectionurl)) {
4478 $config->sectionurl = '/course/rest.php';
4481 // Any additional parameters which need to be included on page submission
4482 if (!isset($config->pageparams)) {
4483 $config->pageparams = array();
4486 // Include toolboxes
4487 $PAGE->requires->yui_module('moodle-course-toolboxes',
4488 'M.course.init_resource_toolbox',
4489 array(array(
4490 'courseid' => $course->id,
4491 'ajaxurl' => $config->resourceurl,
4492 'config' => $config,
4495 $PAGE->requires->yui_module('moodle-course-toolboxes',
4496 'M.course.init_section_toolbox',
4497 array(array(
4498 'courseid' => $course->id,
4499 'format' => $course->format,
4500 'ajaxurl' => $config->sectionurl,
4501 'config' => $config,
4505 // Include course dragdrop
4506 if ($course->id != SITEID) {
4507 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.core_course.init_section_dragdrop',
4508 array(array(
4509 'courseid' => $course->id,
4510 'ajaxurl' => $config->sectionurl,
4511 'config' => $config,
4512 )), null, true);
4514 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.core_course.init_resource_dragdrop',
4515 array(array(
4516 'courseid' => $course->id,
4517 'ajaxurl' => $config->resourceurl,
4518 'config' => $config,
4519 )), null, true);
4522 // Include blocks dragdrop
4523 $params = array(
4524 'courseid' => $course->id,
4525 'pagetype' => $PAGE->pagetype,
4526 'pagelayout' => $PAGE->pagelayout,
4527 'regions' => $PAGE->blocks->get_regions(),
4529 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4531 // Require various strings for the command toolbox
4532 $PAGE->requires->strings_for_js(array(
4533 'moveleft',
4534 'deletechecktype',
4535 'deletechecktypename',
4536 'show',
4537 'hide',
4538 'groupsnone',
4539 'groupsvisible',
4540 'groupsseparate',
4541 'clicktochangeinbrackets',
4542 'markthistopic',
4543 'markedthistopic',
4544 'move',
4545 'movesection',
4546 ), 'moodle');
4548 // Include format-specific strings
4549 if ($course->id != SITEID) {
4550 $PAGE->requires->strings_for_js(array(
4551 'showfromothers',
4552 'hidefromothers',
4553 ), 'format_' . $course->format);
4556 // For confirming resource deletion we need the name of the module in question
4557 foreach ($modules as $module => $modname) {
4558 $PAGE->requires->string_for_js('pluginname', $module);