Merge branch 'install_23_STABLE' of git://git.moodle.cz/moodle-install into MOODLE_23...
[moodle.git] / course / lib.php
blob045c9e5ba94c1539ca8fea2c08335ec71e4d8c38
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');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
35 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
36 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
37 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
38 define('FRONTPAGENEWS', '0');
39 define('FRONTPAGECOURSELIST', '1');
40 define('FRONTPAGECATEGORYNAMES', '2');
41 define('FRONTPAGETOPICONLY', '3');
42 define('FRONTPAGECATEGORYCOMBO', '4');
43 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
44 define('EXCELROWS', 65535);
45 define('FIRSTUSEDEXCELROW', 3);
47 define('MOD_CLASS_ACTIVITY', 0);
48 define('MOD_CLASS_RESOURCE', 1);
50 function make_log_url($module, $url) {
51 switch ($module) {
52 case 'course':
53 if (strpos($url, 'report/') === 0) {
54 // there is only one report type, course reports are deprecated
55 $url = "/$url";
56 break;
58 case 'file':
59 case 'login':
60 case 'lib':
61 case 'admin':
62 case 'calendar':
63 case 'category':
64 case 'mnet course':
65 if (strpos($url, '../') === 0) {
66 $url = ltrim($url, '.');
67 } else {
68 $url = "/course/$url";
70 break;
71 case 'user':
72 case 'blog':
73 $url = "/$module/$url";
74 break;
75 case 'upload':
76 $url = $url;
77 break;
78 case 'coursetags':
79 $url = '/'.$url;
80 break;
81 case 'library':
82 case '':
83 $url = '/';
84 break;
85 case 'message':
86 $url = "/message/$url";
87 break;
88 case 'notes':
89 $url = "/notes/$url";
90 break;
91 case 'tag':
92 $url = "/tag/$url";
93 break;
94 case 'role':
95 $url = '/'.$url;
96 break;
97 default:
98 $url = "/mod/$module/$url";
99 break;
102 //now let's sanitise urls - there might be some ugly nasties:-(
103 $parts = explode('?', $url);
104 $script = array_shift($parts);
105 if (strpos($script, 'http') === 0) {
106 $script = clean_param($script, PARAM_URL);
107 } else {
108 $script = clean_param($script, PARAM_PATH);
111 $query = '';
112 if ($parts) {
113 $query = implode('', $parts);
114 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
115 $parts = explode('&', $query);
116 $eq = urlencode('=');
117 foreach ($parts as $key=>$part) {
118 $part = urlencode(urldecode($part));
119 $part = str_replace($eq, '=', $part);
120 $parts[$key] = $part;
122 $query = '?'.implode('&amp;', $parts);
125 return $script.$query;
129 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
130 $modname="", $modid=0, $modaction="", $groupid=0) {
131 global $CFG, $DB;
133 // It is assumed that $date is the GMT time of midnight for that day,
134 // and so the next 86400 seconds worth of logs are printed.
136 /// Setup for group handling.
138 // TODO: I don't understand group/context/etc. enough to be able to do
139 // something interesting with it here
140 // What is the context of a remote course?
142 /// If the group mode is separate, and this user does not have editing privileges,
143 /// then only the user's group can be viewed.
144 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
145 // $groupid = get_current_group($course->id);
147 /// If this course doesn't have groups, no groupid can be specified.
148 //else if (!$course->groupmode) {
149 // $groupid = 0;
152 $groupid = 0;
154 $joins = array();
155 $where = '';
157 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
158 FROM {mnet_log} l
159 LEFT JOIN {user} u ON l.userid = u.id
160 WHERE ";
161 $params = array();
163 $where .= "l.hostid = :hostid";
164 $params['hostid'] = $hostid;
166 // TODO: Is 1 really a magic number referring to the sitename?
167 if ($course != SITEID || $modid != 0) {
168 $where .= " AND l.course=:courseid";
169 $params['courseid'] = $course;
172 if ($modname) {
173 $where .= " AND l.module = :modname";
174 $params['modname'] = $modname;
177 if ('site_errors' === $modid) {
178 $where .= " AND ( l.action='error' OR l.action='infected' )";
179 } else if ($modid) {
180 //TODO: This assumes that modids are the same across sites... probably
181 //not true
182 $where .= " AND l.cmid = :modid";
183 $params['modid'] = $modid;
186 if ($modaction) {
187 $firstletter = substr($modaction, 0, 1);
188 if ($firstletter == '-') {
189 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
190 $params['modaction'] = '%'.substr($modaction, 1).'%';
191 } else {
192 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
193 $params['modaction'] = '%'.$modaction.'%';
197 if ($user) {
198 $where .= " AND l.userid = :user";
199 $params['user'] = $user;
202 if ($date) {
203 $enddate = $date + 86400;
204 $where .= " AND l.time > :date AND l.time < :enddate";
205 $params['date'] = $date;
206 $params['enddate'] = $enddate;
209 $result = array();
210 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
211 if(!empty($result['totalcount'])) {
212 $where .= " ORDER BY $order";
213 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
214 } else {
215 $result['logs'] = array();
217 return $result;
220 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
221 $modname="", $modid=0, $modaction="", $groupid=0) {
222 global $DB, $SESSION, $USER;
223 // It is assumed that $date is the GMT time of midnight for that day,
224 // and so the next 86400 seconds worth of logs are printed.
226 /// Setup for group handling.
228 /// If the group mode is separate, and this user does not have editing privileges,
229 /// then only the user's group can be viewed.
230 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
231 if (isset($SESSION->currentgroup[$course->id])) {
232 $groupid = $SESSION->currentgroup[$course->id];
233 } else {
234 $groupid = groups_get_all_groups($course->id, $USER->id);
235 if (is_array($groupid)) {
236 $groupid = array_shift(array_keys($groupid));
237 $SESSION->currentgroup[$course->id] = $groupid;
238 } else {
239 $groupid = 0;
243 /// If this course doesn't have groups, no groupid can be specified.
244 else if (!$course->groupmode) {
245 $groupid = 0;
248 $joins = array();
249 $params = array();
251 if ($course->id != SITEID || $modid != 0) {
252 $joins[] = "l.course = :courseid";
253 $params['courseid'] = $course->id;
256 if ($modname) {
257 $joins[] = "l.module = :modname";
258 $params['modname'] = $modname;
261 if ('site_errors' === $modid) {
262 $joins[] = "( l.action='error' OR l.action='infected' )";
263 } else if ($modid) {
264 $joins[] = "l.cmid = :modid";
265 $params['modid'] = $modid;
268 if ($modaction) {
269 $firstletter = substr($modaction, 0, 1);
270 if ($firstletter == '-') {
271 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
272 $params['modaction'] = '%'.substr($modaction, 1).'%';
273 } else {
274 $joins[] = $DB->sql_like('l.action', ':modaction', false);
275 $params['modaction'] = '%'.$modaction.'%';
280 /// Getting all members of a group.
281 if ($groupid and !$user) {
282 if ($gusers = groups_get_members($groupid)) {
283 $gusers = array_keys($gusers);
284 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
285 } else {
286 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
289 else if ($user) {
290 $joins[] = "l.userid = :userid";
291 $params['userid'] = $user;
294 if ($date) {
295 $enddate = $date + 86400;
296 $joins[] = "l.time > :date AND l.time < :enddate";
297 $params['date'] = $date;
298 $params['enddate'] = $enddate;
301 $selector = implode(' AND ', $joins);
303 $totalcount = 0; // Initialise
304 $result = array();
305 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
306 $result['totalcount'] = $totalcount;
307 return $result;
311 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
312 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
314 global $CFG, $DB, $OUTPUT;
316 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
317 $modname, $modid, $modaction, $groupid)) {
318 echo $OUTPUT->notification("No logs found!");
319 echo $OUTPUT->footer();
320 exit;
323 $courses = array();
325 if ($course->id == SITEID) {
326 $courses[0] = '';
327 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
328 foreach ($ccc as $cc) {
329 $courses[$cc->id] = $cc->shortname;
332 } else {
333 $courses[$course->id] = $course->shortname;
336 $totalcount = $logs['totalcount'];
337 $count=0;
338 $ldcache = array();
339 $tt = getdate(time());
340 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
342 $strftimedatetime = get_string("strftimedatetime");
344 echo "<div class=\"info\">\n";
345 print_string("displayingrecords", "", $totalcount);
346 echo "</div>\n";
348 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
350 $table = new html_table();
351 $table->classes = array('logtable','generalbox');
352 $table->align = array('right', 'left', 'left');
353 $table->head = array(
354 get_string('time'),
355 get_string('ip_address'),
356 get_string('fullnameuser'),
357 get_string('action'),
358 get_string('info')
360 $table->data = array();
362 if ($course->id == SITEID) {
363 array_unshift($table->align, 'left');
364 array_unshift($table->head, get_string('course'));
367 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
368 if (empty($logs['logs'])) {
369 $logs['logs'] = array();
372 foreach ($logs['logs'] as $log) {
374 if (isset($ldcache[$log->module][$log->action])) {
375 $ld = $ldcache[$log->module][$log->action];
376 } else {
377 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
378 $ldcache[$log->module][$log->action] = $ld;
380 if ($ld && is_numeric($log->info)) {
381 // ugly hack to make sure fullname is shown correctly
382 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
383 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
384 } else {
385 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
389 //Filter log->info
390 $log->info = format_string($log->info);
392 // If $log->url has been trimmed short by the db size restriction
393 // code in add_to_log, keep a note so we don't add a link to a broken url
394 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
396 $row = array();
397 if ($course->id == SITEID) {
398 if (empty($log->course)) {
399 $row[] = get_string('site');
400 } else {
401 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
405 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
407 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
408 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
410 $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))));
412 $displayaction="$log->module $log->action";
413 if ($brokenurl) {
414 $row[] = $displayaction;
415 } else {
416 $link = make_log_url($log->module,$log->url);
417 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
419 $row[] = $log->info;
420 $table->data[] = $row;
423 echo html_writer::table($table);
424 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
428 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
429 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
431 global $CFG, $DB, $OUTPUT;
433 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
434 $modname, $modid, $modaction, $groupid)) {
435 echo $OUTPUT->notification("No logs found!");
436 echo $OUTPUT->footer();
437 exit;
440 if ($course->id == SITEID) {
441 $courses[0] = '';
442 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
443 foreach ($ccc as $cc) {
444 $courses[$cc->id] = $cc->shortname;
449 $totalcount = $logs['totalcount'];
450 $count=0;
451 $ldcache = array();
452 $tt = getdate(time());
453 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
455 $strftimedatetime = get_string("strftimedatetime");
457 echo "<div class=\"info\">\n";
458 print_string("displayingrecords", "", $totalcount);
459 echo "</div>\n";
461 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
463 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
464 echo "<tr>";
465 if ($course->id == SITEID) {
466 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
468 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
469 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
470 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
471 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
472 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
473 echo "</tr>\n";
475 if (empty($logs['logs'])) {
476 echo "</table>\n";
477 return;
480 $row = 1;
481 foreach ($logs['logs'] as $log) {
483 $log->info = $log->coursename;
484 $row = ($row + 1) % 2;
486 if (isset($ldcache[$log->module][$log->action])) {
487 $ld = $ldcache[$log->module][$log->action];
488 } else {
489 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
490 $ldcache[$log->module][$log->action] = $ld;
492 if (0 && $ld && !empty($log->info)) {
493 // ugly hack to make sure fullname is shown correctly
494 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
495 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
496 } else {
497 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
501 //Filter log->info
502 $log->info = format_string($log->info);
504 echo '<tr class="r'.$row.'">';
505 if ($course->id == SITEID) {
506 $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
507 echo "<td class=\"r$row c0\" >\n";
508 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
509 echo "</td>\n";
511 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
512 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
513 echo "<td class=\"r$row c2\" >\n";
514 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
515 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
516 echo "</td>\n";
517 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
518 echo "<td class=\"r$row c3\" >\n";
519 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
520 echo "</td>\n";
521 echo "<td class=\"r$row c4\">\n";
522 echo $log->action .': '.$log->module;
523 echo "</td>\n";;
524 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
525 echo "</tr>\n";
527 echo "</table>\n";
529 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
533 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
534 $modid, $modaction, $groupid) {
535 global $DB, $CFG;
537 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
538 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
540 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
541 $modname, $modid, $modaction, $groupid)) {
542 return false;
545 $courses = array();
547 if ($course->id == SITEID) {
548 $courses[0] = '';
549 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
550 foreach ($ccc as $cc) {
551 $courses[$cc->id] = $cc->shortname;
554 } else {
555 $courses[$course->id] = $course->shortname;
558 $count=0;
559 $ldcache = array();
560 $tt = getdate(time());
561 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
563 $strftimedatetime = get_string("strftimedatetime");
565 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
566 $filename .= '.txt';
567 header("Content-Type: application/download\n");
568 header("Content-Disposition: attachment; filename=\"$filename\"");
569 header("Expires: 0");
570 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
571 header("Pragma: public");
573 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
574 echo $text."\n";
576 if (empty($logs['logs'])) {
577 return true;
580 foreach ($logs['logs'] as $log) {
581 if (isset($ldcache[$log->module][$log->action])) {
582 $ld = $ldcache[$log->module][$log->action];
583 } else {
584 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
585 $ldcache[$log->module][$log->action] = $ld;
587 if ($ld && is_numeric($log->info)) {
588 // ugly hack to make sure fullname is shown correctly
589 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
590 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
591 } else {
592 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
596 //Filter log->info
597 $log->info = format_string($log->info);
598 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
600 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
601 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
602 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
603 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
604 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
605 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
606 $text = implode("\t", $row);
607 echo $text." \n";
609 return true;
613 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
614 $modid, $modaction, $groupid) {
616 global $CFG, $DB;
618 require_once("$CFG->libdir/excellib.class.php");
620 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
621 $modname, $modid, $modaction, $groupid)) {
622 return false;
625 $courses = array();
627 if ($course->id == SITEID) {
628 $courses[0] = '';
629 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
630 foreach ($ccc as $cc) {
631 $courses[$cc->id] = $cc->shortname;
634 } else {
635 $courses[$course->id] = $course->shortname;
638 $count=0;
639 $ldcache = array();
640 $tt = getdate(time());
641 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
643 $strftimedatetime = get_string("strftimedatetime");
645 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
646 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
647 $filename .= '.xls';
649 $workbook = new MoodleExcelWorkbook('-');
650 $workbook->send($filename);
652 $worksheet = array();
653 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
654 get_string('fullnameuser'), get_string('action'), get_string('info'));
656 // Creating worksheets
657 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
658 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
659 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
660 $worksheet[$wsnumber]->set_column(1, 1, 30);
661 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
662 userdate(time(), $strftimedatetime));
663 $col = 0;
664 foreach ($headers as $item) {
665 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
666 $col++;
670 if (empty($logs['logs'])) {
671 $workbook->close();
672 return true;
675 $formatDate =& $workbook->add_format();
676 $formatDate->set_num_format(get_string('log_excel_date_format'));
678 $row = FIRSTUSEDEXCELROW;
679 $wsnumber = 1;
680 $myxls =& $worksheet[$wsnumber];
681 foreach ($logs['logs'] as $log) {
682 if (isset($ldcache[$log->module][$log->action])) {
683 $ld = $ldcache[$log->module][$log->action];
684 } else {
685 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
686 $ldcache[$log->module][$log->action] = $ld;
688 if ($ld && is_numeric($log->info)) {
689 // ugly hack to make sure fullname is shown correctly
690 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
691 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
692 } else {
693 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
697 // Filter log->info
698 $log->info = format_string($log->info);
699 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
701 if ($nroPages>1) {
702 if ($row > EXCELROWS) {
703 $wsnumber++;
704 $myxls =& $worksheet[$wsnumber];
705 $row = FIRSTUSEDEXCELROW;
709 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
711 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
712 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
713 $myxls->write($row, 2, $log->ip, '');
714 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
715 $myxls->write($row, 3, $fullname, '');
716 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
717 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
718 $myxls->write($row, 5, $log->info, '');
720 $row++;
723 $workbook->close();
724 return true;
727 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
728 $modid, $modaction, $groupid) {
730 global $CFG, $DB;
732 require_once("$CFG->libdir/odslib.class.php");
734 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
735 $modname, $modid, $modaction, $groupid)) {
736 return false;
739 $courses = array();
741 if ($course->id == SITEID) {
742 $courses[0] = '';
743 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
744 foreach ($ccc as $cc) {
745 $courses[$cc->id] = $cc->shortname;
748 } else {
749 $courses[$course->id] = $course->shortname;
752 $count=0;
753 $ldcache = array();
754 $tt = getdate(time());
755 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
757 $strftimedatetime = get_string("strftimedatetime");
759 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
760 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
761 $filename .= '.ods';
763 $workbook = new MoodleODSWorkbook('-');
764 $workbook->send($filename);
766 $worksheet = array();
767 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
768 get_string('fullnameuser'), get_string('action'), get_string('info'));
770 // Creating worksheets
771 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
772 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
773 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
774 $worksheet[$wsnumber]->set_column(1, 1, 30);
775 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
776 userdate(time(), $strftimedatetime));
777 $col = 0;
778 foreach ($headers as $item) {
779 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
780 $col++;
784 if (empty($logs['logs'])) {
785 $workbook->close();
786 return true;
789 $formatDate =& $workbook->add_format();
790 $formatDate->set_num_format(get_string('log_excel_date_format'));
792 $row = FIRSTUSEDEXCELROW;
793 $wsnumber = 1;
794 $myxls =& $worksheet[$wsnumber];
795 foreach ($logs['logs'] as $log) {
796 if (isset($ldcache[$log->module][$log->action])) {
797 $ld = $ldcache[$log->module][$log->action];
798 } else {
799 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
800 $ldcache[$log->module][$log->action] = $ld;
802 if ($ld && is_numeric($log->info)) {
803 // ugly hack to make sure fullname is shown correctly
804 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
805 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
806 } else {
807 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
811 // Filter log->info
812 $log->info = format_string($log->info);
813 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
815 if ($nroPages>1) {
816 if ($row > EXCELROWS) {
817 $wsnumber++;
818 $myxls =& $worksheet[$wsnumber];
819 $row = FIRSTUSEDEXCELROW;
823 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
825 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
826 $myxls->write_date($row, 1, $log->time);
827 $myxls->write_string($row, 2, $log->ip);
828 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
829 $myxls->write_string($row, 3, $fullname);
830 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
831 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
832 $myxls->write_string($row, 5, $log->info);
834 $row++;
837 $workbook->close();
838 return true;
842 function print_overview($courses, array $remote_courses=array()) {
843 global $CFG, $USER, $DB, $OUTPUT;
845 $htmlarray = array();
846 if ($modules = $DB->get_records('modules')) {
847 foreach ($modules as $mod) {
848 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
849 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
850 $fname = $mod->name.'_print_overview';
851 if (function_exists($fname)) {
852 $fname($courses,$htmlarray);
857 foreach ($courses as $course) {
858 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
859 echo $OUTPUT->box_start('coursebox');
860 // decode &amp;'s. format_string above will have encoded them and html_writer will encode again when it processed the title
861 // attribute leading to double encoding.
862 $attributes = array('title' => str_replace('&amp;', '&', $fullname));
863 if (empty($course->visible)) {
864 $attributes['class'] = 'dimmed';
866 echo $OUTPUT->heading(html_writer::link(
867 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
868 if (array_key_exists($course->id,$htmlarray)) {
869 foreach ($htmlarray[$course->id] as $modname => $html) {
870 echo $html;
873 echo $OUTPUT->box_end();
876 if (!empty($remote_courses)) {
877 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
879 foreach ($remote_courses as $course) {
880 echo $OUTPUT->box_start('coursebox');
881 $attributes = array('title' => s($course->fullname));
882 echo $OUTPUT->heading(html_writer::link(
883 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
884 format_string($course->shortname),
885 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
886 echo $OUTPUT->box_end();
892 * This function trawls through the logs looking for
893 * anything new since the user's last login
895 function print_recent_activity($course) {
896 // $course is an object
897 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
899 $context = get_context_instance(CONTEXT_COURSE, $course->id);
901 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
903 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
905 if (!isguestuser()) {
906 if (!empty($USER->lastcourseaccess[$course->id])) {
907 if ($USER->lastcourseaccess[$course->id] > $timestart) {
908 $timestart = $USER->lastcourseaccess[$course->id];
913 echo '<div class="activitydate">';
914 echo get_string('activitysince', '', userdate($timestart));
915 echo '</div>';
916 echo '<div class="activityhead">';
918 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
920 echo "</div>\n";
922 $content = false;
924 /// Firstly, have there been any new enrolments?
926 $users = get_recent_enrolments($course->id, $timestart);
928 //Accessibility: new users now appear in an <OL> list.
929 if ($users) {
930 echo '<div class="newusers">';
931 echo $OUTPUT->heading(get_string("newusers").':', 3);
932 $content = true;
933 echo "<ol class=\"list\">\n";
934 foreach ($users as $user) {
935 $fullname = fullname($user, $viewfullnames);
936 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
938 echo "</ol>\n</div>\n";
941 /// Next, have there been any modifications to the course structure?
943 $modinfo = get_fast_modinfo($course);
945 $changelist = array();
947 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
948 module = 'course' AND
949 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
950 array($timestart, $course->id), "id ASC");
952 if ($logs) {
953 $actions = array('add mod', 'update mod', 'delete mod');
954 $newgones = array(); // added and later deleted items
955 foreach ($logs as $key => $log) {
956 if (!in_array($log->action, $actions)) {
957 continue;
959 $info = explode(' ', $log->info);
961 // note: in most cases I replaced hardcoding of label with use of
962 // $cm->has_view() but it was not possible to do this here because
963 // we don't necessarily have the $cm for it
964 if ($info[0] == 'label') { // Labels are ignored in recent activity
965 continue;
968 if (count($info) != 2) {
969 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
970 continue;
973 $modname = $info[0];
974 $instanceid = $info[1];
976 if ($log->action == 'delete mod') {
977 // unfortunately we do not know if the mod was visible
978 if (!array_key_exists($log->info, $newgones)) {
979 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
980 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
982 } else {
983 if (!isset($modinfo->instances[$modname][$instanceid])) {
984 if ($log->action == 'add mod') {
985 // do not display added and later deleted activities
986 $newgones[$log->info] = true;
988 continue;
990 $cm = $modinfo->instances[$modname][$instanceid];
991 if (!$cm->uservisible) {
992 continue;
995 if ($log->action == 'add mod') {
996 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
997 $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>");
999 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1000 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1001 $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>");
1007 if (!empty($changelist)) {
1008 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1009 $content = true;
1010 foreach ($changelist as $changeinfo => $change) {
1011 echo '<p class="activity">'.$change['text'].'</p>';
1015 /// Now display new things from each module
1017 $usedmodules = array();
1018 foreach($modinfo->cms as $cm) {
1019 if (isset($usedmodules[$cm->modname])) {
1020 continue;
1022 if (!$cm->uservisible) {
1023 continue;
1025 $usedmodules[$cm->modname] = $cm->modname;
1028 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1029 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1030 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1031 $print_recent_activity = $modname.'_print_recent_activity';
1032 if (function_exists($print_recent_activity)) {
1033 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1034 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1036 } else {
1037 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1041 if (! $content) {
1042 echo '<p class="message">'.get_string('nothingnew').'</p>';
1047 * For a given course, returns an array of course activity objects
1048 * Each item in the array contains he following properties:
1050 function get_array_of_activities($courseid) {
1051 // cm - course module id
1052 // mod - name of the module (eg forum)
1053 // section - the number of the section (eg week or topic)
1054 // name - the name of the instance
1055 // visible - is the instance visible or not
1056 // groupingid - grouping id
1057 // groupmembersonly - is this instance visible to group members only
1058 // extra - contains extra string to include in any link
1059 global $CFG, $DB;
1060 if(!empty($CFG->enableavailability)) {
1061 require_once($CFG->libdir.'/conditionlib.php');
1064 $course = $DB->get_record('course', array('id'=>$courseid));
1066 if (empty($course)) {
1067 throw new moodle_exception('courseidnotfound');
1070 $mod = array();
1072 $rawmods = get_course_mods($courseid);
1073 if (empty($rawmods)) {
1074 return $mod; // always return array
1077 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1078 foreach ($sections as $section) {
1079 if (!empty($section->sequence)) {
1080 $sequence = explode(",", $section->sequence);
1081 foreach ($sequence as $seq) {
1082 if (empty($rawmods[$seq])) {
1083 continue;
1085 $mod[$seq] = new stdClass();
1086 $mod[$seq]->id = $rawmods[$seq]->instance;
1087 $mod[$seq]->cm = $rawmods[$seq]->id;
1088 $mod[$seq]->mod = $rawmods[$seq]->modname;
1090 // Oh dear. Inconsistent names left here for backward compatibility.
1091 $mod[$seq]->section = $section->section;
1092 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1094 $mod[$seq]->module = $rawmods[$seq]->module;
1095 $mod[$seq]->added = $rawmods[$seq]->added;
1096 $mod[$seq]->score = $rawmods[$seq]->score;
1097 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1098 $mod[$seq]->visible = $rawmods[$seq]->visible;
1099 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1100 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1101 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1102 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1103 $mod[$seq]->indent = $rawmods[$seq]->indent;
1104 $mod[$seq]->completion = $rawmods[$seq]->completion;
1105 $mod[$seq]->extra = "";
1106 $mod[$seq]->completiongradeitemnumber =
1107 $rawmods[$seq]->completiongradeitemnumber;
1108 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1109 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1110 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1111 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1112 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1113 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1114 if (!empty($CFG->enableavailability)) {
1115 condition_info::fill_availability_conditions($rawmods[$seq]);
1116 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1117 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1120 $modname = $mod[$seq]->mod;
1121 $functionname = $modname."_get_coursemodule_info";
1123 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1124 continue;
1127 include_once("$CFG->dirroot/mod/$modname/lib.php");
1129 if ($hasfunction = function_exists($functionname)) {
1130 if ($info = $functionname($rawmods[$seq])) {
1131 if (!empty($info->icon)) {
1132 $mod[$seq]->icon = $info->icon;
1134 if (!empty($info->iconcomponent)) {
1135 $mod[$seq]->iconcomponent = $info->iconcomponent;
1137 if (!empty($info->name)) {
1138 $mod[$seq]->name = $info->name;
1140 if ($info instanceof cached_cm_info) {
1141 // When using cached_cm_info you can include three new fields
1142 // that aren't available for legacy code
1143 if (!empty($info->content)) {
1144 $mod[$seq]->content = $info->content;
1146 if (!empty($info->extraclasses)) {
1147 $mod[$seq]->extraclasses = $info->extraclasses;
1149 if (!empty($info->iconurl)) {
1150 $mod[$seq]->iconurl = $info->iconurl;
1152 if (!empty($info->onclick)) {
1153 $mod[$seq]->onclick = $info->onclick;
1155 if (!empty($info->customdata)) {
1156 $mod[$seq]->customdata = $info->customdata;
1158 } else {
1159 // When using a stdclass, the (horrible) deprecated ->extra field
1160 // is available for BC
1161 if (!empty($info->extra)) {
1162 $mod[$seq]->extra = $info->extra;
1167 // When there is no modname_get_coursemodule_info function,
1168 // but showdescriptions is enabled, then we use the 'intro'
1169 // and 'introformat' fields in the module table
1170 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1171 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1172 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1173 // Set content from intro and introformat. Filters are disabled
1174 // because we filter it with format_text at display time
1175 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1176 $modvalues, $rawmods[$seq]->id, false);
1178 // To save making another query just below, put name in here
1179 $mod[$seq]->name = $modvalues->name;
1182 if (!isset($mod[$seq]->name)) {
1183 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1186 // Minimise the database size by unsetting default options when they are
1187 // 'empty'. This list corresponds to code in the cm_info constructor.
1188 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1189 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1190 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1191 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1192 'completionview', 'completionexpected', 'score', 'showdescription')
1193 as $property) {
1194 if (property_exists($mod[$seq], $property) &&
1195 empty($mod[$seq]->{$property})) {
1196 unset($mod[$seq]->{$property});
1199 // Special case: this value is usually set to null, but may be 0
1200 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1201 is_null($mod[$seq]->completiongradeitemnumber)) {
1202 unset($mod[$seq]->completiongradeitemnumber);
1208 return $mod;
1213 * Returns a number of useful structures for course displays
1215 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1216 global $CFG, $DB, $COURSE;
1218 $mods = array(); // course modules indexed by id
1219 $modnames = array(); // all course module names (except resource!)
1220 $modnamesplural= array(); // all course module names (plural form)
1221 $modnamesused = array(); // course module names used
1223 if ($allmods = $DB->get_records("modules")) {
1224 foreach ($allmods as $mod) {
1225 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1226 continue;
1228 if ($mod->visible) {
1229 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1230 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1233 collatorlib::asort($modnames);
1234 } else {
1235 print_error("nomodules", 'debug');
1238 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1239 $modinfo = get_fast_modinfo($course);
1241 if ($rawmods=$modinfo->cms) {
1242 foreach($rawmods as $mod) { // Index the mods
1243 if (empty($modnames[$mod->modname])) {
1244 continue;
1246 $mods[$mod->id] = $mod;
1247 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1248 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1249 continue;
1251 // Check groupings
1252 if (!groups_course_module_visible($mod)) {
1253 continue;
1255 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1257 if ($modnamesused) {
1258 collatorlib::asort($modnamesused);
1264 * Returns an array of sections for the requested course id
1266 * This function stores the sections against the course id within a staticvar encase
1267 * of subsequent requests. This is used all over + in some standard libs and course
1268 * format callbacks so subsequent requests are a reality.
1270 * Note: Since Moodle 2.3, it is more efficient to get this data by calling
1271 * get_fast_modinfo, then using $modinfo->get_section_info or get_section_info_all.
1273 * @staticvar array $coursesections
1274 * @param int $courseid
1275 * @return array Array of sections
1277 function get_all_sections($courseid) {
1278 global $DB;
1279 static $coursesections = array();
1280 if (!array_key_exists($courseid, $coursesections)) {
1281 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1282 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
1283 'availablefrom, availableuntil, showavailability, groupingid');
1285 return $coursesections[$courseid];
1289 * Set highlighted section. Only one section can be highlighted at the time.
1291 * @param int $courseid course id
1292 * @param int $marker highlight section with this number, 0 means remove higlightin
1293 * @return void
1295 function course_set_marker($courseid, $marker) {
1296 global $DB;
1297 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1301 * For a given course section, marks it visible or hidden,
1302 * and does the same for every activity in that section
1304 * @param int $courseid course id
1305 * @param int $sectionnumber The section number to adjust
1306 * @param int $visibility The new visibility
1307 * @return array A list of resources which were hidden in the section
1309 function set_section_visible($courseid, $sectionnumber, $visibility) {
1310 global $DB;
1312 $resourcestotoggle = array();
1313 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1314 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1315 if (!empty($section->sequence)) {
1316 $modules = explode(",", $section->sequence);
1317 foreach ($modules as $moduleid) {
1318 set_coursemodule_visible($moduleid, $visibility, true);
1321 rebuild_course_cache($courseid);
1323 // Determine which modules are visible for AJAX update
1324 if (!empty($modules)) {
1325 list($insql, $params) = $DB->get_in_or_equal($modules);
1326 $select = 'id ' . $insql . ' AND visible = ?';
1327 array_push($params, $visibility);
1328 if (!$visibility) {
1329 $select .= ' AND visibleold = 1';
1331 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1334 return $resourcestotoggle;
1338 * Obtains shared data that is used in print_section when displaying a
1339 * course-module entry.
1341 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1343 * This data is also used in other areas of the code.
1344 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1345 * @param object $course Moodle course object
1346 * @return array An array with the following values in this order:
1347 * $content (optional extra content for after link),
1348 * $instancename (text of link)
1350 function get_print_section_cm_text(cm_info $cm, $course) {
1351 global $OUTPUT;
1353 // Get content from modinfo if specified. Content displays either
1354 // in addition to the standard link (below), or replaces it if
1355 // the link is turned off by setting ->url to null.
1356 if (($content = $cm->get_content()) !== '') {
1357 // Improve filter performance by preloading filter setttings for all
1358 // activities on the course (this does nothing if called multiple
1359 // times)
1360 filter_preload_activities($cm->get_modinfo());
1362 // Get module context
1363 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1364 $labelformatoptions = new stdClass();
1365 $labelformatoptions->noclean = true;
1366 $labelformatoptions->overflowdiv = true;
1367 $labelformatoptions->context = $modulecontext;
1368 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1369 } else {
1370 $content = '';
1373 // Get course context
1374 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1375 $stringoptions = new stdClass;
1376 $stringoptions->context = $coursecontext;
1377 $instancename = format_string($cm->name, true, $stringoptions);
1378 return array($content, $instancename);
1382 * Prints a section full of activity modules
1384 * @param stdClass $course The course
1385 * @param stdClass $section The section
1386 * @param array $mods The modules in the section
1387 * @param array $modnamesused An array containing the list of modules and their names
1388 * @param bool $absolute All links are absolute
1389 * @param string $width Width of the container
1390 * @param bool $hidecompletion Hide completion status
1391 * @param int $sectionreturn The section to return to
1392 * @return void
1394 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1395 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1397 static $initialised;
1399 static $groupbuttons;
1400 static $groupbuttonslink;
1401 static $isediting;
1402 static $ismoving;
1403 static $strmovehere;
1404 static $strmovefull;
1405 static $strunreadpostsone;
1406 static $modulenames;
1408 if (!isset($initialised)) {
1409 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1410 $groupbuttonslink = (!$course->groupmodeforce);
1411 $isediting = $PAGE->user_is_editing();
1412 $ismoving = $isediting && ismoving($course->id);
1413 if ($ismoving) {
1414 $strmovehere = get_string("movehere");
1415 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1417 $modulenames = array();
1418 $initialised = true;
1421 $modinfo = get_fast_modinfo($course);
1422 $completioninfo = new completion_info($course);
1424 //Accessibility: replace table with list <ul>, but don't output empty list.
1425 if (!empty($section->sequence)) {
1427 // Fix bug #5027, don't want style=\"width:$width\".
1428 echo "<ul class=\"section img-text\">\n";
1429 $sectionmods = explode(",", $section->sequence);
1431 foreach ($sectionmods as $modnumber) {
1432 if (empty($mods[$modnumber])) {
1433 continue;
1437 * @var cm_info
1439 $mod = $mods[$modnumber];
1441 if ($ismoving and $mod->id == $USER->activitycopy) {
1442 // do not display moving mod
1443 continue;
1446 if (isset($modinfo->cms[$modnumber])) {
1447 // We can continue (because it will not be displayed at all)
1448 // if:
1449 // 1) The activity is not visible to users
1450 // and
1451 // 2a) The 'showavailability' option is not set (if that is set,
1452 // we need to display the activity so we can show
1453 // availability info)
1454 // or
1455 // 2b) The 'availableinfo' is empty, i.e. the activity was
1456 // hidden in a way that leaves no info, such as using the
1457 // eye icon.
1458 if (!$modinfo->cms[$modnumber]->uservisible &&
1459 (empty($modinfo->cms[$modnumber]->showavailability) ||
1460 empty($modinfo->cms[$modnumber]->availableinfo))) {
1461 // visibility shortcut
1462 continue;
1464 } else {
1465 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1466 // module not installed
1467 continue;
1469 if (!coursemodule_visible_for_user($mod) &&
1470 empty($mod->showavailability)) {
1471 // full visibility check
1472 continue;
1476 if (!isset($modulenames[$mod->modname])) {
1477 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1479 $modulename = $modulenames[$mod->modname];
1481 // In some cases the activity is visible to user, but it is
1482 // dimmed. This is done if viewhiddenactivities is true and if:
1483 // 1. the activity is not visible, or
1484 // 2. the activity has dates set which do not include current, or
1485 // 3. the activity has any other conditions set (regardless of whether
1486 // current user meets them)
1487 $modcontext = context_module::instance($mod->id);
1488 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1489 $accessiblebutdim = false;
1490 $conditionalhidden = false;
1491 if ($canviewhidden) {
1492 $accessiblebutdim = !$mod->visible;
1493 if (!empty($CFG->enableavailability)) {
1494 $conditionalhidden = $mod->availablefrom > time() ||
1495 ($mod->availableuntil && $mod->availableuntil < time()) ||
1496 count($mod->conditionsgrade) > 0 ||
1497 count($mod->conditionscompletion) > 0;
1499 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1502 $liclasses = array();
1503 $liclasses[] = 'activity';
1504 $liclasses[] = $mod->modname;
1505 $liclasses[] = 'modtype_'.$mod->modname;
1506 $extraclasses = $mod->get_extra_classes();
1507 if ($extraclasses) {
1508 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1510 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1511 if ($ismoving) {
1512 echo '<a title="'.$strmovefull.'"'.
1513 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1514 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1515 ' alt="'.$strmovehere.'" /></a><br />
1519 $classes = array('mod-indent');
1520 if (!empty($mod->indent)) {
1521 $classes[] = 'mod-indent-'.$mod->indent;
1522 if ($mod->indent > 15) {
1523 $classes[] = 'mod-indent-huge';
1526 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1528 // Get data about this course-module
1529 list($content, $instancename) =
1530 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1532 //Accessibility: for files get description via icon, this is very ugly hack!
1533 $altname = '';
1534 $altname = $mod->modfullname;
1535 // Avoid unnecessary duplication: if e.g. a forum name already
1536 // includes the word forum (or Forum, etc) then it is unhelpful
1537 // to include that in the accessible description that is added.
1538 if (false !== strpos(textlib::strtolower($instancename),
1539 textlib::strtolower($altname))) {
1540 $altname = '';
1542 // File type after name, for alphabetic lists (screen reader).
1543 if ($altname) {
1544 $altname = get_accesshide(' '.$altname);
1547 // We may be displaying this just in order to show information
1548 // about visibility, without the actual link
1549 $contentpart = '';
1550 if ($mod->uservisible) {
1551 // Nope - in this case the link is fully working for user
1552 $linkclasses = '';
1553 $textclasses = '';
1554 if ($accessiblebutdim) {
1555 $linkclasses .= ' dimmed';
1556 $textclasses .= ' dimmed_text';
1557 if ($conditionalhidden) {
1558 $linkclasses .= ' conditionalhidden';
1559 $textclasses .= ' conditionalhidden';
1561 $accesstext = '<span class="accesshide">'.
1562 get_string('hiddenfromstudents').': </span>';
1563 } else {
1564 $accesstext = '';
1566 if ($linkclasses) {
1567 $linkcss = 'class="' . trim($linkclasses) . '" ';
1568 } else {
1569 $linkcss = '';
1571 if ($textclasses) {
1572 $textcss = 'class="' . trim($textclasses) . '" ';
1573 } else {
1574 $textcss = '';
1577 // Get on-click attribute value if specified
1578 $onclick = $mod->get_on_click();
1579 if ($onclick) {
1580 $onclick = ' onclick="' . $onclick . '"';
1583 if ($url = $mod->get_url()) {
1584 // Display link itself
1585 echo '<a ' . $linkcss . $mod->extra . $onclick .
1586 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1587 '" class="activityicon" alt="' . $modulename . '" /> ' .
1588 $accesstext . '<span class="instancename">' .
1589 $instancename . $altname . '</span></a>';
1591 // If specified, display extra content after link
1592 if ($content) {
1593 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1594 '">' . $content . '</div>';
1596 } else {
1597 // No link, so display only content
1598 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1599 $accesstext . $content . '</div>';
1602 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1603 $groupings = groups_get_all_groupings($course->id);
1604 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1606 } else {
1607 $textclasses = $extraclasses;
1608 $textclasses .= ' dimmed_text';
1609 if ($textclasses) {
1610 $textcss = 'class="' . trim($textclasses) . '" ';
1611 } else {
1612 $textcss = '';
1614 $accesstext = '<span class="accesshide">' .
1615 get_string('notavailableyet', 'condition') .
1616 ': </span>';
1618 if ($url = $mod->get_url()) {
1619 // Display greyed-out text of link
1620 echo '<div ' . $textcss . $mod->extra .
1621 ' >' . '<img src="' . $mod->get_icon_url() .
1622 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1623 '</span></div>';
1625 // Do not display content after link when it is greyed out like this.
1626 } else {
1627 // No link, so display only content (also greyed)
1628 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1629 $accesstext . $content . '</div>';
1633 // Module can put text after the link (e.g. forum unread)
1634 echo $mod->get_after_link();
1636 // If there is content but NO link (eg label), then display the
1637 // content here (BEFORE any icons). In this case cons must be
1638 // displayed after the content so that it makes more sense visually
1639 // and for accessibility reasons, e.g. if you have a one-line label
1640 // it should work similarly (at least in terms of ordering) to an
1641 // activity.
1642 if (empty($url)) {
1643 echo $contentpart;
1646 if ($isediting) {
1647 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1648 if (! $mod->groupmodelink = $groupbuttonslink) {
1649 $mod->groupmode = $course->groupmode;
1652 } else {
1653 $mod->groupmode = false;
1655 echo '&nbsp;&nbsp;';
1656 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1657 echo $mod->get_after_edit_icons();
1660 // Completion
1661 $completion = $hidecompletion
1662 ? COMPLETION_TRACKING_NONE
1663 : $completioninfo->is_enabled($mod);
1664 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1665 !isguestuser() && $mod->uservisible) {
1666 $completiondata = $completioninfo->get_data($mod,true);
1667 $completionicon = '';
1668 if ($isediting) {
1669 switch ($completion) {
1670 case COMPLETION_TRACKING_MANUAL :
1671 $completionicon = 'manual-enabled'; break;
1672 case COMPLETION_TRACKING_AUTOMATIC :
1673 $completionicon = 'auto-enabled'; break;
1674 default: // wtf
1676 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1677 switch($completiondata->completionstate) {
1678 case COMPLETION_INCOMPLETE:
1679 $completionicon = 'manual-n'; break;
1680 case COMPLETION_COMPLETE:
1681 $completionicon = 'manual-y'; break;
1683 } else { // Automatic
1684 switch($completiondata->completionstate) {
1685 case COMPLETION_INCOMPLETE:
1686 $completionicon = 'auto-n'; break;
1687 case COMPLETION_COMPLETE:
1688 $completionicon = 'auto-y'; break;
1689 case COMPLETION_COMPLETE_PASS:
1690 $completionicon = 'auto-pass'; break;
1691 case COMPLETION_COMPLETE_FAIL:
1692 $completionicon = 'auto-fail'; break;
1695 if ($completionicon) {
1696 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1697 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1698 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1699 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1700 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1701 $newstate =
1702 $completiondata->completionstate==COMPLETION_COMPLETE
1703 ? COMPLETION_INCOMPLETE
1704 : COMPLETION_COMPLETE;
1705 // In manual mode the icon is a toggle form...
1707 // If this completion state is used by the
1708 // conditional activities system, we need to turn
1709 // off the JS.
1710 if (!empty($CFG->enableavailability) &&
1711 condition_info::completion_value_used_as_condition($course, $mod)) {
1712 $extraclass = ' preventjs';
1713 } else {
1714 $extraclass = '';
1716 echo html_writer::start_tag('form', array(
1717 'class' => 'togglecompletion' . $extraclass,
1718 'method' => 'post',
1719 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1720 echo html_writer::start_tag('div');
1721 echo html_writer::empty_tag('input', array(
1722 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1723 echo html_writer::empty_tag('input', array(
1724 'type' => 'hidden', 'name' => 'modulename',
1725 'value' => $mod->name));
1726 echo html_writer::empty_tag('input', array(
1727 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1728 echo html_writer::empty_tag('input', array(
1729 'type' => 'hidden', 'name' => 'completionstate',
1730 'value' => $newstate));
1731 echo html_writer::empty_tag('input', array(
1732 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle,
1733 'aria-live' => 'polite'));
1734 echo html_writer::end_tag('div');
1735 echo html_writer::end_tag('form');
1736 } else {
1737 // In auto mode, or when editing, the icon is just an image.
1738 echo html_writer::tag('span', html_writer::empty_tag('img', array(
1739 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgalt)),
1740 array('class' => 'autocompletion'));
1745 // If there is content AND a link, then display the content here
1746 // (AFTER any icons). Otherwise it was displayed before
1747 if (!empty($url)) {
1748 echo $contentpart;
1751 // Show availability information (for someone who isn't allowed to
1752 // see the activity itself, or for staff)
1753 if (!$mod->uservisible) {
1754 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1755 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1756 // Don't add availability information if user is not editing and activity is hidden.
1757 if ($mod->visible || $PAGE->user_is_editing()) {
1758 $hidinfoclass = '';
1759 if (!$mod->visible) {
1760 $hidinfoclass = 'hide';
1762 $ci = new condition_info($mod);
1763 $fullinfo = $ci->get_full_information();
1764 if($fullinfo) {
1765 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1766 ? 'userrestriction_visible'
1767 : 'userrestriction_hidden','condition',
1768 $fullinfo).'</div>';
1773 echo html_writer::end_tag('div');
1774 echo html_writer::end_tag('li')."\n";
1777 } elseif ($ismoving) {
1778 echo "<ul class=\"section\">\n";
1781 if ($ismoving) {
1782 echo '<li><a title="'.$strmovefull.'"'.
1783 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1784 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1785 ' alt="'.$strmovehere.'" /></a></li>
1788 if (!empty($section->sequence) || $ismoving) {
1789 echo "</ul><!--class='section'-->\n\n";
1794 * Prints the menus to add activities and resources.
1796 * @param stdClass $course The course
1797 * @param int $section relative section number (field course_sections.section)
1798 * @param array $modnames An array containing the list of modules and their names
1799 * @param bool $vertical Vertical orientation
1800 * @param bool $return Return the menus or send them to output
1801 * @param int $sectionreturn The section to link back to
1802 * @return void|string depending on $return
1804 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false, $sectionreturn=null) {
1805 global $CFG, $OUTPUT;
1807 // check to see if user can add menus
1808 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1809 return false;
1812 // Retrieve all modules with associated metadata
1813 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1815 // We'll sort resources and activities into two lists
1816 $resources = array();
1817 $activities = array();
1819 // We need to add the section section to the link for each module
1820 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1822 foreach ($modules as $module) {
1823 if (isset($module->types)) {
1824 // This module has a subtype
1825 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1826 $subtypes = array();
1827 foreach ($module->types as $subtype) {
1828 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1831 // Sort module subtypes into the list
1832 if (!empty($module->title)) {
1833 // This grouping has a name
1834 if ($module->archetype == MOD_CLASS_RESOURCE) {
1835 $resources[] = array($module->title=>$subtypes);
1836 } else {
1837 $activities[] = array($module->title=>$subtypes);
1839 } else {
1840 // This grouping does not have a name
1841 if ($module->archetype == MOD_CLASS_RESOURCE) {
1842 $resources = array_merge($resources, $subtypes);
1843 } else {
1844 $activities = array_merge($activities, $subtypes);
1847 } else {
1848 // This module has no subtypes
1849 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1850 $resources[$module->link . $sectionlink] = $module->title;
1851 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1852 // System modules cannot be added by user, do not add to dropdown
1853 } else {
1854 $activities[$module->link . $sectionlink] = $module->title;
1859 $straddactivity = get_string('addactivity');
1860 $straddresource = get_string('addresource');
1862 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1864 if (!$vertical) {
1865 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1868 if (!empty($resources)) {
1869 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1870 $select->set_help_icon('resources');
1871 $output .= $OUTPUT->render($select);
1874 if (!empty($activities)) {
1875 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1876 $select->set_help_icon('activities');
1877 $output .= $OUTPUT->render($select);
1880 if (!$vertical) {
1881 $output .= html_writer::end_tag('div');
1884 $output .= html_writer::end_tag('div');
1886 if (course_ajax_enabled($course)) {
1887 $straddeither = get_string('addresourceoractivity');
1888 // The module chooser link
1889 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1890 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1891 $icon = $OUTPUT->pix_icon('t/add', '');
1892 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1893 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1894 $modchooser.= html_writer::end_tag('div');
1895 $modchooser.= html_writer::end_tag('div');
1897 // Wrap the normal output in a noscript div
1898 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1899 if ($usemodchooser) {
1900 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1901 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1902 } else {
1903 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1904 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1905 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1907 $output = $modchooser . $output;
1910 if ($return) {
1911 return $output;
1912 } else {
1913 echo $output;
1918 * Retrieve all metadata for the requested modules
1920 * @param object $course The Course
1921 * @param array $modnames An array containing the list of modules and their
1922 * names
1923 * @param int $sectionreturn The section to return to
1924 * @return array A list of stdClass objects containing metadata about each
1925 * module
1927 function get_module_metadata($course, $modnames, $sectionreturn = null) {
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().'&sr='.$sectionreturn.'&add=';
1939 foreach($modnames as $modname => $modnamestr) {
1940 if (!course_allowed_module($course, $modname)) {
1941 continue;
1943 if (isset($modlist[$course->id][$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 $types = $gettypesfunc();
1960 if (is_array($types) && count($types) > 0) {
1961 $group = new stdClass();
1962 $group->name = $modname;
1963 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1964 foreach($types as $type) {
1965 if ($type->typestr === '--') {
1966 continue;
1968 if (strpos($type->typestr, '--') === 0) {
1969 $group->title = str_replace('--', '', $type->typestr);
1970 continue;
1972 // Set the Sub Type metadata
1973 $subtype = new stdClass();
1974 $subtype->title = $type->typestr;
1975 $subtype->type = str_replace('&amp;', '&', $type->type);
1976 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1977 $subtype->archetype = $type->modclass;
1979 // The group archetype should match the subtype archetypes and all subtypes
1980 // should have the same archetype
1981 $group->archetype = $subtype->archetype;
1983 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1984 $subtype->help = get_string('help' . $subtype->name, $modname);
1986 $subtype->link = $urlbase . $subtype->type;
1987 $group->types[] = $subtype;
1989 $modlist[$course->id][$modname] = $group;
1991 } else {
1992 $module = new stdClass();
1993 $module->title = get_string('modulename', $modname);
1994 $module->name = $modname;
1995 $module->link = $urlbase . $modname;
1996 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1997 $sm = get_string_manager();
1998 if ($sm->string_exists('modulename_help', $modname)) {
1999 $module->help = get_string('modulename_help', $modname);
2000 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
2001 $link = get_string('modulename_link', $modname);
2002 $linktext = get_string('morehelp');
2003 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
2006 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2007 $modlist[$course->id][$modname] = $module;
2009 if (isset($modlist[$course->id][$modname])) {
2010 $return[$modname] = $modlist[$course->id][$modname];
2011 } else {
2012 debugging("Invalid module metadata configuration for {$modname}");
2016 return $return;
2020 * Return the course category context for the category with id $categoryid, except
2021 * that if $categoryid is 0, return the system context.
2023 * @param integer $categoryid a category id or 0.
2024 * @return object the corresponding context
2026 function get_category_or_system_context($categoryid) {
2027 if ($categoryid) {
2028 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
2029 } else {
2030 return get_context_instance(CONTEXT_SYSTEM);
2035 * Gets the child categories of a given courses category. Uses a static cache
2036 * to make repeat calls efficient.
2038 * @param int $parentid the id of a course category.
2039 * @return array all the child course categories.
2041 function get_child_categories($parentid) {
2042 static $allcategories = null;
2044 // only fill in this variable the first time
2045 if (null == $allcategories) {
2046 $allcategories = array();
2048 $categories = get_categories();
2049 foreach ($categories as $category) {
2050 if (empty($allcategories[$category->parent])) {
2051 $allcategories[$category->parent] = array();
2053 $allcategories[$category->parent][] = $category;
2057 if (empty($allcategories[$parentid])) {
2058 return array();
2059 } else {
2060 return $allcategories[$parentid];
2065 * This function recursively travels the categories, building up a nice list
2066 * for display. It also makes an array that list all the parents for each
2067 * category.
2069 * For example, if you have a tree of categories like:
2070 * Miscellaneous (id = 1)
2071 * Subcategory (id = 2)
2072 * Sub-subcategory (id = 4)
2073 * Other category (id = 3)
2074 * Then after calling this function you will have
2075 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2076 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2077 * 3 => 'Other category');
2078 * $parents = array(2 => array(1), 4 => array(1, 2));
2080 * If you specify $requiredcapability, then only categories where the current
2081 * user has that capability will be added to $list, although all categories
2082 * will still be added to $parents, and if you only have $requiredcapability
2083 * in a child category, not the parent, then the child catgegory will still be
2084 * included.
2086 * If you specify the option $excluded, then that category, and all its children,
2087 * are omitted from the tree. This is useful when you are doing something like
2088 * moving categories, where you do not want to allow people to move a category
2089 * to be the child of itself.
2091 * @param array $list For output, accumulates an array categoryid => full category path name
2092 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2093 * @param string/array $requiredcapability if given, only categories where the current
2094 * user has this capability will be added to $list. Can also be an array of capabilities,
2095 * in which case they are all required.
2096 * @param integer $excludeid Omit this category and its children from the lists built.
2097 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2098 * @param string $path For internal use, as part of recursive calls.
2100 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2101 $excludeid = 0, $category = NULL, $path = "") {
2103 // initialize the arrays if needed
2104 if (!is_array($list)) {
2105 $list = array();
2107 if (!is_array($parents)) {
2108 $parents = array();
2111 if (empty($category)) {
2112 // Start at the top level.
2113 $category = new stdClass;
2114 $category->id = 0;
2115 } else {
2116 // This is the excluded category, don't include it.
2117 if ($excludeid > 0 && $excludeid == $category->id) {
2118 return;
2121 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2122 $categoryname = format_string($category->name, true, array('context' => $context));
2124 // Update $path.
2125 if ($path) {
2126 $path = $path.' / '.$categoryname;
2127 } else {
2128 $path = $categoryname;
2131 // Add this category to $list, if the permissions check out.
2132 if (empty($requiredcapability)) {
2133 $list[$category->id] = $path;
2135 } else {
2136 $requiredcapability = (array)$requiredcapability;
2137 if (has_all_capabilities($requiredcapability, $context)) {
2138 $list[$category->id] = $path;
2143 // Add all the children recursively, while updating the parents array.
2144 if ($categories = get_child_categories($category->id)) {
2145 foreach ($categories as $cat) {
2146 if (!empty($category->id)) {
2147 if (isset($parents[$category->id])) {
2148 $parents[$cat->id] = $parents[$category->id];
2150 $parents[$cat->id][] = $category->id;
2152 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2158 * This function generates a structured array of courses and categories.
2160 * The depth of categories is limited by $CFG->maxcategorydepth however there
2161 * is no limit on the number of courses!
2163 * Suitable for use with the course renderers course_category_tree method:
2164 * $renderer = $PAGE->get_renderer('core','course');
2165 * echo $renderer->course_category_tree(get_course_category_tree());
2167 * @global moodle_database $DB
2168 * @param int $id
2169 * @param int $depth
2171 function get_course_category_tree($id = 0, $depth = 0) {
2172 global $DB, $CFG;
2173 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2174 $categories = get_child_categories($id);
2175 $categoryids = array();
2176 foreach ($categories as $key => &$category) {
2177 if (!$category->visible && !$viewhiddencats) {
2178 unset($categories[$key]);
2179 continue;
2181 $categoryids[$category->id] = $category;
2182 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2183 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2184 foreach ($subcategories as $subid=>$subcat) {
2185 $categoryids[$subid] = $subcat;
2187 $category->courses = array();
2191 if ($depth > 0) {
2192 // This is a recursive call so return the required array
2193 return array($categories, $categoryids);
2196 if (empty($categoryids)) {
2197 // No categories available (probably all hidden).
2198 return array();
2201 // The depth is 0 this function has just been called so we can finish it off
2203 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2204 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2205 $sql = "SELECT
2206 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2207 $ccselect
2208 FROM {course} c
2209 $ccjoin
2210 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2211 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2212 // loop throught them
2213 foreach ($courses as $course) {
2214 if ($course->id == SITEID) {
2215 continue;
2217 context_instance_preload($course);
2218 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2219 $categoryids[$course->category]->courses[$course->id] = $course;
2223 return $categories;
2227 * Recursive function to print out all the categories in a nice format
2228 * with or without courses included
2230 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2231 global $CFG;
2233 // maxcategorydepth == 0 meant no limit
2234 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2235 return;
2238 if (!$displaylist) {
2239 make_categories_list($displaylist, $parentslist);
2242 if ($category) {
2243 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2244 print_category_info($category, $depth, $showcourses);
2245 } else {
2246 return; // Don't bother printing children of invisible categories
2249 } else {
2250 $category = new stdClass();
2251 $category->id = "0";
2254 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2255 $countcats = count($categories);
2256 $count = 0;
2257 $first = true;
2258 $last = false;
2259 foreach ($categories as $cat) {
2260 $count++;
2261 if ($count == $countcats) {
2262 $last = true;
2264 $up = $first ? false : true;
2265 $down = $last ? false : true;
2266 $first = false;
2268 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2274 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2276 function make_categories_options() {
2277 make_categories_list($cats,$parents);
2278 foreach ($cats as $key => $value) {
2279 if (array_key_exists($key,$parents)) {
2280 if ($indent = count($parents[$key])) {
2281 for ($i = 0; $i < $indent; $i++) {
2282 $cats[$key] = '&nbsp;'.$cats[$key];
2287 return $cats;
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 * Print courses in category. If category is 0 then all courses are printed.
2471 * @param int|stdClass $category category object or id.
2472 * @return bool true if courses found and printed, else false.
2474 function print_courses($category) {
2475 global $CFG, $OUTPUT;
2477 if (!is_object($category) && $category==0) {
2478 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2479 if (is_array($categories) && count($categories) == 1) {
2480 $category = array_shift($categories);
2481 $courses = get_courses_wmanagers($category->id,
2482 'c.sortorder ASC',
2483 array('summary','summaryformat'));
2484 } else {
2485 $courses = get_courses_wmanagers('all',
2486 'c.sortorder ASC',
2487 array('summary','summaryformat'));
2489 unset($categories);
2490 } else {
2491 $courses = get_courses_wmanagers($category->id,
2492 'c.sortorder ASC',
2493 array('summary','summaryformat'));
2496 if ($courses) {
2497 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2498 foreach ($courses as $course) {
2499 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2500 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2501 echo html_writer::start_tag('li');
2502 print_course($course);
2503 echo html_writer::end_tag('li');
2506 echo html_writer::end_tag('ul');
2507 } else {
2508 echo $OUTPUT->heading(get_string("nocoursesyet"));
2509 $context = get_context_instance(CONTEXT_SYSTEM);
2510 if (has_capability('moodle/course:create', $context)) {
2511 $options = array();
2512 if (!empty($category->id)) {
2513 $options['category'] = $category->id;
2514 } else {
2515 $options['category'] = $CFG->defaultrequestcategory;
2517 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2518 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2519 echo html_writer::end_tag('div');
2520 return false;
2523 return true;
2527 * Print a description of a course, suitable for browsing in a list.
2529 * @param object $course the course object.
2530 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2532 function print_course($course, $highlightterms = '') {
2533 global $CFG, $USER, $DB, $OUTPUT;
2535 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2537 // Rewrite file URLs so that they are correct
2538 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2540 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2541 echo html_writer::start_tag('div', array('class'=>'info'));
2542 echo html_writer::start_tag('h3', array('class'=>'name'));
2544 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2546 $coursename = get_course_display_name_for_list($course);
2547 $linktext = highlight($highlightterms, format_string($coursename));
2548 $linkparams = array('title'=>get_string('entercourse'));
2549 if (empty($course->visible)) {
2550 $linkparams['class'] = 'dimmed';
2552 echo html_writer::link($linkhref, $linktext, $linkparams);
2553 echo html_writer::end_tag('h3');
2555 /// first find all roles that are supposed to be displayed
2556 if (!empty($CFG->coursecontact)) {
2557 $managerroles = explode(',', $CFG->coursecontact);
2558 $namesarray = array();
2559 $rusers = array();
2561 if (!isset($course->managers)) {
2562 $rusers = get_role_users($managerroles, $context, true,
2563 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2564 r.name AS rolename, r.sortorder, r.id AS roleid',
2565 'r.sortorder ASC, u.lastname ASC');
2566 } else {
2567 // use the managers array if we have it for perf reasosn
2568 // populate the datastructure like output of get_role_users();
2569 foreach ($course->managers as $manager) {
2570 $u = new stdClass();
2571 $u = $manager->user;
2572 $u->roleid = $manager->roleid;
2573 $u->rolename = $manager->rolename;
2575 $rusers[] = $u;
2579 /// Rename some of the role names if needed
2580 if (isset($context)) {
2581 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2584 $namesarray = array();
2585 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2586 foreach ($rusers as $ra) {
2587 if (isset($namesarray[$ra->id])) {
2588 // only display a user once with the higest sortorder role
2589 continue;
2592 if (isset($aliasnames[$ra->roleid])) {
2593 $ra->rolename = $aliasnames[$ra->roleid]->name;
2596 $fullname = fullname($ra, $canviewfullnames);
2597 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2598 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2601 if (!empty($namesarray)) {
2602 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2603 foreach ($namesarray as $name) {
2604 echo html_writer::tag('li', $name);
2606 echo html_writer::end_tag('ul');
2609 echo html_writer::end_tag('div'); // End of info div
2611 echo html_writer::start_tag('div', array('class'=>'summary'));
2612 $options = new stdClass();
2613 $options->noclean = true;
2614 $options->para = false;
2615 $options->overflowdiv = true;
2616 if (!isset($course->summaryformat)) {
2617 $course->summaryformat = FORMAT_MOODLE;
2619 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2620 if ($icons = enrol_get_course_info_icons($course)) {
2621 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2622 foreach ($icons as $icon) {
2623 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
2624 echo $OUTPUT->render($icon);
2626 echo html_writer::end_tag('div'); // End of enrolmenticons div
2628 echo html_writer::end_tag('div'); // End of summary div
2629 echo html_writer::end_tag('div'); // End of coursebox div
2633 * Prints custom user information on the home page.
2634 * Over time this can include all sorts of information
2636 function print_my_moodle() {
2637 global $USER, $CFG, $DB, $OUTPUT;
2639 if (!isloggedin() or isguestuser()) {
2640 print_error('nopermissions', '', '', 'See My Moodle');
2643 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2644 $rhosts = array();
2645 $rcourses = array();
2646 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2647 $rcourses = get_my_remotecourses($USER->id);
2648 $rhosts = get_my_remotehosts();
2651 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2653 if (!empty($courses)) {
2654 echo '<ul class="unlist">';
2655 foreach ($courses as $course) {
2656 if ($course->id == SITEID) {
2657 continue;
2659 echo '<li>';
2660 print_course($course);
2661 echo "</li>\n";
2663 echo "</ul>\n";
2666 // MNET
2667 if (!empty($rcourses)) {
2668 // at the IDP, we know of all the remote courses
2669 foreach ($rcourses as $course) {
2670 print_remote_course($course, "100%");
2672 } elseif (!empty($rhosts)) {
2673 // non-IDP, we know of all the remote servers, but not courses
2674 foreach ($rhosts as $host) {
2675 print_remote_host($host, "100%");
2678 unset($course);
2679 unset($host);
2681 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2682 echo "<table width=\"100%\"><tr><td align=\"center\">";
2683 print_course_search("", false, "short");
2684 echo "</td><td align=\"center\">";
2685 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2686 echo "</td></tr></table>\n";
2689 } else {
2690 if ($DB->count_records("course_categories") > 1) {
2691 echo $OUTPUT->box_start("categorybox");
2692 print_whole_category_list();
2693 echo $OUTPUT->box_end();
2694 } else {
2695 print_courses(0);
2701 function print_course_search($value="", $return=false, $format="plain") {
2702 global $CFG;
2703 static $count = 0;
2705 $count++;
2707 $id = 'coursesearch';
2709 if ($count > 1) {
2710 $id .= $count;
2713 $strsearchcourses= get_string("searchcourses");
2715 if ($format == 'plain') {
2716 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2717 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2718 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2719 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2720 $output .= '<input type="submit" value="'.get_string('go').'" />';
2721 $output .= '</fieldset></form>';
2722 } else if ($format == 'short') {
2723 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2724 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2725 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2726 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" value="'.s($value).'" />';
2727 $output .= '<input type="submit" value="'.get_string('go').'" />';
2728 $output .= '</fieldset></form>';
2729 } else if ($format == 'navbar') {
2730 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2731 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2732 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2733 $output .= '<input type="text" id="navsearchbox" size="20" name="search" value="'.s($value).'" />';
2734 $output .= '<input type="submit" value="'.get_string('go').'" />';
2735 $output .= '</fieldset></form>';
2738 if ($return) {
2739 return $output;
2741 echo $output;
2744 function print_remote_course($course, $width="100%") {
2745 global $CFG, $USER;
2747 $linkcss = '';
2749 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2751 echo '<div class="coursebox remotecoursebox clearfix">';
2752 echo '<div class="info">';
2753 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2754 $linkcss.' href="'.$url.'">'
2755 . format_string($course->fullname) .'</a><br />'
2756 . format_string($course->hostname) . ' : '
2757 . format_string($course->cat_name) . ' : '
2758 . format_string($course->shortname). '</div>';
2759 echo '</div><div class="summary">';
2760 $options = new stdClass();
2761 $options->noclean = true;
2762 $options->para = false;
2763 $options->overflowdiv = true;
2764 echo format_text($course->summary, $course->summaryformat, $options);
2765 echo '</div>';
2766 echo '</div>';
2769 function print_remote_host($host, $width="100%") {
2770 global $OUTPUT;
2772 $linkcss = '';
2774 echo '<div class="coursebox clearfix">';
2775 echo '<div class="info">';
2776 echo '<div class="name">';
2777 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2778 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2779 . s($host['name']).'</a> - ';
2780 echo $host['count'] . ' ' . get_string('courses');
2781 echo '</div>';
2782 echo '</div>';
2783 echo '</div>';
2787 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2789 function add_course_module($mod) {
2790 global $DB;
2792 $mod->added = time();
2793 unset($mod->id);
2795 return $DB->insert_record("course_modules", $mod);
2799 * Returns course section - creates new if does not exist yet.
2800 * @param int $relative section number
2801 * @param int $courseid
2802 * @return object $course_section object
2804 function get_course_section($section, $courseid) {
2805 global $DB;
2807 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2808 return $cw;
2810 $cw = new stdClass();
2811 $cw->course = $courseid;
2812 $cw->section = $section;
2813 $cw->summary = "";
2814 $cw->summaryformat = FORMAT_HTML;
2815 $cw->sequence = "";
2816 $id = $DB->insert_record("course_sections", $cw);
2817 rebuild_course_cache($courseid, true);
2818 return $DB->get_record("course_sections", array("id"=>$id));
2822 * Given a full mod object with section and course already defined, adds this module to that section.
2824 * @param object $mod
2825 * @param int $beforemod An existing ID which we will insert the new module before
2826 * @return int The course_sections ID where the mod is inserted
2828 function add_mod_to_section($mod, $beforemod=NULL) {
2829 global $DB;
2831 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2833 $section->sequence = trim($section->sequence);
2835 if (empty($section->sequence)) {
2836 $newsequence = "$mod->coursemodule";
2838 } else if ($beforemod) {
2839 $modarray = explode(",", $section->sequence);
2841 if ($key = array_keys($modarray, $beforemod->id)) {
2842 $insertarray = array($mod->id, $beforemod->id);
2843 array_splice($modarray, $key[0], 1, $insertarray);
2844 $newsequence = implode(",", $modarray);
2846 } else { // Just tack it on the end anyway
2847 $newsequence = "$section->sequence,$mod->coursemodule";
2850 } else {
2851 $newsequence = "$section->sequence,$mod->coursemodule";
2854 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2855 $DB->set_field("course_modules", "section", $section->id, array("id" => $mod->coursemodule));
2856 return $section->id; // Return course_sections ID that was used.
2858 } else { // Insert a new record
2859 $section = new stdClass();
2860 $section->course = $mod->course;
2861 $section->section = $mod->section;
2862 $section->summary = "";
2863 $section->summaryformat = FORMAT_HTML;
2864 $section->sequence = $mod->coursemodule;
2865 $section->id = $DB->insert_record("course_sections", $section);
2866 $DB->set_field("course_modules", "section", $section->id, array("id" => $mod->coursemodule));
2867 return $section->id;
2871 function set_coursemodule_groupmode($id, $groupmode) {
2872 global $DB;
2873 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2876 function set_coursemodule_idnumber($id, $idnumber) {
2877 global $DB;
2878 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2882 * $prevstateoverrides = true will set the visibility of the course module
2883 * to what is defined in visibleold. This enables us to remember the current
2884 * visibility when making a whole section hidden, so that when we toggle
2885 * that section back to visible, we are able to return the visibility of
2886 * the course module back to what it was originally.
2888 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2889 global $DB, $CFG;
2890 require_once($CFG->libdir.'/gradelib.php');
2892 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2893 return false;
2896 // Create events and propagate visibility to associated grade items if the value has changed.
2897 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2898 if ($cm->visible == $visible) {
2899 return true;
2902 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2903 return false;
2905 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2906 foreach($events as $event) {
2907 if ($visible) {
2908 show_event($event);
2909 } else {
2910 hide_event($event);
2915 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2916 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2917 if ($grade_items) {
2918 foreach ($grade_items as $grade_item) {
2919 $grade_item->set_hidden(!$visible);
2923 $cminfo = new stdClass();
2924 $cminfo->id = $id;
2925 $cminfo->visible = $visible;
2927 if ($prevstateoverrides) {
2928 // If we making whole section visiblility change..
2929 if ($visible == 0) {
2930 // Retain previous visibility state.
2931 $cminfo->visibleold = $cm->visible;
2932 } else {
2933 // Restore previous visibility state.
2934 $cminfo->visible = $cm->visibleold;
2936 } else {
2937 $cminfo->visibleold = $visible;
2939 return $DB->update_record('course_modules', $cminfo);
2943 * Delete a course module and any associated data at the course level (events)
2944 * Until 1.5 this function simply marked a deleted flag ... now it
2945 * deletes it completely.
2948 function delete_course_module($id) {
2949 global $CFG, $DB;
2950 require_once($CFG->libdir.'/gradelib.php');
2951 require_once($CFG->dirroot.'/blog/lib.php');
2953 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2954 return true;
2956 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2957 //delete events from calendar
2958 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2959 foreach($events as $event) {
2960 delete_event($event->id);
2963 //delete grade items, outcome items and grades attached to modules
2964 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2965 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2966 foreach ($grade_items as $grade_item) {
2967 $grade_item->delete('moddelete');
2970 // Delete completion and availability data; it is better to do this even if the
2971 // features are not turned on, in case they were turned on previously (these will be
2972 // very quick on an empty table)
2973 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2974 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2975 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2976 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2978 delete_context(CONTEXT_MODULE, $cm->id);
2979 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2982 function delete_mod_from_section($mod, $section) {
2983 global $DB;
2985 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2987 $modarray = explode(",", $section->sequence);
2989 if ($key = array_keys ($modarray, $mod)) {
2990 array_splice($modarray, $key[0], 1);
2991 $newsequence = implode(",", $modarray);
2992 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2993 } else {
2994 return false;
2998 return false;
3002 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
3004 * @param object $course course object
3005 * @param int $section Section number (not id!!!)
3006 * @param int $move (-1 or 1)
3007 * @return boolean true if section moved successfully
3008 * @todo MDL-33379 remove this function in 2.5
3010 function move_section($course, $section, $move) {
3011 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
3013 /// Moves a whole course section up and down within the course
3014 global $USER, $DB;
3016 if (!$move) {
3017 return true;
3020 $sectiondest = $section + $move;
3022 if ($sectiondest > $course->numsections or $sectiondest < 1) {
3023 return false;
3026 $retval = move_section_to($course, $section, $sectiondest);
3027 // If section moved, then rebuild course cache.
3028 if ($retval) {
3029 rebuild_course_cache($course->id, true);
3031 return $retval;
3035 * Moves a section within a course, from a position to another.
3036 * Be very careful: $section and $destination refer to section number,
3037 * not id!.
3039 * @param object $course
3040 * @param int $section Section number (not id!!!)
3041 * @param int $destination
3042 * @return boolean Result
3044 function move_section_to($course, $section, $destination) {
3045 /// Moves a whole course section up and down within the course
3046 global $USER, $DB;
3048 if (!$destination && $destination != 0) {
3049 return true;
3052 if (($destination > $course->numsections) || ($destination < 1)) {
3053 return false;
3056 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3057 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3058 'section ASC, id ASC', 'id, section')) {
3059 return false;
3062 $movedsections = reorder_sections($sections, $section, $destination);
3064 // Update all sections. Do this in 2 steps to avoid breaking database
3065 // uniqueness constraint
3066 $transaction = $DB->start_delegated_transaction();
3067 foreach ($movedsections as $id => $position) {
3068 if ($sections[$id] !== $position) {
3069 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3072 foreach ($movedsections as $id => $position) {
3073 if ($sections[$id] !== $position) {
3074 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3078 // If we move the highlighted section itself, then just highlight the destination.
3079 // Adjust the higlighted section location if we move something over it either direction.
3080 if ($section == $course->marker) {
3081 course_set_marker($course->id, $destination);
3082 } elseif ($section > $course->marker && $course->marker >= $destination) {
3083 course_set_marker($course->id, $course->marker+1);
3084 } elseif ($section < $course->marker && $course->marker <= $destination) {
3085 course_set_marker($course->id, $course->marker-1);
3088 $transaction->allow_commit();
3089 return true;
3093 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3094 * an original position number and a target position number, rebuilds the array so that the
3095 * move is made without any duplication of section positions.
3096 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3097 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3099 * @param array $sections
3100 * @param int $origin_position
3101 * @param int $target_position
3102 * @return array
3104 function reorder_sections($sections, $origin_position, $target_position) {
3105 if (!is_array($sections)) {
3106 return false;
3109 // We can't move section position 0
3110 if ($origin_position < 1) {
3111 echo "We can't move section position 0";
3112 return false;
3115 // Locate origin section in sections array
3116 if (!$origin_key = array_search($origin_position, $sections)) {
3117 echo "searched position not in sections array";
3118 return false; // searched position not in sections array
3121 // Extract origin section
3122 $origin_section = $sections[$origin_key];
3123 unset($sections[$origin_key]);
3125 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3126 $found = false;
3127 $append_array = array();
3128 foreach ($sections as $id => $position) {
3129 if ($found) {
3130 $append_array[$id] = $position;
3131 unset($sections[$id]);
3133 if ($position == $target_position) {
3134 if ($target_position < $origin_position) {
3135 $append_array[$id] = $position;
3136 unset($sections[$id]);
3138 $found = true;
3142 // Append moved section
3143 $sections[$origin_key] = $origin_section;
3145 // Append rest of array (if applicable)
3146 if (!empty($append_array)) {
3147 foreach ($append_array as $id => $position) {
3148 $sections[$id] = $position;
3152 // Renumber positions
3153 $position = 0;
3154 foreach ($sections as $id => $p) {
3155 $sections[$id] = $position;
3156 $position++;
3159 return $sections;
3164 * Move the module object $mod to the specified $section
3165 * If $beforemod exists then that is the module
3166 * before which $modid should be inserted
3167 * All parameters are objects
3169 function moveto_module($mod, $section, $beforemod=NULL) {
3170 global $DB, $OUTPUT;
3172 /// Remove original module from original section
3173 if (! delete_mod_from_section($mod->id, $mod->section)) {
3174 echo $OUTPUT->notification("Could not delete module from existing section");
3177 /// Update module itself if necessary
3179 // If moving to a hidden section then hide module.
3180 if ($mod->section != $section->id) {
3181 if (!$section->visible && $mod->visible) {
3182 // Set this in the object because it is sent as a response to ajax calls.
3183 set_coursemodule_visible($mod->id, 0, true);
3184 $mod->visible = 0;
3186 if ($section->visible && !$mod->visible) {
3187 set_coursemodule_visible($mod->id, 1, true);
3188 // Set this in the object because it is sent as a response to ajax calls.
3189 $mod->visible = $mod->visibleold;
3193 /// Add the module into the new section
3195 $mod->course = $section->course;
3196 $mod->section = $section->section; // need relative reference
3197 $mod->coursemodule = $mod->id;
3199 if (! add_mod_to_section($mod, $beforemod)) {
3200 return false;
3203 return true;
3207 * Produces the editing buttons for a module
3209 * @global core_renderer $OUTPUT
3210 * @staticvar type $str
3211 * @param stdClass $mod The module to produce editing buttons for
3212 * @param bool $absolute_ignored ignored - all links are absolute
3213 * @param bool $moveselect If true a move seleciton process is used (default true)
3214 * @param int $indent The current indenting
3215 * @param int $section The section to link back to
3216 * @return string XHTML for the editing buttons
3218 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3219 global $CFG, $OUTPUT, $COURSE;
3221 static $str;
3223 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3224 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3226 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3227 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3229 // no permission to edit anything
3230 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3231 return false;
3234 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3236 if (!isset($str)) {
3237 $str = new stdClass;
3238 $str->assign = get_string("assignroles", 'role');
3239 $str->delete = get_string("delete");
3240 $str->move = get_string("move");
3241 $str->moveup = get_string("moveup");
3242 $str->movedown = get_string("movedown");
3243 $str->moveright = get_string("moveright");
3244 $str->moveleft = get_string("moveleft");
3245 $str->update = get_string("update");
3246 $str->duplicate = get_string("duplicate");
3247 $str->hide = get_string("hide");
3248 $str->show = get_string("show");
3249 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3250 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3251 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3252 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3253 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3254 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3255 $str->edittitle = get_string('edittitle', 'moodle');
3258 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3260 if ($section !== null) {
3261 $baseurl->param('sr', $section);
3263 $actions = array();
3265 // AJAX edit title
3266 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3267 $actions[] = new action_link(
3268 new moodle_url($baseurl, array('update' => $mod->id)),
3269 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3270 null,
3271 array('class' => 'editing_title', 'title' => $str->edittitle)
3275 // leftright
3276 if ($hasmanageactivities) {
3277 if (right_to_left()) { // Exchange arrows on RTL
3278 $rightarrow = 't/left';
3279 $leftarrow = 't/right';
3280 } else {
3281 $rightarrow = 't/right';
3282 $leftarrow = 't/left';
3285 if ($indent > 0) {
3286 $actions[] = new action_link(
3287 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3288 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3289 null,
3290 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3293 if ($indent >= 0) {
3294 $actions[] = new action_link(
3295 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3296 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3297 null,
3298 array('class' => 'editing_moveright', 'title' => $str->moveright)
3303 // move
3304 if ($hasmanageactivities) {
3305 if ($moveselect) {
3306 $actions[] = new action_link(
3307 new moodle_url($baseurl, array('copy' => $mod->id)),
3308 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3309 null,
3310 array('class' => 'editing_move', 'title' => $str->move)
3312 } else {
3313 $actions[] = new action_link(
3314 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3315 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3316 null,
3317 array('class' => 'editing_moveup', 'title' => $str->moveup)
3319 $actions[] = new action_link(
3320 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3321 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3322 null,
3323 array('class' => 'editing_movedown', 'title' => $str->movedown)
3328 // Update
3329 if ($hasmanageactivities) {
3330 $actions[] = new action_link(
3331 new moodle_url($baseurl, array('update' => $mod->id)),
3332 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3333 null,
3334 array('class' => 'editing_update', 'title' => $str->update)
3338 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3339 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3340 $actions[] = new action_link(
3341 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3342 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3343 null,
3344 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3348 // Delete
3349 if ($hasmanageactivities) {
3350 $actions[] = new action_link(
3351 new moodle_url($baseurl, array('delete' => $mod->id)),
3352 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3353 null,
3354 array('class' => 'editing_delete', 'title' => $str->delete)
3358 // hideshow
3359 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3360 if ($mod->visible) {
3361 $actions[] = new action_link(
3362 new moodle_url($baseurl, array('hide' => $mod->id)),
3363 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3364 null,
3365 array('class' => 'editing_hide', 'title' => $str->hide)
3367 } else {
3368 $actions[] = new action_link(
3369 new moodle_url($baseurl, array('show' => $mod->id)),
3370 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3371 null,
3372 array('class' => 'editing_show', 'title' => $str->show)
3377 // groupmode
3378 if ($hasmanageactivities and $mod->groupmode !== false) {
3379 if ($mod->groupmode == SEPARATEGROUPS) {
3380 $groupmode = 0;
3381 $grouptitle = $str->groupsseparate;
3382 $forcedgrouptitle = $str->forcedgroupsseparate;
3383 $groupclass = 'editing_groupsseparate';
3384 $groupimage = 't/groups';
3385 } else if ($mod->groupmode == VISIBLEGROUPS) {
3386 $groupmode = 1;
3387 $grouptitle = $str->groupsvisible;
3388 $forcedgrouptitle = $str->forcedgroupsvisible;
3389 $groupclass = 'editing_groupsvisible';
3390 $groupimage = 't/groupv';
3391 } else {
3392 $groupmode = 2;
3393 $grouptitle = $str->groupsnone;
3394 $forcedgrouptitle = $str->forcedgroupsnone;
3395 $groupclass = 'editing_groupsnone';
3396 $groupimage = 't/groupn';
3398 if ($mod->groupmodelink) {
3399 $actions[] = new action_link(
3400 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3401 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3402 null,
3403 array('class' => $groupclass, 'title' => $grouptitle)
3405 } else {
3406 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3410 // Assign
3411 if (has_capability('moodle/role:assign', $modcontext)){
3412 $actions[] = new action_link(
3413 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3414 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3415 null,
3416 array('class' => 'editing_assign', 'title' => $str->assign)
3420 $output = html_writer::start_tag('span', array('class' => 'commands'));
3421 foreach ($actions as $action) {
3422 if ($action instanceof renderable) {
3423 $output .= $OUTPUT->render($action);
3424 } else {
3425 $output .= $action;
3428 $output .= html_writer::end_tag('span');
3429 return $output;
3433 * given a course object with shortname & fullname, this function will
3434 * truncate the the number of chars allowed and add ... if it was too long
3436 function course_format_name ($course,$max=100) {
3438 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3439 $shortname = format_string($course->shortname, true, array('context' => $context));
3440 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3441 $str = $shortname.': '. $fullname;
3442 if (textlib::strlen($str) <= $max) {
3443 return $str;
3445 else {
3446 return textlib::substr($str,0,$max-3).'...';
3451 * Is the user allowed to add this type of module to this course?
3452 * @param object $course the course settings. Only $course->id is used.
3453 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3454 * @return bool whether the current user is allowed to add this type of module to this course.
3456 function course_allowed_module($course, $modname) {
3457 global $DB;
3459 if (is_numeric($modname)) {
3460 throw new coding_exception('Function course_allowed_module no longer
3461 supports numeric module ids. Please update your code to pass the module name.');
3464 $capability = 'mod/' . $modname . ':addinstance';
3465 if (!get_capability_info($capability)) {
3466 // Debug warning that the capability does not exist, but no more than once per page.
3467 static $warned = array();
3468 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3469 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3470 debugging('The module ' . $modname . ' does not define the standard capability ' .
3471 $capability , DEBUG_DEVELOPER);
3472 $warned[$modname] = 1;
3475 // If the capability does not exist, the module can always be added.
3476 return true;
3479 $coursecontext = context_course::instance($course->id);
3480 return has_capability($capability, $coursecontext);
3484 * Recursively delete category including all subcategories and courses.
3485 * @param stdClass $category
3486 * @param boolean $showfeedback display some notices
3487 * @return array return deleted courses
3489 function category_delete_full($category, $showfeedback=true) {
3490 global $CFG, $DB;
3491 require_once($CFG->libdir.'/gradelib.php');
3492 require_once($CFG->libdir.'/questionlib.php');
3493 require_once($CFG->dirroot.'/cohort/lib.php');
3495 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3496 foreach ($children as $childcat) {
3497 category_delete_full($childcat, $showfeedback);
3501 $deletedcourses = array();
3502 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3503 foreach ($courses as $course) {
3504 if (!delete_course($course, false)) {
3505 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3507 $deletedcourses[] = $course;
3511 // move or delete cohorts in this context
3512 cohort_delete_category($category);
3514 // now delete anything that may depend on course category context
3515 grade_course_category_delete($category->id, 0, $showfeedback);
3516 if (!question_delete_course_category($category, 0, $showfeedback)) {
3517 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3520 // finally delete the category and it's context
3521 $DB->delete_records('course_categories', array('id'=>$category->id));
3522 delete_context(CONTEXT_COURSECAT, $category->id);
3523 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3525 events_trigger('course_category_deleted', $category);
3527 return $deletedcourses;
3531 * Delete category, but move contents to another category.
3532 * @param object $ccategory
3533 * @param int $newparentid category id
3534 * @return bool status
3536 function category_delete_move($category, $newparentid, $showfeedback=true) {
3537 global $CFG, $DB, $OUTPUT;
3538 require_once($CFG->libdir.'/gradelib.php');
3539 require_once($CFG->libdir.'/questionlib.php');
3540 require_once($CFG->dirroot.'/cohort/lib.php');
3542 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3543 return false;
3546 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3547 foreach ($children as $childcat) {
3548 move_category($childcat, $newparentcat);
3552 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3553 if (!move_courses(array_keys($courses), $newparentid)) {
3554 if ($showfeedback) {
3555 echo $OUTPUT->notification("Error moving courses");
3557 return false;
3559 if ($showfeedback) {
3560 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3564 // move or delete cohorts in this context
3565 cohort_delete_category($category);
3567 // now delete anything that may depend on course category context
3568 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3569 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3570 if ($showfeedback) {
3571 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3573 return false;
3576 // finally delete the category and it's context
3577 $DB->delete_records('course_categories', array('id'=>$category->id));
3578 delete_context(CONTEXT_COURSECAT, $category->id);
3579 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3581 events_trigger('course_category_deleted', $category);
3583 if ($showfeedback) {
3584 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3586 return true;
3590 * Efficiently moves many courses around while maintaining
3591 * sortorder in order.
3593 * @param array $courseids is an array of course ids
3594 * @param int $categoryid
3595 * @return bool success
3597 function move_courses($courseids, $categoryid) {
3598 global $CFG, $DB, $OUTPUT;
3600 if (empty($courseids)) {
3601 // nothing to do
3602 return;
3605 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3606 return false;
3609 $courseids = array_reverse($courseids);
3610 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3611 $i = 1;
3613 foreach ($courseids as $courseid) {
3614 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3615 $course = new stdClass();
3616 $course->id = $courseid;
3617 $course->category = $category->id;
3618 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3619 if ($category->visible == 0) {
3620 // hide the course when moving into hidden category,
3621 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3622 $course->visible = 0;
3625 $DB->update_record('course', $course);
3626 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
3628 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3629 context_moved($context, $newparent);
3632 fix_course_sortorder();
3634 return true;
3638 * Hide course category and child course and subcategories
3639 * @param stdClass $category
3640 * @return void
3642 function course_category_hide($category) {
3643 global $DB;
3645 $category->visible = 0;
3646 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3647 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3648 $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
3649 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3650 // get all child categories and hide too
3651 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3652 foreach ($subcats as $cat) {
3653 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3654 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3655 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3656 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3659 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$category->id", $category->id);
3663 * Show course category and child course and subcategories
3664 * @param stdClass $category
3665 * @return void
3667 function course_category_show($category) {
3668 global $DB;
3670 $category->visible = 1;
3671 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3672 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3673 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3674 // get all child categories and unhide too
3675 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3676 foreach ($subcats as $cat) {
3677 if ($cat->visibleold) {
3678 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3680 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3683 add_to_log(SITEID, "category", "show", "editcategory.php?id=$category->id", $category->id);
3687 * Efficiently moves a category - NOTE that this can have
3688 * a huge impact access-control-wise...
3690 function move_category($category, $newparentcat) {
3691 global $CFG, $DB;
3693 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3695 $hidecat = false;
3696 if (empty($newparentcat->id)) {
3697 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3699 $newparent = get_context_instance(CONTEXT_SYSTEM);
3701 } else {
3702 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3703 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3705 if (!$newparentcat->visible and $category->visible) {
3706 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3707 $hidecat = true;
3711 context_moved($context, $newparent);
3713 // now make it last in new category
3714 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3716 // Log action.
3717 add_to_log(SITEID, "category", "move", "editcategory.php?id=$category->id", $category->id);
3719 // and fix the sortorders
3720 fix_course_sortorder();
3722 if ($hidecat) {
3723 course_category_hide($category);
3728 * Returns the display name of the given section that the course prefers.
3730 * This function utilizes a callback that can be implemented within the course
3731 * formats lib.php file to customize the display name that is used to reference
3732 * the section.
3734 * By default (if callback is not defined) the method
3735 * {@see get_numeric_section_name} is called instead.
3737 * @param stdClass $course The course to get the section name for
3738 * @param stdClass $section Section object from database
3739 * @return Display name that the course format prefers, e.g. "Week 2"
3741 * @see get_generic_section_name
3743 function get_section_name(stdClass $course, stdClass $section) {
3744 global $CFG;
3746 /// Inelegant hack for bug 3408
3747 if ($course->format == 'site') {
3748 return get_string('site');
3751 // Use course formatter callback if it exists
3752 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3753 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3754 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3755 require_once $namingfile;
3757 if (function_exists($namingfunction)) {
3758 return $namingfunction($course, $section);
3761 // else, default behavior:
3762 return get_generic_section_name($course->format, $section);
3766 * Gets the generic section name for a courses section.
3768 * @param string $format Course format ID e.g. 'weeks' $course->format
3769 * @param stdClass $section Section object from database
3770 * @return Display name that the course format prefers, e.g. "Week 2"
3772 function get_generic_section_name($format, stdClass $section) {
3773 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3777 function course_format_uses_sections($format) {
3778 global $CFG;
3780 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3781 $featurefunction = 'callback_'.$format.'_uses_sections';
3782 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3783 require_once $featurefile;
3785 if (function_exists($featurefunction)) {
3786 return $featurefunction();
3789 return false;
3793 * Returns the information about the ajax support in the given source format
3795 * The returned object's property (boolean)capable indicates that
3796 * the course format supports Moodle course ajax features.
3797 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3799 * @param string $format
3800 * @return stdClass
3802 function course_format_ajax_support($format) {
3803 global $CFG;
3805 // set up default values
3806 $ajaxsupport = new stdClass();
3807 $ajaxsupport->capable = false;
3808 $ajaxsupport->testedbrowsers = array();
3810 // get the information from the course format library
3811 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3812 $featurefunction = 'callback_'.$format.'_ajax_support';
3813 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3814 require_once $featurefile;
3816 if (function_exists($featurefunction)) {
3817 $formatsupport = $featurefunction();
3818 if (isset($formatsupport->capable)) {
3819 $ajaxsupport->capable = $formatsupport->capable;
3821 if (is_array($formatsupport->testedbrowsers)) {
3822 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3826 return $ajaxsupport;
3830 * Can the current user delete this course?
3831 * Course creators have exception,
3832 * 1 day after the creation they can sill delete the course.
3833 * @param int $courseid
3834 * @return boolean
3836 function can_delete_course($courseid) {
3837 global $USER, $DB;
3839 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3841 if (has_capability('moodle/course:delete', $context)) {
3842 return true;
3845 // hack: now try to find out if creator created this course recently (1 day)
3846 if (!has_capability('moodle/course:create', $context)) {
3847 return false;
3850 $since = time() - 60*60*24;
3852 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3853 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3855 return $DB->record_exists_select('log', $select, $params);
3859 * Save the Your name for 'Some role' strings.
3861 * @param integer $courseid the id of this course.
3862 * @param array $data the data that came from the course settings form.
3864 function save_local_role_names($courseid, $data) {
3865 global $DB;
3866 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3868 foreach ($data as $fieldname => $value) {
3869 if (strpos($fieldname, 'role_') !== 0) {
3870 continue;
3872 list($ignored, $roleid) = explode('_', $fieldname);
3874 // make up our mind whether we want to delete, update or insert
3875 if (!$value) {
3876 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3878 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3879 $rolename->name = $value;
3880 $DB->update_record('role_names', $rolename);
3882 } else {
3883 $rolename = new stdClass;
3884 $rolename->contextid = $context->id;
3885 $rolename->roleid = $roleid;
3886 $rolename->name = $value;
3887 $DB->insert_record('role_names', $rolename);
3893 * Create a course and either return a $course object
3895 * Please note this functions does not verify any access control,
3896 * the calling code is responsible for all validation (usually it is the form definition).
3898 * @param array $editoroptions course description editor options
3899 * @param object $data - all the data needed for an entry in the 'course' table
3900 * @return object new course instance
3902 function create_course($data, $editoroptions = NULL) {
3903 global $CFG, $DB;
3905 //check the categoryid - must be given for all new courses
3906 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3908 //check if the shortname already exist
3909 if (!empty($data->shortname)) {
3910 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3911 throw new moodle_exception('shortnametaken');
3915 //check if the id number already exist
3916 if (!empty($data->idnumber)) {
3917 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3918 throw new moodle_exception('idnumbertaken');
3922 $data->timecreated = time();
3923 $data->timemodified = $data->timecreated;
3925 // place at beginning of any category
3926 $data->sortorder = 0;
3928 if ($editoroptions) {
3929 // summary text is updated later, we need context to store the files first
3930 $data->summary = '';
3931 $data->summary_format = FORMAT_HTML;
3934 if (!isset($data->visible)) {
3935 // data not from form, add missing visibility info
3936 $data->visible = $category->visible;
3938 $data->visibleold = $data->visible;
3940 $newcourseid = $DB->insert_record('course', $data);
3941 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3943 if ($editoroptions) {
3944 // Save the files used in the summary editor and store
3945 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3946 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3947 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3950 $course = $DB->get_record('course', array('id'=>$newcourseid));
3952 // Setup the blocks
3953 blocks_add_default_course_blocks($course);
3955 $section = new stdClass();
3956 $section->course = $course->id; // Create a default section.
3957 $section->section = 0;
3958 $section->summaryformat = FORMAT_HTML;
3959 $DB->insert_record('course_sections', $section);
3961 fix_course_sortorder();
3963 // new context created - better mark it as dirty
3964 mark_context_dirty($context->path);
3966 // Save any custom role names.
3967 save_local_role_names($course->id, (array)$data);
3969 // set up enrolments
3970 enrol_course_updated(true, $course, $data);
3972 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3974 // Trigger events
3975 events_trigger('course_created', $course);
3977 return $course;
3981 * Create a new course category and marks the context as dirty
3983 * This function does not set the sortorder for the new category and
3984 * @see{fix_course_sortorder} should be called after creating a new course
3985 * category
3987 * Please note that this function does not verify access control.
3989 * @param object $category All of the data required for an entry in the course_categories table
3990 * @return object new course category
3992 function create_course_category($category) {
3993 global $DB;
3995 $category->timemodified = time();
3996 $category->id = $DB->insert_record('course_categories', $category);
3997 $category = $DB->get_record('course_categories', array('id' => $category->id));
3999 // We should mark the context as dirty
4000 $category->context = context_coursecat::instance($category->id);
4001 $category->context->mark_dirty();
4003 return $category;
4007 * Update a course.
4009 * Please note this functions does not verify any access control,
4010 * the calling code is responsible for all validation (usually it is the form definition).
4012 * @param object $data - all the data needed for an entry in the 'course' table
4013 * @param array $editoroptions course description editor options
4014 * @return void
4016 function update_course($data, $editoroptions = NULL) {
4017 global $CFG, $DB;
4019 $data->timemodified = time();
4021 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
4022 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
4024 if ($editoroptions) {
4025 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
4028 if (!isset($data->category) or empty($data->category)) {
4029 // prevent nulls and 0 in category field
4030 unset($data->category);
4032 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
4034 if (!isset($data->visible)) {
4035 // data not from form, add missing visibility info
4036 $data->visible = $oldcourse->visible;
4039 if ($data->visible != $oldcourse->visible) {
4040 // reset the visibleold flag when manually hiding/unhiding course
4041 $data->visibleold = $data->visible;
4042 } else {
4043 if ($movecat) {
4044 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
4045 if (empty($newcategory->visible)) {
4046 // make sure when moving into hidden category the course is hidden automatically
4047 $data->visible = 0;
4052 // Update with the new data
4053 $DB->update_record('course', $data);
4055 $course = $DB->get_record('course', array('id'=>$data->id));
4057 if ($movecat) {
4058 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
4059 context_moved($context, $newparent);
4062 fix_course_sortorder();
4064 // Test for and remove blocks which aren't appropriate anymore
4065 blocks_remove_inappropriate($course);
4067 // Save any custom role names.
4068 save_local_role_names($course->id, $data);
4070 // update enrol settings
4071 enrol_course_updated(false, $course, $data);
4073 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4075 // Trigger events
4076 events_trigger('course_updated', $course);
4080 * Average number of participants
4081 * @return integer
4083 function average_number_of_participants() {
4084 global $DB, $SITE;
4086 //count total of enrolments for visible course (except front page)
4087 $sql = 'SELECT COUNT(*) FROM (
4088 SELECT DISTINCT ue.userid, e.courseid
4089 FROM {user_enrolments} ue, {enrol} e, {course} c
4090 WHERE ue.enrolid = e.id
4091 AND e.courseid <> :siteid
4092 AND c.id = e.courseid
4093 AND c.visible = 1) total';
4094 $params = array('siteid' => $SITE->id);
4095 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4098 //count total of visible courses (minus front page)
4099 $coursetotal = $DB->count_records('course', array('visible' => 1));
4100 $coursetotal = $coursetotal - 1 ;
4102 //average of enrolment
4103 if (empty($coursetotal)) {
4104 $participantaverage = 0;
4105 } else {
4106 $participantaverage = $enrolmenttotal / $coursetotal;
4109 return $participantaverage;
4113 * Average number of course modules
4114 * @return integer
4116 function average_number_of_courses_modules() {
4117 global $DB, $SITE;
4119 //count total of visible course module (except front page)
4120 $sql = 'SELECT COUNT(*) FROM (
4121 SELECT cm.course, cm.module
4122 FROM {course} c, {course_modules} cm
4123 WHERE c.id = cm.course
4124 AND c.id <> :siteid
4125 AND cm.visible = 1
4126 AND c.visible = 1) total';
4127 $params = array('siteid' => $SITE->id);
4128 $moduletotal = $DB->count_records_sql($sql, $params);
4131 //count total of visible courses (minus front page)
4132 $coursetotal = $DB->count_records('course', array('visible' => 1));
4133 $coursetotal = $coursetotal - 1 ;
4135 //average of course module
4136 if (empty($coursetotal)) {
4137 $coursemoduleaverage = 0;
4138 } else {
4139 $coursemoduleaverage = $moduletotal / $coursetotal;
4142 return $coursemoduleaverage;
4146 * This class pertains to course requests and contains methods associated with
4147 * create, approving, and removing course requests.
4149 * Please note we do not allow embedded images here because there is no context
4150 * to store them with proper access control.
4152 * @copyright 2009 Sam Hemelryk
4153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4154 * @since Moodle 2.0
4156 * @property-read int $id
4157 * @property-read string $fullname
4158 * @property-read string $shortname
4159 * @property-read string $summary
4160 * @property-read int $summaryformat
4161 * @property-read int $summarytrust
4162 * @property-read string $reason
4163 * @property-read int $requester
4165 class course_request {
4168 * This is the stdClass that stores the properties for the course request
4169 * and is externally accessed through the __get magic method
4170 * @var stdClass
4172 protected $properties;
4175 * An array of options for the summary editor used by course request forms.
4176 * This is initially set by {@link summary_editor_options()}
4177 * @var array
4178 * @static
4180 protected static $summaryeditoroptions;
4183 * Static function to prepare the summary editor for working with a course
4184 * request.
4186 * @static
4187 * @param null|stdClass $data Optional, an object containing the default values
4188 * for the form, these may be modified when preparing the
4189 * editor so this should be called before creating the form
4190 * @return stdClass An object that can be used to set the default values for
4191 * an mforms form
4193 public static function prepare($data=null) {
4194 if ($data === null) {
4195 $data = new stdClass;
4197 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4198 return $data;
4202 * Static function to create a new course request when passed an array of properties
4203 * for it.
4205 * This function also handles saving any files that may have been used in the editor
4207 * @static
4208 * @param stdClass $data
4209 * @return course_request The newly created course request
4211 public static function create($data) {
4212 global $USER, $DB, $CFG;
4213 $data->requester = $USER->id;
4215 // Summary is a required field so copy the text over
4216 $data->summary = $data->summary_editor['text'];
4217 $data->summaryformat = $data->summary_editor['format'];
4219 $data->id = $DB->insert_record('course_request', $data);
4221 // Create a new course_request object and return it
4222 $request = new course_request($data);
4224 // Notify the admin if required.
4225 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4227 $a = new stdClass;
4228 $a->link = "$CFG->wwwroot/course/pending.php";
4229 $a->user = fullname($USER);
4230 $subject = get_string('courserequest');
4231 $message = get_string('courserequestnotifyemail', 'admin', $a);
4232 foreach ($users as $user) {
4233 $request->notify($user, $USER, 'courserequested', $subject, $message);
4237 return $request;
4241 * Returns an array of options to use with a summary editor
4243 * @uses course_request::$summaryeditoroptions
4244 * @return array An array of options to use with the editor
4246 public static function summary_editor_options() {
4247 global $CFG;
4248 if (self::$summaryeditoroptions === null) {
4249 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4251 return self::$summaryeditoroptions;
4255 * Loads the properties for this course request object. Id is required and if
4256 * only id is provided then we load the rest of the properties from the database
4258 * @param stdClass|int $properties Either an object containing properties
4259 * or the course_request id to load
4261 public function __construct($properties) {
4262 global $DB;
4263 if (empty($properties->id)) {
4264 if (empty($properties)) {
4265 throw new coding_exception('You must provide a course request id when creating a course_request object');
4267 $id = $properties;
4268 $properties = new stdClass;
4269 $properties->id = (int)$id;
4270 unset($id);
4272 if (empty($properties->requester)) {
4273 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4274 print_error('unknowncourserequest');
4276 } else {
4277 $this->properties = $properties;
4279 $this->properties->collision = null;
4283 * Returns the requested property
4285 * @param string $key
4286 * @return mixed
4288 public function __get($key) {
4289 return $this->properties->$key;
4293 * Override this to ensure empty($request->blah) calls return a reliable answer...
4295 * This is required because we define the __get method
4297 * @param mixed $key
4298 * @return bool True is it not empty, false otherwise
4300 public function __isset($key) {
4301 return (!empty($this->properties->$key));
4305 * Returns the user who requested this course
4307 * Uses a static var to cache the results and cut down the number of db queries
4309 * @staticvar array $requesters An array of cached users
4310 * @return stdClass The user who requested the course
4312 public function get_requester() {
4313 global $DB;
4314 static $requesters= array();
4315 if (!array_key_exists($this->properties->requester, $requesters)) {
4316 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4318 return $requesters[$this->properties->requester];
4322 * Checks that the shortname used by the course does not conflict with any other
4323 * courses that exist
4325 * @param string|null $shortnamemark The string to append to the requests shortname
4326 * should a conflict be found
4327 * @return bool true is there is a conflict, false otherwise
4329 public function check_shortname_collision($shortnamemark = '[*]') {
4330 global $DB;
4332 if ($this->properties->collision !== null) {
4333 return $this->properties->collision;
4336 if (empty($this->properties->shortname)) {
4337 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4338 $this->properties->collision = false;
4339 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4340 if (!empty($shortnamemark)) {
4341 $this->properties->shortname .= ' '.$shortnamemark;
4343 $this->properties->collision = true;
4344 } else {
4345 $this->properties->collision = false;
4347 return $this->properties->collision;
4351 * This function approves the request turning it into a course
4353 * This function converts the course request into a course, at the same time
4354 * transferring any files used in the summary to the new course and then removing
4355 * the course request and the files associated with it.
4357 * @return int The id of the course that was created from this request
4359 public function approve() {
4360 global $CFG, $DB, $USER;
4362 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4364 $category = get_course_category($CFG->defaultrequestcategory);
4365 $courseconfig = get_config('moodlecourse');
4367 // Transfer appropriate settings
4368 $data = clone($this->properties);
4369 unset($data->id);
4370 unset($data->reason);
4371 unset($data->requester);
4373 // Set category
4374 $data->category = $category->id;
4375 $data->sortorder = $category->sortorder; // place as the first in category
4377 // Set misc settings
4378 $data->requested = 1;
4380 // Apply course default settings
4381 $data->format = $courseconfig->format;
4382 $data->numsections = $courseconfig->numsections;
4383 $data->hiddensections = $courseconfig->hiddensections;
4384 $data->newsitems = $courseconfig->newsitems;
4385 $data->showgrades = $courseconfig->showgrades;
4386 $data->showreports = $courseconfig->showreports;
4387 $data->maxbytes = $courseconfig->maxbytes;
4388 $data->groupmode = $courseconfig->groupmode;
4389 $data->groupmodeforce = $courseconfig->groupmodeforce;
4390 $data->visible = $courseconfig->visible;
4391 $data->visibleold = $data->visible;
4392 $data->lang = $courseconfig->lang;
4394 $course = create_course($data);
4395 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
4397 // add enrol instances
4398 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4399 if ($manual = enrol_get_plugin('manual')) {
4400 $manual->add_default_instance($course);
4404 // enrol the requester as teacher if necessary
4405 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4406 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4409 $this->delete();
4411 $a = new stdClass();
4412 $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
4413 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4414 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4416 return $course->id;
4420 * Reject a course request
4422 * This function rejects a course request, emailing the requesting user the
4423 * provided notice and then removing the request from the database
4425 * @param string $notice The message to display to the user
4427 public function reject($notice) {
4428 global $USER, $DB;
4429 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4430 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4431 $this->delete();
4435 * Deletes the course request and any associated files
4437 public function delete() {
4438 global $DB;
4439 $DB->delete_records('course_request', array('id' => $this->properties->id));
4443 * Send a message from one user to another using events_trigger
4445 * @param object $touser
4446 * @param object $fromuser
4447 * @param string $name
4448 * @param string $subject
4449 * @param string $message
4451 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4452 $eventdata = new stdClass();
4453 $eventdata->component = 'moodle';
4454 $eventdata->name = $name;
4455 $eventdata->userfrom = $fromuser;
4456 $eventdata->userto = $touser;
4457 $eventdata->subject = $subject;
4458 $eventdata->fullmessage = $message;
4459 $eventdata->fullmessageformat = FORMAT_PLAIN;
4460 $eventdata->fullmessagehtml = '';
4461 $eventdata->smallmessage = '';
4462 $eventdata->notification = 1;
4463 message_send($eventdata);
4468 * Return a list of page types
4469 * @param string $pagetype current page type
4470 * @param stdClass $parentcontext Block's parent context
4471 * @param stdClass $currentcontext Current context of block
4473 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4474 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
4475 if (isset($currentcontext)) {
4476 // if above course context ,display all course fomats
4477 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4478 if ($course->id == SITEID) {
4479 return array('*'=>get_string('page-x', 'pagetype'));
4482 return array('*'=>get_string('page-x', 'pagetype'),
4483 'course-*'=>get_string('page-course-x', 'pagetype'),
4484 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4489 * Determine whether course ajax should be enabled for the specified course
4491 * @param stdClass $course The course to test against
4492 * @return boolean Whether course ajax is enabled or note
4494 function course_ajax_enabled($course) {
4495 global $CFG, $PAGE, $SITE;
4497 // Ajax must be enabled globally
4498 if (!$CFG->enableajax) {
4499 return false;
4502 // The user must be editing for AJAX to be included
4503 if (!$PAGE->user_is_editing()) {
4504 return false;
4507 // Check that the theme suports
4508 if (!$PAGE->theme->enablecourseajax) {
4509 return false;
4512 // Check that the course format supports ajax functionality
4513 // The site 'format' doesn't have information on course format support
4514 if ($SITE->id !== $course->id) {
4515 $courseformatajaxsupport = course_format_ajax_support($course->format);
4516 if (!$courseformatajaxsupport->capable) {
4517 return false;
4521 // All conditions have been met so course ajax should be enabled
4522 return true;
4526 * Include the relevant javascript and language strings for the resource
4527 * toolbox YUI module
4529 * @param integer $id The ID of the course being applied to
4530 * @param array $usedmodules An array containing the names of the modules in use on the page
4531 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4532 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4533 * * resourceurl The URL to post changes to for resource changes
4534 * * sectionurl The URL to post changes to for section changes
4535 * * pageparams Additional parameters to pass through in the post
4536 * @return bool
4538 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4539 global $PAGE, $SITE;
4541 // Ensure that ajax should be included
4542 if (!course_ajax_enabled($course)) {
4543 return false;
4546 if (!$config) {
4547 $config = new stdClass();
4550 // The URL to use for resource changes
4551 if (!isset($config->resourceurl)) {
4552 $config->resourceurl = '/course/rest.php';
4555 // The URL to use for section changes
4556 if (!isset($config->sectionurl)) {
4557 $config->sectionurl = '/course/rest.php';
4560 // Any additional parameters which need to be included on page submission
4561 if (!isset($config->pageparams)) {
4562 $config->pageparams = array();
4565 // Include toolboxes
4566 $PAGE->requires->yui_module('moodle-course-toolboxes',
4567 'M.course.init_resource_toolbox',
4568 array(array(
4569 'courseid' => $course->id,
4570 'ajaxurl' => $config->resourceurl,
4571 'config' => $config,
4574 $PAGE->requires->yui_module('moodle-course-toolboxes',
4575 'M.course.init_section_toolbox',
4576 array(array(
4577 'courseid' => $course->id,
4578 'format' => $course->format,
4579 'ajaxurl' => $config->sectionurl,
4580 'config' => $config,
4584 // Include course dragdrop
4585 if ($course->id != $SITE->id) {
4586 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4587 array(array(
4588 'courseid' => $course->id,
4589 'ajaxurl' => $config->sectionurl,
4590 'config' => $config,
4591 )), null, true);
4593 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4594 array(array(
4595 'courseid' => $course->id,
4596 'ajaxurl' => $config->resourceurl,
4597 'config' => $config,
4598 )), null, true);
4601 // Include blocks dragdrop
4602 $params = array(
4603 'courseid' => $course->id,
4604 'pagetype' => $PAGE->pagetype,
4605 'pagelayout' => $PAGE->pagelayout,
4606 'subpage' => $PAGE->subpage,
4607 'regions' => $PAGE->blocks->get_regions(),
4609 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4611 // Require various strings for the command toolbox
4612 $PAGE->requires->strings_for_js(array(
4613 'moveleft',
4614 'deletechecktype',
4615 'deletechecktypename',
4616 'edittitle',
4617 'edittitleinstructions',
4618 'show',
4619 'hide',
4620 'groupsnone',
4621 'groupsvisible',
4622 'groupsseparate',
4623 'clicktochangeinbrackets',
4624 'markthistopic',
4625 'markedthistopic',
4626 'move',
4627 'movesection',
4628 ), 'moodle');
4630 // Include format-specific strings
4631 if ($course->id != $SITE->id) {
4632 $PAGE->requires->strings_for_js(array(
4633 'showfromothers',
4634 'hidefromothers',
4635 ), 'format_' . $course->format);
4638 // For confirming resource deletion we need the name of the module in question
4639 foreach ($usedmodules as $module => $modname) {
4640 $PAGE->requires->string_for_js('pluginname', $module);
4643 // Load drag and drop upload AJAX.
4644 dndupload_add_to_course($course, $enabledmodules);
4646 // Add the module chooser
4647 $PAGE->requires->yui_module('moodle-course-modchooser',
4648 'M.course.init_chooser',
4649 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
4651 $PAGE->requires->strings_for_js(array(
4652 'addresourceoractivity',
4653 'modchooserenable',
4654 'modchooserdisable',
4655 ), 'moodle');
4657 return true;
4661 * The URL to use for the specified course (with section)
4663 * @param stdClass $course The course to get the section name for
4664 * @param int $sectionno The section number to return a link to
4665 * if omitted the course view page is returned
4666 * @param array $options options for view URL. At the moment core uses:
4667 * 'navigation' (bool) if true and section has no separate page, the function returns null
4668 * 'sr' (int) used by multipage formats to specify to which section to return
4669 * @return moodle_url The url of course
4671 function course_get_url($course, $sectionno = null, $options = array()) {
4672 if ($course->id == SITEID) {
4673 return new moodle_url('/');
4675 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4677 $sr = null;
4678 if (array_key_exists('sr', $options)) {
4679 $sr = $options['sr'];
4681 if ($sectionno !== null) {
4682 if ($sr !== null) {
4683 if ($sr) {
4684 $usercoursedisplay = COURSE_DISPLAY_MULTIPAGE;
4685 $sectionno = $sr;
4686 } else {
4687 $usercoursedisplay = COURSE_DISPLAY_SINGLEPAGE;
4689 } else {
4690 $usercoursedisplay = $course->coursedisplay;
4692 if ($sectionno != 0 && $usercoursedisplay == COURSE_DISPLAY_MULTIPAGE) {
4693 $url->param('section', $sectionno);
4694 } else {
4695 if (!empty($options['navigation'])) {
4696 return null;
4698 $url->set_anchor('section-'.$sectionno);
4702 return $url;