Merge branch 'w22_MDL-39676_m24_whereparam' of git://github.com/skodak/moodle into...
[moodle.git] / course / lib.php
blob18576c863078237ebdc9a302528534b980136e4e
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');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'calendar':
71 case 'category':
72 case 'mnet course':
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
75 } else {
76 $url = "/course/$url";
78 break;
79 case 'user':
80 case 'blog':
81 $url = "/$module/$url";
82 break;
83 case 'upload':
84 $url = $url;
85 break;
86 case 'coursetags':
87 $url = '/'.$url;
88 break;
89 case 'library':
90 case '':
91 $url = '/';
92 break;
93 case 'message':
94 $url = "/message/$url";
95 break;
96 case 'notes':
97 $url = "/notes/$url";
98 break;
99 case 'tag':
100 $url = "/tag/$url";
101 break;
102 case 'role':
103 $url = '/'.$url;
104 break;
105 default:
106 $url = "/mod/$module/$url";
107 break;
110 //now let's sanitise urls - there might be some ugly nasties:-(
111 $parts = explode('?', $url);
112 $script = array_shift($parts);
113 if (strpos($script, 'http') === 0) {
114 $script = clean_param($script, PARAM_URL);
115 } else {
116 $script = clean_param($script, PARAM_PATH);
119 $query = '';
120 if ($parts) {
121 $query = implode('', $parts);
122 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
123 $parts = explode('&', $query);
124 $eq = urlencode('=');
125 foreach ($parts as $key=>$part) {
126 $part = urlencode(urldecode($part));
127 $part = str_replace($eq, '=', $part);
128 $parts[$key] = $part;
130 $query = '?'.implode('&amp;', $parts);
133 return $script.$query;
137 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
138 $modname="", $modid=0, $modaction="", $groupid=0) {
139 global $CFG, $DB;
141 // It is assumed that $date is the GMT time of midnight for that day,
142 // and so the next 86400 seconds worth of logs are printed.
144 /// Setup for group handling.
146 // TODO: I don't understand group/context/etc. enough to be able to do
147 // something interesting with it here
148 // What is the context of a remote course?
150 /// If the group mode is separate, and this user does not have editing privileges,
151 /// then only the user's group can be viewed.
152 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
153 // $groupid = get_current_group($course->id);
155 /// If this course doesn't have groups, no groupid can be specified.
156 //else if (!$course->groupmode) {
157 // $groupid = 0;
160 $groupid = 0;
162 $joins = array();
163 $where = '';
165 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
166 FROM {mnet_log} l
167 LEFT JOIN {user} u ON l.userid = u.id
168 WHERE ";
169 $params = array();
171 $where .= "l.hostid = :hostid";
172 $params['hostid'] = $hostid;
174 // TODO: Is 1 really a magic number referring to the sitename?
175 if ($course != SITEID || $modid != 0) {
176 $where .= " AND l.course=:courseid";
177 $params['courseid'] = $course;
180 if ($modname) {
181 $where .= " AND l.module = :modname";
182 $params['modname'] = $modname;
185 if ('site_errors' === $modid) {
186 $where .= " AND ( l.action='error' OR l.action='infected' )";
187 } else if ($modid) {
188 //TODO: This assumes that modids are the same across sites... probably
189 //not true
190 $where .= " AND l.cmid = :modid";
191 $params['modid'] = $modid;
194 if ($modaction) {
195 $firstletter = substr($modaction, 0, 1);
196 if ($firstletter == '-') {
197 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
198 $params['modaction'] = '%'.substr($modaction, 1).'%';
199 } else {
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
201 $params['modaction'] = '%'.$modaction.'%';
205 if ($user) {
206 $where .= " AND l.userid = :user";
207 $params['user'] = $user;
210 if ($date) {
211 $enddate = $date + 86400;
212 $where .= " AND l.time > :date AND l.time < :enddate";
213 $params['date'] = $date;
214 $params['enddate'] = $enddate;
217 $result = array();
218 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
219 if(!empty($result['totalcount'])) {
220 $where .= " ORDER BY $order";
221 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
222 } else {
223 $result['logs'] = array();
225 return $result;
228 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
229 $modname="", $modid=0, $modaction="", $groupid=0) {
230 global $DB, $SESSION, $USER;
231 // It is assumed that $date is the GMT time of midnight for that day,
232 // and so the next 86400 seconds worth of logs are printed.
234 /// Setup for group handling.
236 /// If the group mode is separate, and this user does not have editing privileges,
237 /// then only the user's group can be viewed.
238 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
239 if (isset($SESSION->currentgroup[$course->id])) {
240 $groupid = $SESSION->currentgroup[$course->id];
241 } else {
242 $groupid = groups_get_all_groups($course->id, $USER->id);
243 if (is_array($groupid)) {
244 $groupid = array_shift(array_keys($groupid));
245 $SESSION->currentgroup[$course->id] = $groupid;
246 } else {
247 $groupid = 0;
251 /// If this course doesn't have groups, no groupid can be specified.
252 else if (!$course->groupmode) {
253 $groupid = 0;
256 $joins = array();
257 $params = array();
259 if ($course->id != SITEID || $modid != 0) {
260 $joins[] = "l.course = :courseid";
261 $params['courseid'] = $course->id;
264 if ($modname) {
265 $joins[] = "l.module = :modname";
266 $params['modname'] = $modname;
269 if ('site_errors' === $modid) {
270 $joins[] = "( l.action='error' OR l.action='infected' )";
271 } else if ($modid) {
272 $joins[] = "l.cmid = :modid";
273 $params['modid'] = $modid;
276 if ($modaction) {
277 $firstletter = substr($modaction, 0, 1);
278 if ($firstletter == '-') {
279 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
280 $params['modaction'] = '%'.substr($modaction, 1).'%';
281 } else {
282 $joins[] = $DB->sql_like('l.action', ':modaction', false);
283 $params['modaction'] = '%'.$modaction.'%';
288 /// Getting all members of a group.
289 if ($groupid and !$user) {
290 if ($gusers = groups_get_members($groupid)) {
291 $gusers = array_keys($gusers);
292 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
293 } else {
294 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
297 else if ($user) {
298 $joins[] = "l.userid = :userid";
299 $params['userid'] = $user;
302 if ($date) {
303 $enddate = $date + 86400;
304 $joins[] = "l.time > :date AND l.time < :enddate";
305 $params['date'] = $date;
306 $params['enddate'] = $enddate;
309 $selector = implode(' AND ', $joins);
311 $totalcount = 0; // Initialise
312 $result = array();
313 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
314 $result['totalcount'] = $totalcount;
315 return $result;
319 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
320 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
322 global $CFG, $DB, $OUTPUT;
324 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
325 $modname, $modid, $modaction, $groupid)) {
326 echo $OUTPUT->notification("No logs found!");
327 echo $OUTPUT->footer();
328 exit;
331 $courses = array();
333 if ($course->id == SITEID) {
334 $courses[0] = '';
335 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
336 foreach ($ccc as $cc) {
337 $courses[$cc->id] = $cc->shortname;
340 } else {
341 $courses[$course->id] = $course->shortname;
344 $totalcount = $logs['totalcount'];
345 $count=0;
346 $ldcache = array();
347 $tt = getdate(time());
348 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
350 $strftimedatetime = get_string("strftimedatetime");
352 echo "<div class=\"info\">\n";
353 print_string("displayingrecords", "", $totalcount);
354 echo "</div>\n";
356 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
358 $table = new html_table();
359 $table->classes = array('logtable','generalbox');
360 $table->align = array('right', 'left', 'left');
361 $table->head = array(
362 get_string('time'),
363 get_string('ip_address'),
364 get_string('fullnameuser'),
365 get_string('action'),
366 get_string('info')
368 $table->data = array();
370 if ($course->id == SITEID) {
371 array_unshift($table->align, 'left');
372 array_unshift($table->head, get_string('course'));
375 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
376 if (empty($logs['logs'])) {
377 $logs['logs'] = array();
380 foreach ($logs['logs'] as $log) {
382 if (isset($ldcache[$log->module][$log->action])) {
383 $ld = $ldcache[$log->module][$log->action];
384 } else {
385 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
386 $ldcache[$log->module][$log->action] = $ld;
388 if ($ld && is_numeric($log->info)) {
389 // ugly hack to make sure fullname is shown correctly
390 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
391 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
392 } else {
393 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
397 //Filter log->info
398 $log->info = format_string($log->info);
400 // If $log->url has been trimmed short by the db size restriction
401 // code in add_to_log, keep a note so we don't add a link to a broken url
402 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
404 $row = array();
405 if ($course->id == SITEID) {
406 if (empty($log->course)) {
407 $row[] = get_string('site');
408 } else {
409 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
413 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
415 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
416 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
418 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
420 $displayaction="$log->module $log->action";
421 if ($brokenurl) {
422 $row[] = $displayaction;
423 } else {
424 $link = make_log_url($log->module,$log->url);
425 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
427 $row[] = $log->info;
428 $table->data[] = $row;
431 echo html_writer::table($table);
432 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
436 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG, $DB, $OUTPUT;
441 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 echo $OUTPUT->notification("No logs found!");
444 echo $OUTPUT->footer();
445 exit;
448 if ($course->id == SITEID) {
449 $courses[0] = '';
450 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
451 foreach ($ccc as $cc) {
452 $courses[$cc->id] = $cc->shortname;
457 $totalcount = $logs['totalcount'];
458 $count=0;
459 $ldcache = array();
460 $tt = getdate(time());
461 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
463 $strftimedatetime = get_string("strftimedatetime");
465 echo "<div class=\"info\">\n";
466 print_string("displayingrecords", "", $totalcount);
467 echo "</div>\n";
469 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
471 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
472 echo "<tr>";
473 if ($course->id == SITEID) {
474 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
476 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
477 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
478 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
479 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
480 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
481 echo "</tr>\n";
483 if (empty($logs['logs'])) {
484 echo "</table>\n";
485 return;
488 $row = 1;
489 foreach ($logs['logs'] as $log) {
491 $log->info = $log->coursename;
492 $row = ($row + 1) % 2;
494 if (isset($ldcache[$log->module][$log->action])) {
495 $ld = $ldcache[$log->module][$log->action];
496 } else {
497 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
498 $ldcache[$log->module][$log->action] = $ld;
500 if (0 && $ld && !empty($log->info)) {
501 // ugly hack to make sure fullname is shown correctly
502 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
503 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
504 } else {
505 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
509 //Filter log->info
510 $log->info = format_string($log->info);
512 echo '<tr class="r'.$row.'">';
513 if ($course->id == SITEID) {
514 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
515 echo "<td class=\"r$row c0\" >\n";
516 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
517 echo "</td>\n";
519 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
520 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
521 echo "<td class=\"r$row c2\" >\n";
522 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
523 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
524 echo "</td>\n";
525 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
526 echo "<td class=\"r$row c3\" >\n";
527 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
528 echo "</td>\n";
529 echo "<td class=\"r$row c4\">\n";
530 echo $log->action .': '.$log->module;
531 echo "</td>\n";;
532 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
533 echo "</tr>\n";
535 echo "</table>\n";
537 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
541 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
542 $modid, $modaction, $groupid) {
543 global $DB, $CFG;
545 require_once($CFG->libdir . '/csvlib.class.php');
547 $csvexporter = new csv_export_writer('tab');
549 $header = array();
550 $header[] = get_string('course');
551 $header[] = get_string('time');
552 $header[] = get_string('ip_address');
553 $header[] = get_string('fullnameuser');
554 $header[] = get_string('action');
555 $header[] = get_string('info');
557 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
558 $modname, $modid, $modaction, $groupid)) {
559 return false;
562 $courses = array();
564 if ($course->id == SITEID) {
565 $courses[0] = '';
566 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
567 foreach ($ccc as $cc) {
568 $courses[$cc->id] = $cc->shortname;
571 } else {
572 $courses[$course->id] = $course->shortname;
575 $count=0;
576 $ldcache = array();
577 $tt = getdate(time());
578 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
580 $strftimedatetime = get_string("strftimedatetime");
582 $csvexporter->set_filename('logs', '.txt');
583 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
584 $csvexporter->add_data($title);
585 $csvexporter->add_data($header);
587 if (empty($logs['logs'])) {
588 return true;
591 foreach ($logs['logs'] as $log) {
592 if (isset($ldcache[$log->module][$log->action])) {
593 $ld = $ldcache[$log->module][$log->action];
594 } else {
595 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
596 $ldcache[$log->module][$log->action] = $ld;
598 if ($ld && is_numeric($log->info)) {
599 // ugly hack to make sure fullname is shown correctly
600 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
601 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
602 } else {
603 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
607 //Filter log->info
608 $log->info = format_string($log->info);
609 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
611 $coursecontext = context_course::instance($course->id);
612 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
613 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
614 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
615 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
616 $csvexporter->add_data($row);
618 $csvexporter->download_file();
619 return true;
623 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
624 $modid, $modaction, $groupid) {
626 global $CFG, $DB;
628 require_once("$CFG->libdir/excellib.class.php");
630 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
631 $modname, $modid, $modaction, $groupid)) {
632 return false;
635 $courses = array();
637 if ($course->id == SITEID) {
638 $courses[0] = '';
639 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
640 foreach ($ccc as $cc) {
641 $courses[$cc->id] = $cc->shortname;
644 } else {
645 $courses[$course->id] = $course->shortname;
648 $count=0;
649 $ldcache = array();
650 $tt = getdate(time());
651 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
653 $strftimedatetime = get_string("strftimedatetime");
655 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
656 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
657 $filename .= '.xls';
659 $workbook = new MoodleExcelWorkbook('-');
660 $workbook->send($filename);
662 $worksheet = array();
663 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
664 get_string('fullnameuser'), get_string('action'), get_string('info'));
666 // Creating worksheets
667 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
668 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
669 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
670 $worksheet[$wsnumber]->set_column(1, 1, 30);
671 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
672 userdate(time(), $strftimedatetime));
673 $col = 0;
674 foreach ($headers as $item) {
675 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
676 $col++;
680 if (empty($logs['logs'])) {
681 $workbook->close();
682 return true;
685 $formatDate =& $workbook->add_format();
686 $formatDate->set_num_format(get_string('log_excel_date_format'));
688 $row = FIRSTUSEDEXCELROW;
689 $wsnumber = 1;
690 $myxls =& $worksheet[$wsnumber];
691 foreach ($logs['logs'] as $log) {
692 if (isset($ldcache[$log->module][$log->action])) {
693 $ld = $ldcache[$log->module][$log->action];
694 } else {
695 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
696 $ldcache[$log->module][$log->action] = $ld;
698 if ($ld && is_numeric($log->info)) {
699 // ugly hack to make sure fullname is shown correctly
700 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
701 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
702 } else {
703 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
707 // Filter log->info
708 $log->info = format_string($log->info);
709 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
711 if ($nroPages>1) {
712 if ($row > EXCELROWS) {
713 $wsnumber++;
714 $myxls =& $worksheet[$wsnumber];
715 $row = FIRSTUSEDEXCELROW;
719 $coursecontext = context_course::instance($course->id);
721 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
722 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
723 $myxls->write($row, 2, $log->ip, '');
724 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
725 $myxls->write($row, 3, $fullname, '');
726 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
727 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
728 $myxls->write($row, 5, $log->info, '');
730 $row++;
733 $workbook->close();
734 return true;
737 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
738 $modid, $modaction, $groupid) {
740 global $CFG, $DB;
742 require_once("$CFG->libdir/odslib.class.php");
744 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
745 $modname, $modid, $modaction, $groupid)) {
746 return false;
749 $courses = array();
751 if ($course->id == SITEID) {
752 $courses[0] = '';
753 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
754 foreach ($ccc as $cc) {
755 $courses[$cc->id] = $cc->shortname;
758 } else {
759 $courses[$course->id] = $course->shortname;
762 $count=0;
763 $ldcache = array();
764 $tt = getdate(time());
765 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
767 $strftimedatetime = get_string("strftimedatetime");
769 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
770 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
771 $filename .= '.ods';
773 $workbook = new MoodleODSWorkbook('-');
774 $workbook->send($filename);
776 $worksheet = array();
777 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
778 get_string('fullnameuser'), get_string('action'), get_string('info'));
780 // Creating worksheets
781 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
782 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
783 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
784 $worksheet[$wsnumber]->set_column(1, 1, 30);
785 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
786 userdate(time(), $strftimedatetime));
787 $col = 0;
788 foreach ($headers as $item) {
789 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
790 $col++;
794 if (empty($logs['logs'])) {
795 $workbook->close();
796 return true;
799 $formatDate =& $workbook->add_format();
800 $formatDate->set_num_format(get_string('log_excel_date_format'));
802 $row = FIRSTUSEDEXCELROW;
803 $wsnumber = 1;
804 $myxls =& $worksheet[$wsnumber];
805 foreach ($logs['logs'] as $log) {
806 if (isset($ldcache[$log->module][$log->action])) {
807 $ld = $ldcache[$log->module][$log->action];
808 } else {
809 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
810 $ldcache[$log->module][$log->action] = $ld;
812 if ($ld && is_numeric($log->info)) {
813 // ugly hack to make sure fullname is shown correctly
814 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
815 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
816 } else {
817 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
821 // Filter log->info
822 $log->info = format_string($log->info);
823 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
825 if ($nroPages>1) {
826 if ($row > EXCELROWS) {
827 $wsnumber++;
828 $myxls =& $worksheet[$wsnumber];
829 $row = FIRSTUSEDEXCELROW;
833 $coursecontext = context_course::instance($course->id);
835 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
836 $myxls->write_date($row, 1, $log->time);
837 $myxls->write_string($row, 2, $log->ip);
838 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
839 $myxls->write_string($row, 3, $fullname);
840 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
841 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
842 $myxls->write_string($row, 5, $log->info);
844 $row++;
847 $workbook->close();
848 return true;
852 function print_overview($courses, array $remote_courses=array()) {
853 global $CFG, $USER, $DB, $OUTPUT;
855 $htmlarray = array();
856 if ($modules = $DB->get_records('modules')) {
857 foreach ($modules as $mod) {
858 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
859 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
860 $fname = $mod->name.'_print_overview';
861 if (function_exists($fname)) {
862 $fname($courses,$htmlarray);
867 foreach ($courses as $course) {
868 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
869 echo $OUTPUT->box_start('coursebox');
870 $attributes = array('title' => s($fullname));
871 if (empty($course->visible)) {
872 $attributes['class'] = 'dimmed';
874 echo $OUTPUT->heading(html_writer::link(
875 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
876 if (array_key_exists($course->id,$htmlarray)) {
877 foreach ($htmlarray[$course->id] as $modname => $html) {
878 echo $html;
881 echo $OUTPUT->box_end();
884 if (!empty($remote_courses)) {
885 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
887 foreach ($remote_courses as $course) {
888 echo $OUTPUT->box_start('coursebox');
889 $attributes = array('title' => s($course->fullname));
890 echo $OUTPUT->heading(html_writer::link(
891 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
892 format_string($course->shortname),
893 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
894 echo $OUTPUT->box_end();
900 * This function trawls through the logs looking for
901 * anything new since the user's last login
903 function print_recent_activity($course) {
904 // $course is an object
905 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
907 $context = context_course::instance($course->id);
909 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
911 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
913 if (!isguestuser()) {
914 if (!empty($USER->lastcourseaccess[$course->id])) {
915 if ($USER->lastcourseaccess[$course->id] > $timestart) {
916 $timestart = $USER->lastcourseaccess[$course->id];
921 echo '<div class="activitydate">';
922 echo get_string('activitysince', '', userdate($timestart));
923 echo '</div>';
924 echo '<div class="activityhead">';
926 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
928 echo "</div>\n";
930 $content = false;
932 /// Firstly, have there been any new enrolments?
934 $users = get_recent_enrolments($course->id, $timestart);
936 //Accessibility: new users now appear in an <OL> list.
937 if ($users) {
938 echo '<div class="newusers">';
939 echo $OUTPUT->heading(get_string("newusers").':', 3);
940 $content = true;
941 echo "<ol class=\"list\">\n";
942 foreach ($users as $user) {
943 $fullname = fullname($user, $viewfullnames);
944 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
946 echo "</ol>\n</div>\n";
949 /// Next, have there been any modifications to the course structure?
951 $modinfo = get_fast_modinfo($course);
953 $changelist = array();
955 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
956 module = 'course' AND
957 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
958 array($timestart, $course->id), "id ASC");
960 if ($logs) {
961 $actions = array('add mod', 'update mod', 'delete mod');
962 $newgones = array(); // added and later deleted items
963 foreach ($logs as $key => $log) {
964 if (!in_array($log->action, $actions)) {
965 continue;
967 $info = explode(' ', $log->info);
969 // note: in most cases I replaced hardcoding of label with use of
970 // $cm->has_view() but it was not possible to do this here because
971 // we don't necessarily have the $cm for it
972 if ($info[0] == 'label') { // Labels are ignored in recent activity
973 continue;
976 if (count($info) != 2) {
977 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
978 continue;
981 $modname = $info[0];
982 $instanceid = $info[1];
984 if ($log->action == 'delete mod') {
985 // unfortunately we do not know if the mod was visible
986 if (!array_key_exists($log->info, $newgones)) {
987 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
988 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
990 } else {
991 if (!isset($modinfo->instances[$modname][$instanceid])) {
992 if ($log->action == 'add mod') {
993 // do not display added and later deleted activities
994 $newgones[$log->info] = true;
996 continue;
998 $cm = $modinfo->instances[$modname][$instanceid];
999 if (!$cm->uservisible) {
1000 continue;
1003 if ($log->action == 'add mod') {
1004 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1005 $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>");
1007 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1008 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1009 $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>");
1015 if (!empty($changelist)) {
1016 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1017 $content = true;
1018 foreach ($changelist as $changeinfo => $change) {
1019 echo '<p class="activity">'.$change['text'].'</p>';
1023 /// Now display new things from each module
1025 $usedmodules = array();
1026 foreach($modinfo->cms as $cm) {
1027 if (isset($usedmodules[$cm->modname])) {
1028 continue;
1030 if (!$cm->uservisible) {
1031 continue;
1033 $usedmodules[$cm->modname] = $cm->modname;
1036 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1037 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1038 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1039 $print_recent_activity = $modname.'_print_recent_activity';
1040 if (function_exists($print_recent_activity)) {
1041 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1042 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1044 } else {
1045 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1049 if (! $content) {
1050 echo '<p class="message">'.get_string('nothingnew').'</p>';
1055 * For a given course, returns an array of course activity objects
1056 * Each item in the array contains he following properties:
1058 function get_array_of_activities($courseid) {
1059 // cm - course module id
1060 // mod - name of the module (eg forum)
1061 // section - the number of the section (eg week or topic)
1062 // name - the name of the instance
1063 // visible - is the instance visible or not
1064 // groupingid - grouping id
1065 // groupmembersonly - is this instance visible to group members only
1066 // extra - contains extra string to include in any link
1067 global $CFG, $DB;
1068 if(!empty($CFG->enableavailability)) {
1069 require_once($CFG->libdir.'/conditionlib.php');
1072 $course = $DB->get_record('course', array('id'=>$courseid));
1074 if (empty($course)) {
1075 throw new moodle_exception('courseidnotfound');
1078 $mod = array();
1080 $rawmods = get_course_mods($courseid);
1081 if (empty($rawmods)) {
1082 return $mod; // always return array
1085 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1086 foreach ($sections as $section) {
1087 if (!empty($section->sequence)) {
1088 $sequence = explode(",", $section->sequence);
1089 foreach ($sequence as $seq) {
1090 if (empty($rawmods[$seq])) {
1091 continue;
1093 $mod[$seq] = new stdClass();
1094 $mod[$seq]->id = $rawmods[$seq]->instance;
1095 $mod[$seq]->cm = $rawmods[$seq]->id;
1096 $mod[$seq]->mod = $rawmods[$seq]->modname;
1098 // Oh dear. Inconsistent names left here for backward compatibility.
1099 $mod[$seq]->section = $section->section;
1100 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1102 $mod[$seq]->module = $rawmods[$seq]->module;
1103 $mod[$seq]->added = $rawmods[$seq]->added;
1104 $mod[$seq]->score = $rawmods[$seq]->score;
1105 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1106 $mod[$seq]->visible = $rawmods[$seq]->visible;
1107 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1108 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1109 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1110 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1111 $mod[$seq]->indent = $rawmods[$seq]->indent;
1112 $mod[$seq]->completion = $rawmods[$seq]->completion;
1113 $mod[$seq]->extra = "";
1114 $mod[$seq]->completiongradeitemnumber =
1115 $rawmods[$seq]->completiongradeitemnumber;
1116 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1117 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1118 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1119 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1120 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1121 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1122 if (!empty($CFG->enableavailability)) {
1123 condition_info::fill_availability_conditions($rawmods[$seq]);
1124 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1125 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1126 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1129 $modname = $mod[$seq]->mod;
1130 $functionname = $modname."_get_coursemodule_info";
1132 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1133 continue;
1136 include_once("$CFG->dirroot/mod/$modname/lib.php");
1138 if ($hasfunction = function_exists($functionname)) {
1139 if ($info = $functionname($rawmods[$seq])) {
1140 if (!empty($info->icon)) {
1141 $mod[$seq]->icon = $info->icon;
1143 if (!empty($info->iconcomponent)) {
1144 $mod[$seq]->iconcomponent = $info->iconcomponent;
1146 if (!empty($info->name)) {
1147 $mod[$seq]->name = $info->name;
1149 if ($info instanceof cached_cm_info) {
1150 // When using cached_cm_info you can include three new fields
1151 // that aren't available for legacy code
1152 if (!empty($info->content)) {
1153 $mod[$seq]->content = $info->content;
1155 if (!empty($info->extraclasses)) {
1156 $mod[$seq]->extraclasses = $info->extraclasses;
1158 if (!empty($info->iconurl)) {
1159 $mod[$seq]->iconurl = $info->iconurl;
1161 if (!empty($info->onclick)) {
1162 $mod[$seq]->onclick = $info->onclick;
1164 if (!empty($info->customdata)) {
1165 $mod[$seq]->customdata = $info->customdata;
1167 } else {
1168 // When using a stdclass, the (horrible) deprecated ->extra field
1169 // is available for BC
1170 if (!empty($info->extra)) {
1171 $mod[$seq]->extra = $info->extra;
1176 // When there is no modname_get_coursemodule_info function,
1177 // but showdescriptions is enabled, then we use the 'intro'
1178 // and 'introformat' fields in the module table
1179 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1180 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1181 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1182 // Set content from intro and introformat. Filters are disabled
1183 // because we filter it with format_text at display time
1184 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1185 $modvalues, $rawmods[$seq]->id, false);
1187 // To save making another query just below, put name in here
1188 $mod[$seq]->name = $modvalues->name;
1191 if (!isset($mod[$seq]->name)) {
1192 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1195 // Minimise the database size by unsetting default options when they are
1196 // 'empty'. This list corresponds to code in the cm_info constructor.
1197 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1198 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1199 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1200 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1201 'completionview', 'completionexpected', 'score', 'showdescription')
1202 as $property) {
1203 if (property_exists($mod[$seq], $property) &&
1204 empty($mod[$seq]->{$property})) {
1205 unset($mod[$seq]->{$property});
1208 // Special case: this value is usually set to null, but may be 0
1209 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1210 is_null($mod[$seq]->completiongradeitemnumber)) {
1211 unset($mod[$seq]->completiongradeitemnumber);
1217 return $mod;
1221 * Returns the localised human-readable names of all used modules
1223 * @param bool $plural if true returns the plural forms of the names
1224 * @return array where key is the module name (component name without 'mod_') and
1225 * the value is the human-readable string. Array sorted alphabetically by value
1227 function get_module_types_names($plural = false) {
1228 static $modnames = null;
1229 global $DB, $CFG;
1230 if ($modnames === null) {
1231 $modnames = array(0 => array(), 1 => array());
1232 if ($allmods = $DB->get_records("modules")) {
1233 foreach ($allmods as $mod) {
1234 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1235 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1236 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1239 collatorlib::asort($modnames[0]);
1240 collatorlib::asort($modnames[1]);
1243 return $modnames[(int)$plural];
1247 * Set highlighted section. Only one section can be highlighted at the time.
1249 * @param int $courseid course id
1250 * @param int $marker highlight section with this number, 0 means remove higlightin
1251 * @return void
1253 function course_set_marker($courseid, $marker) {
1254 global $DB;
1255 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1256 format_base::reset_course_cache($courseid);
1260 * For a given course section, marks it visible or hidden,
1261 * and does the same for every activity in that section
1263 * @param int $courseid course id
1264 * @param int $sectionnumber The section number to adjust
1265 * @param int $visibility The new visibility
1266 * @return array A list of resources which were hidden in the section
1268 function set_section_visible($courseid, $sectionnumber, $visibility) {
1269 global $DB;
1271 $resourcestotoggle = array();
1272 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1273 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1274 if (!empty($section->sequence)) {
1275 $modules = explode(",", $section->sequence);
1276 foreach ($modules as $moduleid) {
1277 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1278 if ($visibility) {
1279 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1280 set_coursemodule_visible($moduleid, $cm->visibleold);
1281 } else {
1282 // We hide the section, so we hide the module but we store the original state in visibleold.
1283 set_coursemodule_visible($moduleid, 0);
1284 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1289 rebuild_course_cache($courseid, true);
1291 // Determine which modules are visible for AJAX update
1292 if (!empty($modules)) {
1293 list($insql, $params) = $DB->get_in_or_equal($modules);
1294 $select = 'id ' . $insql . ' AND visible = ?';
1295 array_push($params, $visibility);
1296 if (!$visibility) {
1297 $select .= ' AND visibleold = 1';
1299 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1302 return $resourcestotoggle;
1306 * Obtains shared data that is used in print_section when displaying a
1307 * course-module entry.
1309 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1311 * This data is also used in other areas of the code.
1312 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1313 * @param object $course Moodle course object
1314 * @return array An array with the following values in this order:
1315 * $content (optional extra content for after link),
1316 * $instancename (text of link)
1318 function get_print_section_cm_text(cm_info $cm, $course) {
1319 global $OUTPUT;
1321 // Get content from modinfo if specified. Content displays either
1322 // in addition to the standard link (below), or replaces it if
1323 // the link is turned off by setting ->url to null.
1324 if (($content = $cm->get_content()) !== '') {
1325 // Improve filter performance by preloading filter setttings for all
1326 // activities on the course (this does nothing if called multiple
1327 // times)
1328 filter_preload_activities($cm->get_modinfo());
1330 // Get module context
1331 $modulecontext = context_module::instance($cm->id);
1332 $labelformatoptions = new stdClass();
1333 $labelformatoptions->noclean = true;
1334 $labelformatoptions->overflowdiv = true;
1335 $labelformatoptions->context = $modulecontext;
1336 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1337 } else {
1338 $content = '';
1341 // Get course context
1342 $coursecontext = context_course::instance($course->id);
1343 $stringoptions = new stdClass;
1344 $stringoptions->context = $coursecontext;
1345 $instancename = format_string($cm->name, true, $stringoptions);
1346 return array($content, $instancename);
1350 * Prints a section full of activity modules
1352 * @param stdClass $course The course
1353 * @param stdClass|section_info $section The section object containing properties id and section
1354 * @param array $mods (argument not used)
1355 * @param array $modnamesused (argument not used)
1356 * @param bool $absolute All links are absolute
1357 * @param string $width Width of the container
1358 * @param bool $hidecompletion Hide completion status
1359 * @param int $sectionreturn The section to return to
1360 * @return void
1362 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1363 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1365 static $initialised;
1367 static $groupbuttons;
1368 static $groupbuttonslink;
1369 static $isediting;
1370 static $ismoving;
1371 static $strmovehere;
1372 static $strmovefull;
1373 static $strunreadpostsone;
1375 if (!isset($initialised)) {
1376 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1377 $groupbuttonslink = (!$course->groupmodeforce);
1378 $isediting = $PAGE->user_is_editing();
1379 $ismoving = $isediting && ismoving($course->id);
1380 if ($ismoving) {
1381 $strmovehere = get_string("movehere");
1382 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1384 $initialised = true;
1387 $modinfo = get_fast_modinfo($course);
1388 $completioninfo = new completion_info($course);
1390 //Accessibility: replace table with list <ul>, but don't output empty list.
1391 if (!empty($modinfo->sections[$section->section])) {
1393 // Fix bug #5027, don't want style=\"width:$width\".
1394 echo "<ul class=\"section img-text\">\n";
1396 foreach ($modinfo->sections[$section->section] as $modnumber) {
1397 $mod = $modinfo->cms[$modnumber];
1399 if ($ismoving and $mod->id == $USER->activitycopy) {
1400 // do not display moving mod
1401 continue;
1404 // We can continue (because it will not be displayed at all)
1405 // if:
1406 // 1) The activity is not visible to users
1407 // and
1408 // 2a) The 'showavailability' option is not set (if that is set,
1409 // we need to display the activity so we can show
1410 // availability info)
1411 // or
1412 // 2b) The 'availableinfo' is empty, i.e. the activity was
1413 // hidden in a way that leaves no info, such as using the
1414 // eye icon.
1415 if (!$mod->uservisible &&
1416 (empty($mod->showavailability) ||
1417 empty($mod->availableinfo))) {
1418 // visibility shortcut
1419 continue;
1422 // In some cases the activity is visible to user, but it is
1423 // dimmed. This is done if viewhiddenactivities is true and if:
1424 // 1. the activity is not visible, or
1425 // 2. the activity has dates set which do not include current, or
1426 // 3. the activity has any other conditions set (regardless of whether
1427 // current user meets them)
1428 $modcontext = context_module::instance($mod->id);
1429 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1430 $accessiblebutdim = false;
1431 $conditionalhidden = false;
1432 if ($canviewhidden) {
1433 $accessiblebutdim = !$mod->visible;
1434 if (!empty($CFG->enableavailability)) {
1435 $conditionalhidden = $mod->availablefrom > time() ||
1436 ($mod->availableuntil && $mod->availableuntil < time()) ||
1437 count($mod->conditionsgrade) > 0 ||
1438 count($mod->conditionscompletion) > 0;
1440 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1443 $liclasses = array();
1444 $liclasses[] = 'activity';
1445 $liclasses[] = $mod->modname;
1446 $liclasses[] = 'modtype_'.$mod->modname;
1447 $extraclasses = $mod->get_extra_classes();
1448 if ($extraclasses) {
1449 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1451 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1452 if ($ismoving) {
1453 echo '<a title="'.$strmovefull.'"'.
1454 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1455 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1456 ' alt="'.$strmovehere.'" /></a><br />
1460 $classes = array('mod-indent');
1461 if (!empty($mod->indent)) {
1462 $classes[] = 'mod-indent-'.$mod->indent;
1463 if ($mod->indent > 15) {
1464 $classes[] = 'mod-indent-huge';
1467 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1469 // Get data about this course-module
1470 list($content, $instancename) =
1471 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1473 //Accessibility: for files get description via icon, this is very ugly hack!
1474 $altname = '';
1475 $altname = $mod->modfullname;
1476 // Avoid unnecessary duplication: if e.g. a forum name already
1477 // includes the word forum (or Forum, etc) then it is unhelpful
1478 // to include that in the accessible description that is added.
1479 if (false !== strpos(textlib::strtolower($instancename),
1480 textlib::strtolower($altname))) {
1481 $altname = '';
1483 // File type after name, for alphabetic lists (screen reader).
1484 if ($altname) {
1485 $altname = get_accesshide(' '.$altname);
1488 // Start the div for the activity title, excluding the edit icons.
1489 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1491 // We may be displaying this just in order to show information
1492 // about visibility, without the actual link
1493 $contentpart = '';
1494 if ($mod->uservisible) {
1495 // Nope - in this case the link is fully working for user
1496 $linkclasses = '';
1497 $textclasses = '';
1498 if ($accessiblebutdim) {
1499 $linkclasses .= ' dimmed';
1500 $textclasses .= ' dimmed_text';
1501 if ($conditionalhidden) {
1502 $linkclasses .= ' conditionalhidden';
1503 $textclasses .= ' conditionalhidden';
1505 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1506 } else {
1507 $accesstext = '';
1509 if ($linkclasses) {
1510 $linkcss = trim($linkclasses) . ' ';
1511 } else {
1512 $linkcss = '';
1514 if ($textclasses) {
1515 $textcss = trim($textclasses) . ' ';
1516 } else {
1517 $textcss = '';
1520 // Get on-click attribute value if specified and decode the onclick - it
1521 // has already been encoded for display (puke).
1522 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
1524 $groupinglabel = '';
1525 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1526 $groupings = groups_get_all_groupings($course->id);
1527 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
1528 array('class' => 'groupinglabel'));
1531 if ($url = $mod->get_url()) {
1532 // Display link itself.
1533 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1534 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1535 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
1536 echo html_writer::link($url, $activitylink, array('class' => $linkcss, 'onclick' => $onclick)) .
1537 $groupinglabel;
1539 // If specified, display extra content after link.
1540 if ($content) {
1541 $contentpart = html_writer::tag('div', $content, array('class' =>
1542 trim('contentafterlink ' . $textclasses)));
1544 } else {
1545 // No link, so display only content.
1546 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textcss));
1549 } else {
1550 $textclasses = $extraclasses;
1551 $textclasses .= ' dimmed_text';
1552 if ($textclasses) {
1553 $textcss = 'class="' . trim($textclasses) . '" ';
1554 } else {
1555 $textcss = '';
1557 $accesstext = '<span class="accesshide">' .
1558 get_string('notavailableyet', 'condition') .
1559 ': </span>';
1561 if ($url = $mod->get_url()) {
1562 // Display greyed-out text of link
1563 echo '<div ' . $textcss . $mod->extra .
1564 ' >' . '<img src="' . $mod->get_icon_url() .
1565 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1566 '</span></div>';
1568 // Do not display content after link when it is greyed out like this.
1569 } else {
1570 // No link, so display only content (also greyed)
1571 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1572 $accesstext . $content . '</div>';
1576 // Module can put text after the link (e.g. forum unread)
1577 echo $mod->get_after_link();
1579 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1580 echo html_writer::end_tag('div');
1582 // If there is content but NO link (eg label), then display the
1583 // content here (BEFORE any icons). In this case cons must be
1584 // displayed after the content so that it makes more sense visually
1585 // and for accessibility reasons, e.g. if you have a one-line label
1586 // it should work similarly (at least in terms of ordering) to an
1587 // activity.
1588 if (empty($url)) {
1589 echo $contentpart;
1592 if ($isediting) {
1593 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1594 if (! $mod->groupmodelink = $groupbuttonslink) {
1595 $mod->groupmode = $course->groupmode;
1598 } else {
1599 $mod->groupmode = false;
1601 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1602 echo $mod->get_after_edit_icons();
1605 // Completion
1606 $completion = $hidecompletion
1607 ? COMPLETION_TRACKING_NONE
1608 : $completioninfo->is_enabled($mod);
1609 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1610 !isguestuser() && $mod->uservisible) {
1611 $completiondata = $completioninfo->get_data($mod,true);
1612 $completionicon = '';
1613 if ($isediting) {
1614 switch ($completion) {
1615 case COMPLETION_TRACKING_MANUAL :
1616 $completionicon = 'manual-enabled'; break;
1617 case COMPLETION_TRACKING_AUTOMATIC :
1618 $completionicon = 'auto-enabled'; break;
1619 default: // wtf
1621 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1622 switch($completiondata->completionstate) {
1623 case COMPLETION_INCOMPLETE:
1624 $completionicon = 'manual-n'; break;
1625 case COMPLETION_COMPLETE:
1626 $completionicon = 'manual-y'; break;
1628 } else { // Automatic
1629 switch($completiondata->completionstate) {
1630 case COMPLETION_INCOMPLETE:
1631 $completionicon = 'auto-n'; break;
1632 case COMPLETION_COMPLETE:
1633 $completionicon = 'auto-y'; break;
1634 case COMPLETION_COMPLETE_PASS:
1635 $completionicon = 'auto-pass'; break;
1636 case COMPLETION_COMPLETE_FAIL:
1637 $completionicon = 'auto-fail'; break;
1640 if ($completionicon) {
1641 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1642 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1643 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1644 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1645 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1646 $newstate =
1647 $completiondata->completionstate==COMPLETION_COMPLETE
1648 ? COMPLETION_INCOMPLETE
1649 : COMPLETION_COMPLETE;
1650 // In manual mode the icon is a toggle form...
1652 // If this completion state is used by the
1653 // conditional activities system, we need to turn
1654 // off the JS.
1655 if (!empty($CFG->enableavailability) &&
1656 condition_info::completion_value_used_as_condition($course, $mod)) {
1657 $extraclass = ' preventjs';
1658 } else {
1659 $extraclass = '';
1661 echo html_writer::start_tag('form', array(
1662 'class' => 'togglecompletion' . $extraclass,
1663 'method' => 'post',
1664 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1665 echo html_writer::start_tag('div');
1666 echo html_writer::empty_tag('input', array(
1667 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1668 echo html_writer::empty_tag('input', array(
1669 'type' => 'hidden', 'name' => 'modulename',
1670 'value' => $mod->name));
1671 echo html_writer::empty_tag('input', array(
1672 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1673 echo html_writer::empty_tag('input', array(
1674 'type' => 'hidden', 'name' => 'completionstate',
1675 'value' => $newstate));
1676 echo html_writer::empty_tag('input', array(
1677 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle,
1678 'aria-live' => 'polite'));
1679 echo html_writer::end_tag('div');
1680 echo html_writer::end_tag('form');
1681 } else {
1682 // In auto mode, or when editing, the icon is just an image.
1683 echo html_writer::tag('span', html_writer::empty_tag('img', array(
1684 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgalt)),
1685 array('class' => 'autocompletion'));
1690 // If there is content AND a link, then display the content here
1691 // (AFTER any icons). Otherwise it was displayed before
1692 if (!empty($url)) {
1693 echo $contentpart;
1696 // Show availability information (for someone who isn't allowed to
1697 // see the activity itself, or for staff)
1698 if (!$mod->uservisible) {
1699 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1700 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1701 // Don't add availability information if user is not editing and activity is hidden.
1702 if ($mod->visible || $PAGE->user_is_editing()) {
1703 $hidinfoclass = '';
1704 if (!$mod->visible) {
1705 $hidinfoclass = 'hide';
1707 $ci = new condition_info($mod);
1708 $fullinfo = $ci->get_full_information();
1709 if($fullinfo) {
1710 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1711 ? 'userrestriction_visible'
1712 : 'userrestriction_hidden','condition',
1713 $fullinfo).'</div>';
1718 echo html_writer::end_tag('div');
1719 echo html_writer::end_tag('li')."\n";
1722 } elseif ($ismoving) {
1723 echo "<ul class=\"section\">\n";
1726 if ($ismoving) {
1727 echo '<li><a title="'.$strmovefull.'"'.
1728 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1729 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1730 ' alt="'.$strmovehere.'" /></a></li>
1733 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1734 echo "</ul><!--class='section'-->\n\n";
1739 * Prints the menus to add activities and resources.
1741 * @param stdClass $course The course
1742 * @param int $section relative section number (field course_sections.section)
1743 * @param null|array $modnames An array containing the list of modules and their names
1744 * if omitted will be taken from get_module_types_names()
1745 * @param bool $vertical Vertical orientation
1746 * @param bool $return Return the menus or send them to output
1747 * @param int $sectionreturn The section to link back to
1748 * @return void|string depending on $return
1750 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1751 global $CFG, $OUTPUT;
1753 if ($modnames === null) {
1754 $modnames = get_module_types_names();
1757 // check to see if user can add menus and there are modules to add
1758 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1759 || empty($modnames)) {
1760 if ($return) {
1761 return '';
1762 } else {
1763 return false;
1767 // Retrieve all modules with associated metadata
1768 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1770 // We'll sort resources and activities into two lists
1771 $resources = array();
1772 $activities = array();
1774 // We need to add the section section to the link for each module
1775 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1777 foreach ($modules as $module) {
1778 if (isset($module->types)) {
1779 // This module has a subtype
1780 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1781 $subtypes = array();
1782 foreach ($module->types as $subtype) {
1783 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1786 // Sort module subtypes into the list
1787 if (!empty($module->title)) {
1788 // This grouping has a name
1789 if ($module->archetype == MOD_CLASS_RESOURCE) {
1790 $resources[] = array($module->title=>$subtypes);
1791 } else {
1792 $activities[] = array($module->title=>$subtypes);
1794 } else {
1795 // This grouping does not have a name
1796 if ($module->archetype == MOD_CLASS_RESOURCE) {
1797 $resources = array_merge($resources, $subtypes);
1798 } else {
1799 $activities = array_merge($activities, $subtypes);
1802 } else {
1803 // This module has no subtypes
1804 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1805 $resources[$module->link . $sectionlink] = $module->title;
1806 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1807 // System modules cannot be added by user, do not add to dropdown
1808 } else {
1809 $activities[$module->link . $sectionlink] = $module->title;
1814 $straddactivity = get_string('addactivity');
1815 $straddresource = get_string('addresource');
1816 $sectionname = get_section_name($course, $section);
1817 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1818 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1820 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1822 if (!$vertical) {
1823 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1826 if (!empty($resources)) {
1827 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1828 $select->set_help_icon('resources');
1829 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1830 $output .= $OUTPUT->render($select);
1833 if (!empty($activities)) {
1834 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1835 $select->set_help_icon('activities');
1836 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1837 $output .= $OUTPUT->render($select);
1840 if (!$vertical) {
1841 $output .= html_writer::end_tag('div');
1844 $output .= html_writer::end_tag('div');
1846 if (course_ajax_enabled($course)) {
1847 $straddeither = get_string('addresourceoractivity');
1848 // The module chooser link
1849 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1850 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1851 $icon = $OUTPUT->pix_icon('t/add', '');
1852 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1853 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1854 $modchooser.= html_writer::end_tag('div');
1855 $modchooser.= html_writer::end_tag('div');
1857 // Wrap the normal output in a noscript div
1858 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1859 if ($usemodchooser) {
1860 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1861 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1862 } else {
1863 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1864 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1865 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1867 $output = $modchooser . $output;
1870 if ($return) {
1871 return $output;
1872 } else {
1873 echo $output;
1878 * Retrieve all metadata for the requested modules
1880 * @param object $course The Course
1881 * @param array $modnames An array containing the list of modules and their
1882 * names
1883 * @param int $sectionreturn The section to return to
1884 * @return array A list of stdClass objects containing metadata about each
1885 * module
1887 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1888 global $CFG, $OUTPUT;
1890 // get_module_metadata will be called once per section on the page and courses may show
1891 // different modules to one another
1892 static $modlist = array();
1893 if (!isset($modlist[$course->id])) {
1894 $modlist[$course->id] = array();
1897 $return = array();
1898 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1899 foreach($modnames as $modname => $modnamestr) {
1900 if (!course_allowed_module($course, $modname)) {
1901 continue;
1903 if (isset($modlist[$course->id][$modname])) {
1904 // This module is already cached
1905 $return[$modname] = $modlist[$course->id][$modname];
1906 continue;
1909 // Include the module lib
1910 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1911 if (!file_exists($libfile)) {
1912 continue;
1914 include_once($libfile);
1916 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1917 $gettypesfunc = $modname.'_get_types';
1918 if (function_exists($gettypesfunc)) {
1919 $types = $gettypesfunc();
1920 if (is_array($types) && count($types) > 0) {
1921 $group = new stdClass();
1922 $group->name = $modname;
1923 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1924 foreach($types as $type) {
1925 if ($type->typestr === '--') {
1926 continue;
1928 if (strpos($type->typestr, '--') === 0) {
1929 $group->title = str_replace('--', '', $type->typestr);
1930 continue;
1932 // Set the Sub Type metadata
1933 $subtype = new stdClass();
1934 $subtype->title = $type->typestr;
1935 $subtype->type = str_replace('&amp;', '&', $type->type);
1936 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1937 $subtype->archetype = $type->modclass;
1939 // The group archetype should match the subtype archetypes and all subtypes
1940 // should have the same archetype
1941 $group->archetype = $subtype->archetype;
1943 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1944 $subtype->help = get_string('help' . $subtype->name, $modname);
1946 $subtype->link = $urlbase . $subtype->type;
1947 $group->types[] = $subtype;
1949 $modlist[$course->id][$modname] = $group;
1951 } else {
1952 $module = new stdClass();
1953 $module->title = get_string('modulename', $modname);
1954 $module->name = $modname;
1955 $module->link = $urlbase . $modname;
1956 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1957 $sm = get_string_manager();
1958 if ($sm->string_exists('modulename_help', $modname)) {
1959 $module->help = get_string('modulename_help', $modname);
1960 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1961 $link = get_string('modulename_link', $modname);
1962 $linktext = get_string('morehelp');
1963 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1966 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1967 $modlist[$course->id][$modname] = $module;
1969 if (isset($modlist[$course->id][$modname])) {
1970 $return[$modname] = $modlist[$course->id][$modname];
1971 } else {
1972 debugging("Invalid module metadata configuration for {$modname}");
1976 return $return;
1980 * Return the course category context for the category with id $categoryid, except
1981 * that if $categoryid is 0, return the system context.
1983 * @param integer $categoryid a category id or 0.
1984 * @return object the corresponding context
1986 function get_category_or_system_context($categoryid) {
1987 if ($categoryid) {
1988 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1989 } else {
1990 return context_system::instance();
1995 * Gets the child categories of a given courses category. Uses a static cache
1996 * to make repeat calls efficient.
1998 * @param int $parentid the id of a course category.
1999 * @return array all the child course categories.
2001 function get_child_categories($parentid) {
2002 static $allcategories = null;
2004 // only fill in this variable the first time
2005 if (null == $allcategories) {
2006 $allcategories = array();
2008 $categories = get_categories();
2009 foreach ($categories as $category) {
2010 if (empty($allcategories[$category->parent])) {
2011 $allcategories[$category->parent] = array();
2013 $allcategories[$category->parent][] = $category;
2017 if (empty($allcategories[$parentid])) {
2018 return array();
2019 } else {
2020 return $allcategories[$parentid];
2025 * This function recursively travels the categories, building up a nice list
2026 * for display. It also makes an array that list all the parents for each
2027 * category.
2029 * For example, if you have a tree of categories like:
2030 * Miscellaneous (id = 1)
2031 * Subcategory (id = 2)
2032 * Sub-subcategory (id = 4)
2033 * Other category (id = 3)
2034 * Then after calling this function you will have
2035 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2036 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2037 * 3 => 'Other category');
2038 * $parents = array(2 => array(1), 4 => array(1, 2));
2040 * If you specify $requiredcapability, then only categories where the current
2041 * user has that capability will be added to $list, although all categories
2042 * will still be added to $parents, and if you only have $requiredcapability
2043 * in a child category, not the parent, then the child catgegory will still be
2044 * included.
2046 * If you specify the option $excluded, then that category, and all its children,
2047 * are omitted from the tree. This is useful when you are doing something like
2048 * moving categories, where you do not want to allow people to move a category
2049 * to be the child of itself.
2051 * @param array $list For output, accumulates an array categoryid => full category path name
2052 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2053 * @param string/array $requiredcapability if given, only categories where the current
2054 * user has this capability will be added to $list. Can also be an array of capabilities,
2055 * in which case they are all required.
2056 * @param integer $excludeid Omit this category and its children from the lists built.
2057 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2058 * @param string $path For internal use, as part of recursive calls.
2060 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2061 $excludeid = 0, $category = NULL, $path = "") {
2063 // initialize the arrays if needed
2064 if (!is_array($list)) {
2065 $list = array();
2067 if (!is_array($parents)) {
2068 $parents = array();
2071 if (empty($category)) {
2072 // Start at the top level.
2073 $category = new stdClass;
2074 $category->id = 0;
2075 } else {
2076 // This is the excluded category, don't include it.
2077 if ($excludeid > 0 && $excludeid == $category->id) {
2078 return;
2081 $context = context_coursecat::instance($category->id);
2082 $categoryname = format_string($category->name, true, array('context' => $context));
2084 // Update $path.
2085 if ($path) {
2086 $path = $path.' / '.$categoryname;
2087 } else {
2088 $path = $categoryname;
2091 // Add this category to $list, if the permissions check out.
2092 if (empty($requiredcapability)) {
2093 $list[$category->id] = $path;
2095 } else {
2096 $requiredcapability = (array)$requiredcapability;
2097 if (has_all_capabilities($requiredcapability, $context)) {
2098 $list[$category->id] = $path;
2103 // Add all the children recursively, while updating the parents array.
2104 if ($categories = get_child_categories($category->id)) {
2105 foreach ($categories as $cat) {
2106 if (!empty($category->id)) {
2107 if (isset($parents[$category->id])) {
2108 $parents[$cat->id] = $parents[$category->id];
2110 $parents[$cat->id][] = $category->id;
2112 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2118 * This function generates a structured array of courses and categories.
2120 * The depth of categories is limited by $CFG->maxcategorydepth however there
2121 * is no limit on the number of courses!
2123 * Suitable for use with the course renderers course_category_tree method:
2124 * $renderer = $PAGE->get_renderer('core','course');
2125 * echo $renderer->course_category_tree(get_course_category_tree());
2127 * @global moodle_database $DB
2128 * @param int $id
2129 * @param int $depth
2131 function get_course_category_tree($id = 0, $depth = 0) {
2132 global $DB, $CFG;
2133 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2134 $categories = get_child_categories($id);
2135 $categoryids = array();
2136 foreach ($categories as $key => &$category) {
2137 if (!$category->visible && !$viewhiddencats) {
2138 unset($categories[$key]);
2139 continue;
2141 $categoryids[$category->id] = $category;
2142 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2143 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2144 foreach ($subcategories as $subid=>$subcat) {
2145 $categoryids[$subid] = $subcat;
2147 $category->courses = array();
2151 if ($depth > 0) {
2152 // This is a recursive call so return the required array
2153 return array($categories, $categoryids);
2156 if (empty($categoryids)) {
2157 // No categories available (probably all hidden).
2158 return array();
2161 // The depth is 0 this function has just been called so we can finish it off
2163 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2164 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2165 $sql = "SELECT
2166 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2167 $ccselect
2168 FROM {course} c
2169 $ccjoin
2170 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2171 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2172 // loop throught them
2173 foreach ($courses as $course) {
2174 if ($course->id == SITEID) {
2175 continue;
2177 context_instance_preload($course);
2178 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2179 $categoryids[$course->category]->courses[$course->id] = $course;
2183 return $categories;
2187 * Recursive function to print out all the categories in a nice format
2188 * with or without courses included
2190 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2191 global $CFG;
2193 // maxcategorydepth == 0 meant no limit
2194 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2195 return;
2198 if (!$displaylist) {
2199 make_categories_list($displaylist, $parentslist);
2202 if ($category) {
2203 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2204 print_category_info($category, $depth, $showcourses);
2205 } else {
2206 return; // Don't bother printing children of invisible categories
2209 } else {
2210 $category = new stdClass();
2211 $category->id = "0";
2214 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2215 $countcats = count($categories);
2216 $count = 0;
2217 $first = true;
2218 $last = false;
2219 foreach ($categories as $cat) {
2220 $count++;
2221 if ($count == $countcats) {
2222 $last = true;
2224 $up = $first ? false : true;
2225 $down = $last ? false : true;
2226 $first = false;
2228 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2234 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2236 function make_categories_options() {
2237 make_categories_list($cats,$parents);
2238 foreach ($cats as $key => $value) {
2239 if (array_key_exists($key,$parents)) {
2240 if ($indent = count($parents[$key])) {
2241 for ($i = 0; $i < $indent; $i++) {
2242 $cats[$key] = '&nbsp;'.$cats[$key];
2247 return $cats;
2251 * Prints the category info in indented fashion
2252 * This function is only used by print_whole_category_list() above
2254 function print_category_info($category, $depth=0, $showcourses = false) {
2255 global $CFG, $DB, $OUTPUT;
2257 $strsummary = get_string('summary');
2259 $catlinkcss = null;
2260 if (!$category->visible) {
2261 $catlinkcss = array('class'=>'dimmed');
2263 static $coursecount = null;
2264 if (null === $coursecount) {
2265 // only need to check this once
2266 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2269 if ($showcourses and $coursecount) {
2270 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2271 } else {
2272 $catimage = "&nbsp;";
2275 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2276 $context = context_coursecat::instance($category->id);
2277 $fullname = format_string($category->name, true, array('context' => $context));
2279 if ($showcourses and $coursecount) {
2280 echo '<div class="categorylist clearfix">';
2281 $cat = '';
2282 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2283 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2284 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2286 $html = '';
2287 if ($depth > 0) {
2288 for ($i=0; $i< $depth; $i++) {
2289 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2290 $cat = '';
2292 } else {
2293 $html = $cat;
2295 echo html_writer::tag('div', $html, array('class'=>'category'));
2296 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2298 // does the depth exceed maxcategorydepth
2299 // maxcategorydepth == 0 or unset meant no limit
2300 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2301 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2302 foreach ($courses as $course) {
2303 $linkcss = null;
2304 if (!$course->visible) {
2305 $linkcss = array('class'=>'dimmed');
2308 $coursename = get_course_display_name_for_list($course);
2309 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2311 // print enrol info
2312 $courseicon = '';
2313 if ($icons = enrol_get_course_info_icons($course)) {
2314 foreach ($icons as $pix_icon) {
2315 $courseicon = $OUTPUT->render($pix_icon);
2319 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2321 if ($course->summary) {
2322 $link = new moodle_url('/course/info.php?id='.$course->id);
2323 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2324 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2325 array('title'=>$strsummary));
2327 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2330 $html = '';
2331 for ($i=0; $i <= $depth; $i++) {
2332 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2333 $coursecontent = '';
2335 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2338 echo '</div>';
2339 } else {
2340 echo '<div class="categorylist">';
2341 $html = '';
2342 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2343 if (count($courses) > 0) {
2344 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2347 if ($depth > 0) {
2348 for ($i=0; $i< $depth; $i++) {
2349 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2350 $cat = '';
2352 } else {
2353 $html = $cat;
2356 echo html_writer::tag('div', $html, array('class'=>'category'));
2357 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2358 echo '</div>';
2363 * Print the buttons relating to course requests.
2365 * @param object $systemcontext the system context.
2367 function print_course_request_buttons($systemcontext) {
2368 global $CFG, $DB, $OUTPUT;
2369 if (empty($CFG->enablecourserequests)) {
2370 return;
2372 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2373 /// Print a button to request a new course
2374 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2376 /// Print a button to manage pending requests
2377 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2378 $disabled = !$DB->record_exists('course_request', array());
2379 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2384 * Does the user have permission to edit things in this category?
2386 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2387 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2389 function can_edit_in_category($categoryid = 0) {
2390 $context = get_category_or_system_context($categoryid);
2391 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2395 * Prints the turn editing on/off button on course/index.php or course/category.php.
2397 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2398 * @return string HTML of the editing button, or empty string, if this user is not allowed
2399 * to see it.
2401 function update_category_button($categoryid = 0) {
2402 global $CFG, $PAGE, $OUTPUT;
2404 // Check permissions.
2405 if (!can_edit_in_category($categoryid)) {
2406 return '';
2409 // Work out the appropriate action.
2410 if ($PAGE->user_is_editing()) {
2411 $label = get_string('turneditingoff');
2412 $edit = 'off';
2413 } else {
2414 $label = get_string('turneditingon');
2415 $edit = 'on';
2418 // Generate the button HTML.
2419 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2420 if ($categoryid) {
2421 $options['id'] = $categoryid;
2422 $page = 'category.php';
2423 } else {
2424 $page = 'index.php';
2426 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2430 * Print courses in category. If category is 0 then all courses are printed.
2431 * @param int|stdClass $category category object or id.
2432 * @return bool true if courses found and printed, else false.
2434 function print_courses($category) {
2435 global $CFG, $OUTPUT;
2437 if (!is_object($category) && $category==0) {
2438 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2439 if (is_array($categories) && count($categories) == 1) {
2440 $category = array_shift($categories);
2441 $courses = get_courses_wmanagers($category->id,
2442 'c.sortorder ASC',
2443 array('summary','summaryformat'));
2444 } else {
2445 $courses = get_courses_wmanagers('all',
2446 'c.sortorder ASC',
2447 array('summary','summaryformat'));
2449 unset($categories);
2450 } else {
2451 $courses = get_courses_wmanagers($category->id,
2452 'c.sortorder ASC',
2453 array('summary','summaryformat'));
2456 if ($courses) {
2457 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2458 foreach ($courses as $course) {
2459 $coursecontext = context_course::instance($course->id);
2460 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2461 echo html_writer::start_tag('li');
2462 print_course($course);
2463 echo html_writer::end_tag('li');
2466 echo html_writer::end_tag('ul');
2467 } else {
2468 echo $OUTPUT->heading(get_string("nocoursesyet"));
2469 $context = context_system::instance();
2470 if (has_capability('moodle/course:create', $context)) {
2471 $options = array();
2472 if (!empty($category->id)) {
2473 $options['category'] = $category->id;
2474 } else {
2475 $options['category'] = $CFG->defaultrequestcategory;
2477 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2478 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2479 echo html_writer::end_tag('div');
2480 return false;
2483 return true;
2487 * Print a description of a course, suitable for browsing in a list.
2489 * @param object $course the course object.
2490 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2492 function print_course($course, $highlightterms = '') {
2493 global $CFG, $USER, $DB, $OUTPUT;
2495 $context = context_course::instance($course->id);
2497 // Rewrite file URLs so that they are correct
2498 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2500 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2501 echo html_writer::start_tag('div', array('class'=>'info'));
2502 echo html_writer::start_tag('h3', array('class'=>'name'));
2504 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2506 $coursename = get_course_display_name_for_list($course);
2507 $linktext = highlight($highlightterms, format_string($coursename));
2508 $linkparams = array('title'=>get_string('entercourse'));
2509 if (empty($course->visible)) {
2510 $linkparams['class'] = 'dimmed';
2512 echo html_writer::link($linkhref, $linktext, $linkparams);
2513 echo html_writer::end_tag('h3');
2515 /// first find all roles that are supposed to be displayed
2516 if (!empty($CFG->coursecontact)) {
2517 $managerroles = explode(',', $CFG->coursecontact);
2518 $rusers = array();
2520 if (!isset($course->managers)) {
2521 list($sort, $sortparams) = users_order_by_sql('u');
2522 $rusers = get_role_users($managerroles, $context, true,
2523 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2524 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2525 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2526 } else {
2527 // use the managers array if we have it for perf reasosn
2528 // populate the datastructure like output of get_role_users();
2529 foreach ($course->managers as $manager) {
2530 $user = clone($manager->user);
2531 $user->roleid = $manager->roleid;
2532 $user->rolename = $manager->rolename;
2533 $user->roleshortname = $manager->roleshortname;
2534 $user->rolecoursealias = $manager->rolecoursealias;
2535 $rusers[$user->id] = $user;
2539 $namesarray = array();
2540 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2541 foreach ($rusers as $ra) {
2542 if (isset($namesarray[$ra->id])) {
2543 // only display a user once with the higest sortorder role
2544 continue;
2547 $role = new stdClass();
2548 $role->id = $ra->roleid;
2549 $role->name = $ra->rolename;
2550 $role->shortname = $ra->roleshortname;
2551 $role->coursealias = $ra->rolecoursealias;
2552 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2554 $fullname = fullname($ra, $canviewfullnames);
2555 $namesarray[$ra->id] = $rolename.': '.
2556 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2559 if (!empty($namesarray)) {
2560 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2561 foreach ($namesarray as $name) {
2562 echo html_writer::tag('li', $name);
2564 echo html_writer::end_tag('ul');
2567 echo html_writer::end_tag('div'); // End of info div
2569 echo html_writer::start_tag('div', array('class'=>'summary'));
2570 $options = new stdClass();
2571 $options->noclean = true;
2572 $options->para = false;
2573 $options->overflowdiv = true;
2574 if (!isset($course->summaryformat)) {
2575 $course->summaryformat = FORMAT_MOODLE;
2577 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2578 if ($icons = enrol_get_course_info_icons($course)) {
2579 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2580 foreach ($icons as $icon) {
2581 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
2582 echo $OUTPUT->render($icon);
2584 echo html_writer::end_tag('div'); // End of enrolmenticons div
2586 echo html_writer::end_tag('div'); // End of summary div
2587 echo html_writer::end_tag('div'); // End of coursebox div
2591 * Prints custom user information on the home page.
2592 * Over time this can include all sorts of information
2594 function print_my_moodle() {
2595 global $USER, $CFG, $DB, $OUTPUT;
2597 if (!isloggedin() or isguestuser()) {
2598 print_error('nopermissions', '', '', 'See My Moodle');
2601 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2602 $rhosts = array();
2603 $rcourses = array();
2604 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2605 $rcourses = get_my_remotecourses($USER->id);
2606 $rhosts = get_my_remotehosts();
2609 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2611 if (!empty($courses)) {
2612 echo '<ul class="unlist">';
2613 foreach ($courses as $course) {
2614 if ($course->id == SITEID) {
2615 continue;
2617 echo '<li>';
2618 print_course($course);
2619 echo "</li>\n";
2621 echo "</ul>\n";
2624 // MNET
2625 if (!empty($rcourses)) {
2626 // at the IDP, we know of all the remote courses
2627 foreach ($rcourses as $course) {
2628 print_remote_course($course, "100%");
2630 } elseif (!empty($rhosts)) {
2631 // non-IDP, we know of all the remote servers, but not courses
2632 foreach ($rhosts as $host) {
2633 print_remote_host($host, "100%");
2636 unset($course);
2637 unset($host);
2639 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2640 echo "<table width=\"100%\"><tr><td align=\"center\">";
2641 print_course_search("", false, "short");
2642 echo "</td><td align=\"center\">";
2643 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2644 echo "</td></tr></table>\n";
2647 } else {
2648 if ($DB->count_records("course_categories") > 1) {
2649 echo $OUTPUT->box_start("categorybox");
2650 print_whole_category_list();
2651 echo $OUTPUT->box_end();
2652 } else {
2653 print_courses(0);
2659 function print_course_search($value="", $return=false, $format="plain") {
2660 global $CFG;
2661 static $count = 0;
2663 $count++;
2665 $id = 'coursesearch';
2667 if ($count > 1) {
2668 $id .= $count;
2671 $strsearchcourses= get_string("searchcourses");
2673 if ($format == 'plain') {
2674 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2675 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2676 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2677 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2678 $output .= '<input type="submit" value="'.get_string('go').'" />';
2679 $output .= '</fieldset></form>';
2680 } else if ($format == 'short') {
2681 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2682 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2683 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2684 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" value="'.s($value).'" />';
2685 $output .= '<input type="submit" value="'.get_string('go').'" />';
2686 $output .= '</fieldset></form>';
2687 } else if ($format == 'navbar') {
2688 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2689 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2690 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2691 $output .= '<input type="text" id="navsearchbox" size="20" name="search" value="'.s($value).'" />';
2692 $output .= '<input type="submit" value="'.get_string('go').'" />';
2693 $output .= '</fieldset></form>';
2696 if ($return) {
2697 return $output;
2699 echo $output;
2702 function print_remote_course($course, $width="100%") {
2703 global $CFG, $USER;
2705 $linkcss = '';
2707 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2709 echo '<div class="coursebox remotecoursebox clearfix">';
2710 echo '<div class="info">';
2711 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2712 $linkcss.' href="'.$url.'">'
2713 . format_string($course->fullname) .'</a><br />'
2714 . format_string($course->hostname) . ' : '
2715 . format_string($course->cat_name) . ' : '
2716 . format_string($course->shortname). '</div>';
2717 echo '</div><div class="summary">';
2718 $options = new stdClass();
2719 $options->noclean = true;
2720 $options->para = false;
2721 $options->overflowdiv = true;
2722 echo format_text($course->summary, $course->summaryformat, $options);
2723 echo '</div>';
2724 echo '</div>';
2727 function print_remote_host($host, $width="100%") {
2728 global $OUTPUT;
2730 $linkcss = '';
2732 echo '<div class="coursebox clearfix">';
2733 echo '<div class="info">';
2734 echo '<div class="name">';
2735 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2736 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2737 . s($host['name']).'</a> - ';
2738 echo $host['count'] . ' ' . get_string('courses');
2739 echo '</div>';
2740 echo '</div>';
2741 echo '</div>';
2745 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2747 function add_course_module($mod) {
2748 global $DB;
2750 $mod->added = time();
2751 unset($mod->id);
2753 $cmid = $DB->insert_record("course_modules", $mod);
2754 rebuild_course_cache($mod->course, true);
2755 return $cmid;
2759 * Creates missing course section(s) and rebuilds course cache
2761 * @param int|stdClass $courseorid course id or course object
2762 * @param int|array $sections list of relative section numbers to create
2763 * @return bool if there were any sections created
2765 function course_create_sections_if_missing($courseorid, $sections) {
2766 global $DB;
2767 if (!is_array($sections)) {
2768 $sections = array($sections);
2770 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2771 if (is_object($courseorid)) {
2772 $courseorid = $courseorid->id;
2774 $coursechanged = false;
2775 foreach ($sections as $sectionnum) {
2776 if (!in_array($sectionnum, $existing)) {
2777 $cw = new stdClass();
2778 $cw->course = $courseorid;
2779 $cw->section = $sectionnum;
2780 $cw->summary = '';
2781 $cw->summaryformat = FORMAT_HTML;
2782 $cw->sequence = '';
2783 $id = $DB->insert_record("course_sections", $cw);
2784 $coursechanged = true;
2787 if ($coursechanged) {
2788 rebuild_course_cache($courseorid, true);
2790 return $coursechanged;
2794 * Adds an existing module to the section
2796 * Updates both tables {course_sections} and {course_modules}
2798 * @param int|stdClass $courseorid course id or course object
2799 * @param int $cmid id of the module already existing in course_modules table
2800 * @param int $sectionnum relative number of the section (field course_sections.section)
2801 * If section does not exist it will be created
2802 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2803 * before which the module needs to be included. Null for inserting in the
2804 * end of the section
2805 * @return int The course_sections ID where the module is inserted
2807 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2808 global $DB, $COURSE;
2809 if (is_object($beforemod)) {
2810 $beforemod = $beforemod->id;
2812 if (is_object($courseorid)) {
2813 $courseid = $courseorid->id;
2814 } else {
2815 $courseid = $courseorid;
2817 course_create_sections_if_missing($courseorid, $sectionnum);
2818 // Do not try to use modinfo here, there is no guarantee it is valid!
2819 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
2820 $modarray = explode(",", trim($section->sequence));
2821 if (empty($section->sequence)) {
2822 $newsequence = "$cmid";
2823 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2824 $insertarray = array($cmid, $beforemod);
2825 array_splice($modarray, $key[0], 1, $insertarray);
2826 $newsequence = implode(",", $modarray);
2827 } else {
2828 $newsequence = "$section->sequence,$cmid";
2830 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2831 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
2832 if (is_object($courseorid)) {
2833 rebuild_course_cache($courseorid->id, true);
2834 } else {
2835 rebuild_course_cache($courseorid, true);
2837 return $section->id; // Return course_sections ID that was used.
2840 function set_coursemodule_groupmode($id, $groupmode) {
2841 global $DB;
2842 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2843 if ($cm->groupmode != $groupmode) {
2844 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2845 rebuild_course_cache($cm->course, true);
2847 return ($cm->groupmode != $groupmode);
2850 function set_coursemodule_idnumber($id, $idnumber) {
2851 global $DB;
2852 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2853 if ($cm->idnumber != $idnumber) {
2854 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2855 rebuild_course_cache($cm->course, true);
2857 return ($cm->idnumber != $idnumber);
2861 * Set the visibility of a module and inherent properties.
2863 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2864 * has been moved to {@link set_section_visible()} which was the only place from which
2865 * the parameter was used.
2867 * @param int $id of the module
2868 * @param int $visible state of the module
2869 * @return bool false when the module was not found, true otherwise
2871 function set_coursemodule_visible($id, $visible) {
2872 global $DB, $CFG;
2873 require_once($CFG->libdir.'/gradelib.php');
2875 // Trigger developer's attention when using the previously removed argument.
2876 if (func_num_args() > 2) {
2877 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2878 has been removed.', DEBUG_DEVELOPER);
2881 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2882 return false;
2885 // Create events and propagate visibility to associated grade items if the value has changed.
2886 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2887 if ($cm->visible == $visible) {
2888 return true;
2891 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2892 return false;
2894 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2895 foreach($events as $event) {
2896 if ($visible) {
2897 show_event($event);
2898 } else {
2899 hide_event($event);
2904 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2905 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2906 if ($grade_items) {
2907 foreach ($grade_items as $grade_item) {
2908 $grade_item->set_hidden(!$visible);
2912 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2913 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2914 $cminfo = new stdClass();
2915 $cminfo->id = $id;
2916 $cminfo->visible = $visible;
2917 $cminfo->visibleold = $visible;
2918 $DB->update_record('course_modules', $cminfo);
2920 rebuild_course_cache($cm->course, true);
2921 return true;
2925 * Delete a course module and any associated data at the course level (events)
2926 * Until 1.5 this function simply marked a deleted flag ... now it
2927 * deletes it completely.
2930 function delete_course_module($id) {
2931 global $CFG, $DB;
2932 require_once($CFG->libdir.'/gradelib.php');
2933 require_once($CFG->dirroot.'/blog/lib.php');
2935 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2936 return true;
2938 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2939 //delete events from calendar
2940 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2941 foreach($events as $event) {
2942 delete_event($event->id);
2945 //delete grade items, outcome items and grades attached to modules
2946 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2947 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2948 foreach ($grade_items as $grade_item) {
2949 $grade_item->delete('moddelete');
2952 // Delete completion and availability data; it is better to do this even if the
2953 // features are not turned on, in case they were turned on previously (these will be
2954 // very quick on an empty table)
2955 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2956 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2957 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2958 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2959 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2961 delete_context(CONTEXT_MODULE, $cm->id);
2962 $DB->delete_records('course_modules', array('id'=>$cm->id));
2963 rebuild_course_cache($cm->course, true);
2964 return true;
2967 function delete_mod_from_section($modid, $sectionid) {
2968 global $DB;
2970 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2972 $modarray = explode(",", $section->sequence);
2974 if ($key = array_keys ($modarray, $modid)) {
2975 array_splice($modarray, $key[0], 1);
2976 $newsequence = implode(",", $modarray);
2977 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2978 rebuild_course_cache($section->course, true);
2979 return true;
2980 } else {
2981 return false;
2985 return false;
2989 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2991 * @param object $course course object
2992 * @param int $section Section number (not id!!!)
2993 * @param int $move (-1 or 1)
2994 * @return boolean true if section moved successfully
2995 * @todo MDL-33379 remove this function in 2.5
2997 function move_section($course, $section, $move) {
2998 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
3000 /// Moves a whole course section up and down within the course
3001 global $USER;
3003 if (!$move) {
3004 return true;
3007 $sectiondest = $section + $move;
3009 // compartibility with course formats using field 'numsections'
3010 $courseformatoptions = course_get_format($course)->get_format_options();
3011 if (array_key_exists('numsections', $courseformatoptions) &&
3012 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
3013 return false;
3016 $retval = move_section_to($course, $section, $sectiondest);
3017 return $retval;
3021 * Moves a section within a course, from a position to another.
3022 * Be very careful: $section and $destination refer to section number,
3023 * not id!.
3025 * @param object $course
3026 * @param int $section Section number (not id!!!)
3027 * @param int $destination
3028 * @return boolean Result
3030 function move_section_to($course, $section, $destination) {
3031 /// Moves a whole course section up and down within the course
3032 global $USER, $DB;
3034 if (!$destination && $destination != 0) {
3035 return true;
3038 // compartibility with course formats using field 'numsections'
3039 $courseformatoptions = course_get_format($course)->get_format_options();
3040 if ((array_key_exists('numsections', $courseformatoptions) &&
3041 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3042 return false;
3045 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3046 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3047 'section ASC, id ASC', 'id, section')) {
3048 return false;
3051 $movedsections = reorder_sections($sections, $section, $destination);
3053 // Update all sections. Do this in 2 steps to avoid breaking database
3054 // uniqueness constraint
3055 $transaction = $DB->start_delegated_transaction();
3056 foreach ($movedsections as $id => $position) {
3057 if ($sections[$id] !== $position) {
3058 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3061 foreach ($movedsections as $id => $position) {
3062 if ($sections[$id] !== $position) {
3063 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3067 // If we move the highlighted section itself, then just highlight the destination.
3068 // Adjust the higlighted section location if we move something over it either direction.
3069 if ($section == $course->marker) {
3070 course_set_marker($course->id, $destination);
3071 } elseif ($section > $course->marker && $course->marker >= $destination) {
3072 course_set_marker($course->id, $course->marker+1);
3073 } elseif ($section < $course->marker && $course->marker <= $destination) {
3074 course_set_marker($course->id, $course->marker-1);
3077 $transaction->allow_commit();
3078 rebuild_course_cache($course->id, true);
3079 return true;
3083 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3084 * an original position number and a target position number, rebuilds the array so that the
3085 * move is made without any duplication of section positions.
3086 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3087 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3089 * @param array $sections
3090 * @param int $origin_position
3091 * @param int $target_position
3092 * @return array
3094 function reorder_sections($sections, $origin_position, $target_position) {
3095 if (!is_array($sections)) {
3096 return false;
3099 // We can't move section position 0
3100 if ($origin_position < 1) {
3101 echo "We can't move section position 0";
3102 return false;
3105 // Locate origin section in sections array
3106 if (!$origin_key = array_search($origin_position, $sections)) {
3107 echo "searched position not in sections array";
3108 return false; // searched position not in sections array
3111 // Extract origin section
3112 $origin_section = $sections[$origin_key];
3113 unset($sections[$origin_key]);
3115 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3116 $found = false;
3117 $append_array = array();
3118 foreach ($sections as $id => $position) {
3119 if ($found) {
3120 $append_array[$id] = $position;
3121 unset($sections[$id]);
3123 if ($position == $target_position) {
3124 if ($target_position < $origin_position) {
3125 $append_array[$id] = $position;
3126 unset($sections[$id]);
3128 $found = true;
3132 // Append moved section
3133 $sections[$origin_key] = $origin_section;
3135 // Append rest of array (if applicable)
3136 if (!empty($append_array)) {
3137 foreach ($append_array as $id => $position) {
3138 $sections[$id] = $position;
3142 // Renumber positions
3143 $position = 0;
3144 foreach ($sections as $id => $p) {
3145 $sections[$id] = $position;
3146 $position++;
3149 return $sections;
3154 * Move the module object $mod to the specified $section
3155 * If $beforemod exists then that is the module
3156 * before which $modid should be inserted
3157 * All parameters are objects
3159 function moveto_module($mod, $section, $beforemod=NULL) {
3160 global $OUTPUT, $DB;
3162 /// Remove original module from original section
3163 if (! delete_mod_from_section($mod->id, $mod->section)) {
3164 echo $OUTPUT->notification("Could not delete module from existing section");
3167 // if moving to a hidden section then hide module
3168 if ($mod->section != $section->id) {
3169 if (!$section->visible && $mod->visible) {
3170 // Set this in the object because it is sent as a response to ajax calls.
3171 $mod->visible = 0;
3172 set_coursemodule_visible($mod->id, 0);
3173 // Set visibleold to 1 so module will be visible when section is made visible.
3174 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
3176 if ($section->visible && !$mod->visible) {
3177 set_coursemodule_visible($mod->id, $mod->visibleold);
3178 // Set this in the object because it is sent as a response to ajax calls.
3179 $mod->visible = $mod->visibleold;
3183 /// Add the module into the new section
3184 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3185 return true;
3189 * Produces the editing buttons for a module
3191 * @global core_renderer $OUTPUT
3192 * @staticvar type $str
3193 * @param stdClass $mod The module to produce editing buttons for
3194 * @param bool $absolute_ignored ignored - all links are absolute
3195 * @param bool $moveselect If true a move seleciton process is used (default true)
3196 * @param int $indent The current indenting
3197 * @param int $section The section to link back to
3198 * @return string XHTML for the editing buttons
3200 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3201 global $CFG, $OUTPUT, $COURSE;
3203 static $str;
3205 $coursecontext = context_course::instance($mod->course);
3206 $modcontext = context_module::instance($mod->id);
3208 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3209 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3211 // no permission to edit anything
3212 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3213 return false;
3216 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3218 if (!isset($str)) {
3219 $str = new stdClass;
3220 $str->assign = get_string("assignroles", 'role');
3221 $str->delete = get_string("delete");
3222 $str->move = get_string("move");
3223 $str->moveup = get_string("moveup");
3224 $str->movedown = get_string("movedown");
3225 $str->moveright = get_string("moveright");
3226 $str->moveleft = get_string("moveleft");
3227 $str->update = get_string("update");
3228 $str->duplicate = get_string("duplicate");
3229 $str->hide = get_string("hide");
3230 $str->show = get_string("show");
3231 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3232 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3233 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3234 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3235 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3236 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3237 $str->edittitle = get_string('edittitle', 'moodle');
3240 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3242 if ($section !== null) {
3243 $baseurl->param('sr', $section);
3245 $actions = array();
3247 // AJAX edit title
3248 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3249 $actions[] = new action_link(
3250 new moodle_url($baseurl, array('update' => $mod->id)),
3251 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3252 null,
3253 array('class' => 'editing_title', 'title' => $str->edittitle)
3257 // leftright
3258 if ($hasmanageactivities) {
3259 if (right_to_left()) { // Exchange arrows on RTL
3260 $rightarrow = 't/left';
3261 $leftarrow = 't/right';
3262 } else {
3263 $rightarrow = 't/right';
3264 $leftarrow = 't/left';
3267 if ($indent > 0) {
3268 $actions[] = new action_link(
3269 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3270 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3271 null,
3272 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3275 if ($indent >= 0) {
3276 $actions[] = new action_link(
3277 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3278 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3279 null,
3280 array('class' => 'editing_moveright', 'title' => $str->moveright)
3285 // move
3286 if ($hasmanageactivities) {
3287 if ($moveselect) {
3288 $actions[] = new action_link(
3289 new moodle_url($baseurl, array('copy' => $mod->id)),
3290 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3291 null,
3292 array('class' => 'editing_move', 'title' => $str->move)
3294 } else {
3295 $actions[] = new action_link(
3296 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3297 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3298 null,
3299 array('class' => 'editing_moveup', 'title' => $str->moveup)
3301 $actions[] = new action_link(
3302 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3303 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3304 null,
3305 array('class' => 'editing_movedown', 'title' => $str->movedown)
3310 // Update
3311 if ($hasmanageactivities) {
3312 $actions[] = new action_link(
3313 new moodle_url($baseurl, array('update' => $mod->id)),
3314 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3315 null,
3316 array('class' => 'editing_update', 'title' => $str->update)
3320 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3321 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3322 $actions[] = new action_link(
3323 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3324 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3325 null,
3326 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3330 // Delete
3331 if ($hasmanageactivities) {
3332 $actions[] = new action_link(
3333 new moodle_url($baseurl, array('delete' => $mod->id)),
3334 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3335 null,
3336 array('class' => 'editing_delete', 'title' => $str->delete)
3340 // hideshow
3341 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3342 if ($mod->visible) {
3343 $actions[] = new action_link(
3344 new moodle_url($baseurl, array('hide' => $mod->id)),
3345 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3346 null,
3347 array('class' => 'editing_hide', 'title' => $str->hide)
3349 } else {
3350 $actions[] = new action_link(
3351 new moodle_url($baseurl, array('show' => $mod->id)),
3352 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3353 null,
3354 array('class' => 'editing_show', 'title' => $str->show)
3359 // groupmode
3360 if ($hasmanageactivities and $mod->groupmode !== false) {
3361 if ($mod->groupmode == SEPARATEGROUPS) {
3362 $groupmode = 0;
3363 $grouptitle = $str->groupsseparate;
3364 $forcedgrouptitle = $str->forcedgroupsseparate;
3365 $groupclass = 'editing_groupsseparate';
3366 $groupimage = 't/groups';
3367 } else if ($mod->groupmode == VISIBLEGROUPS) {
3368 $groupmode = 1;
3369 $grouptitle = $str->groupsvisible;
3370 $forcedgrouptitle = $str->forcedgroupsvisible;
3371 $groupclass = 'editing_groupsvisible';
3372 $groupimage = 't/groupv';
3373 } else {
3374 $groupmode = 2;
3375 $grouptitle = $str->groupsnone;
3376 $forcedgrouptitle = $str->forcedgroupsnone;
3377 $groupclass = 'editing_groupsnone';
3378 $groupimage = 't/groupn';
3380 if ($mod->groupmodelink) {
3381 $actions[] = new action_link(
3382 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3383 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3384 null,
3385 array('class' => $groupclass, 'title' => $grouptitle)
3387 } else {
3388 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3392 // Assign
3393 if (has_capability('moodle/role:assign', $modcontext)){
3394 $actions[] = new action_link(
3395 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3396 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3397 null,
3398 array('class' => 'editing_assign', 'title' => $str->assign)
3402 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3403 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3404 // the course page HTML will allow this to be removed.
3405 $output = ' ' . html_writer::start_tag('span', array('class' => 'commands'));
3406 foreach ($actions as $action) {
3407 if ($action instanceof renderable) {
3408 $output .= $OUTPUT->render($action);
3409 } else {
3410 $output .= $action;
3413 $output .= html_writer::end_tag('span');
3414 return $output;
3418 * given a course object with shortname & fullname, this function will
3419 * truncate the the number of chars allowed and add ... if it was too long
3421 function course_format_name ($course,$max=100) {
3423 $context = context_course::instance($course->id);
3424 $shortname = format_string($course->shortname, true, array('context' => $context));
3425 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3426 $str = $shortname.': '. $fullname;
3427 if (textlib::strlen($str) <= $max) {
3428 return $str;
3430 else {
3431 return textlib::substr($str,0,$max-3).'...';
3436 * Is the user allowed to add this type of module to this course?
3437 * @param object $course the course settings. Only $course->id is used.
3438 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3439 * @return bool whether the current user is allowed to add this type of module to this course.
3441 function course_allowed_module($course, $modname) {
3442 if (is_numeric($modname)) {
3443 throw new coding_exception('Function course_allowed_module no longer
3444 supports numeric module ids. Please update your code to pass the module name.');
3447 $capability = 'mod/' . $modname . ':addinstance';
3448 if (!get_capability_info($capability)) {
3449 // Debug warning that the capability does not exist, but no more than once per page.
3450 static $warned = array();
3451 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3452 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3453 debugging('The module ' . $modname . ' does not define the standard capability ' .
3454 $capability , DEBUG_DEVELOPER);
3455 $warned[$modname] = 1;
3458 // If the capability does not exist, the module can always be added.
3459 return true;
3462 $coursecontext = context_course::instance($course->id);
3463 return has_capability($capability, $coursecontext);
3467 * Recursively delete category including all subcategories and courses.
3468 * @param stdClass $category
3469 * @param boolean $showfeedback display some notices
3470 * @return array return deleted courses
3472 function category_delete_full($category, $showfeedback=true) {
3473 global $CFG, $DB;
3474 require_once($CFG->libdir.'/gradelib.php');
3475 require_once($CFG->libdir.'/questionlib.php');
3476 require_once($CFG->dirroot.'/cohort/lib.php');
3478 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3479 foreach ($children as $childcat) {
3480 category_delete_full($childcat, $showfeedback);
3484 $deletedcourses = array();
3485 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3486 foreach ($courses as $course) {
3487 if (!delete_course($course, false)) {
3488 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3490 $deletedcourses[] = $course;
3494 // move or delete cohorts in this context
3495 cohort_delete_category($category);
3497 // now delete anything that may depend on course category context
3498 grade_course_category_delete($category->id, 0, $showfeedback);
3499 if (!question_delete_course_category($category, 0, $showfeedback)) {
3500 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3503 // finally delete the category and it's context
3504 $DB->delete_records('course_categories', array('id'=>$category->id));
3505 delete_context(CONTEXT_COURSECAT, $category->id);
3506 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3508 events_trigger('course_category_deleted', $category);
3510 return $deletedcourses;
3514 * Delete category, but move contents to another category.
3515 * @param object $ccategory
3516 * @param int $newparentid category id
3517 * @return bool status
3519 function category_delete_move($category, $newparentid, $showfeedback=true) {
3520 global $CFG, $DB, $OUTPUT;
3521 require_once($CFG->libdir.'/gradelib.php');
3522 require_once($CFG->libdir.'/questionlib.php');
3523 require_once($CFG->dirroot.'/cohort/lib.php');
3525 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3526 return false;
3529 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3530 foreach ($children as $childcat) {
3531 move_category($childcat, $newparentcat);
3535 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3536 if (!move_courses(array_keys($courses), $newparentid)) {
3537 if ($showfeedback) {
3538 echo $OUTPUT->notification("Error moving courses");
3540 return false;
3542 if ($showfeedback) {
3543 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3547 // move or delete cohorts in this context
3548 cohort_delete_category($category);
3550 // now delete anything that may depend on course category context
3551 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3552 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3553 if ($showfeedback) {
3554 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3556 return false;
3559 // finally delete the category and it's context
3560 $DB->delete_records('course_categories', array('id'=>$category->id));
3561 delete_context(CONTEXT_COURSECAT, $category->id);
3562 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3564 events_trigger('course_category_deleted', $category);
3566 if ($showfeedback) {
3567 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3569 return true;
3573 * Efficiently moves many courses around while maintaining
3574 * sortorder in order.
3576 * @param array $courseids is an array of course ids
3577 * @param int $categoryid
3578 * @return bool success
3580 function move_courses($courseids, $categoryid) {
3581 global $CFG, $DB, $OUTPUT;
3583 if (empty($courseids)) {
3584 // nothing to do
3585 return;
3588 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3589 return false;
3592 $courseids = array_reverse($courseids);
3593 $newparent = context_coursecat::instance($category->id);
3594 $i = 1;
3596 foreach ($courseids as $courseid) {
3597 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3598 $course = new stdClass();
3599 $course->id = $courseid;
3600 $course->category = $category->id;
3601 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3602 if ($category->visible == 0) {
3603 // hide the course when moving into hidden category,
3604 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3605 $course->visible = 0;
3608 $DB->update_record('course', $course);
3609 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
3611 $context = context_course::instance($course->id);
3612 context_moved($context, $newparent);
3615 fix_course_sortorder();
3617 return true;
3621 * Hide course category and child course and subcategories
3622 * @param stdClass $category
3623 * @return void
3625 function course_category_hide($category) {
3626 global $DB;
3628 $category->visible = 0;
3629 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3630 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3631 $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
3632 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3633 // get all child categories and hide too
3634 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3635 foreach ($subcats as $cat) {
3636 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3637 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3638 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3639 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3642 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$category->id", $category->id);
3646 * Show course category and child course and subcategories
3647 * @param stdClass $category
3648 * @return void
3650 function course_category_show($category) {
3651 global $DB;
3653 $category->visible = 1;
3654 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3655 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3656 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3657 // get all child categories and unhide too
3658 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3659 foreach ($subcats as $cat) {
3660 if ($cat->visibleold) {
3661 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3663 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3666 add_to_log(SITEID, "category", "show", "editcategory.php?id=$category->id", $category->id);
3670 * Efficiently moves a category - NOTE that this can have
3671 * a huge impact access-control-wise...
3673 function move_category($category, $newparentcat) {
3674 global $CFG, $DB;
3676 $context = context_coursecat::instance($category->id);
3678 $hidecat = false;
3679 if (empty($newparentcat->id)) {
3680 $DB->set_field('course_categories', 'parent', 0, array('id' => $category->id));
3681 $newparent = context_system::instance();
3682 } else {
3683 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $category->id));
3684 $newparent = context_coursecat::instance($newparentcat->id);
3686 if (!$newparentcat->visible and $category->visible) {
3687 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3688 $hidecat = true;
3692 context_moved($context, $newparent);
3694 // now make it last in new category
3695 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3697 // Log action.
3698 add_to_log(SITEID, "category", "move", "editcategory.php?id=$category->id", $category->id);
3700 // and fix the sortorders
3701 fix_course_sortorder();
3703 if ($hidecat) {
3704 course_category_hide($category);
3709 * Returns the display name of the given section that the course prefers
3711 * Implementation of this function is provided by course format
3712 * @see format_base::get_section_name()
3714 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3715 * @param int|stdClass $section Section object from database or just field course_sections.section
3716 * @return string Display name that the course format prefers, e.g. "Week 2"
3718 function get_section_name($courseorid, $section) {
3719 return course_get_format($courseorid)->get_section_name($section);
3723 * Tells if current course format uses sections
3725 * @param string $format Course format ID e.g. 'weeks' $course->format
3726 * @return bool
3728 function course_format_uses_sections($format) {
3729 $course = new stdClass();
3730 $course->format = $format;
3731 return course_get_format($course)->uses_sections();
3735 * Returns the information about the ajax support in the given source format
3737 * The returned object's property (boolean)capable indicates that
3738 * the course format supports Moodle course ajax features.
3739 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3741 * @param string $format
3742 * @return stdClass
3744 function course_format_ajax_support($format) {
3745 $course = new stdClass();
3746 $course->format = $format;
3747 return course_get_format($course)->supports_ajax();
3751 * Can the current user delete this course?
3752 * Course creators have exception,
3753 * 1 day after the creation they can sill delete the course.
3754 * @param int $courseid
3755 * @return boolean
3757 function can_delete_course($courseid) {
3758 global $USER, $DB;
3760 $context = context_course::instance($courseid);
3762 if (has_capability('moodle/course:delete', $context)) {
3763 return true;
3766 // hack: now try to find out if creator created this course recently (1 day)
3767 if (!has_capability('moodle/course:create', $context)) {
3768 return false;
3771 $since = time() - 60*60*24;
3773 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3774 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3776 return $DB->record_exists_select('log', $select, $params);
3780 * Save the Your name for 'Some role' strings.
3782 * @param integer $courseid the id of this course.
3783 * @param array $data the data that came from the course settings form.
3785 function save_local_role_names($courseid, $data) {
3786 global $DB;
3787 $context = context_course::instance($courseid);
3789 foreach ($data as $fieldname => $value) {
3790 if (strpos($fieldname, 'role_') !== 0) {
3791 continue;
3793 list($ignored, $roleid) = explode('_', $fieldname);
3795 // make up our mind whether we want to delete, update or insert
3796 if (!$value) {
3797 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3799 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3800 $rolename->name = $value;
3801 $DB->update_record('role_names', $rolename);
3803 } else {
3804 $rolename = new stdClass;
3805 $rolename->contextid = $context->id;
3806 $rolename->roleid = $roleid;
3807 $rolename->name = $value;
3808 $DB->insert_record('role_names', $rolename);
3814 * Create a course and either return a $course object
3816 * Please note this functions does not verify any access control,
3817 * the calling code is responsible for all validation (usually it is the form definition).
3819 * @param array $editoroptions course description editor options
3820 * @param object $data - all the data needed for an entry in the 'course' table
3821 * @return object new course instance
3823 function create_course($data, $editoroptions = NULL) {
3824 global $CFG, $DB;
3826 //check the categoryid - must be given for all new courses
3827 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3829 //check if the shortname already exist
3830 if (!empty($data->shortname)) {
3831 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3832 throw new moodle_exception('shortnametaken');
3836 //check if the id number already exist
3837 if (!empty($data->idnumber)) {
3838 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3839 throw new moodle_exception('idnumbertaken');
3843 $data->timecreated = time();
3844 $data->timemodified = $data->timecreated;
3846 // place at beginning of any category
3847 $data->sortorder = 0;
3849 if ($editoroptions) {
3850 // summary text is updated later, we need context to store the files first
3851 $data->summary = '';
3852 $data->summary_format = FORMAT_HTML;
3855 if (!isset($data->visible)) {
3856 // data not from form, add missing visibility info
3857 $data->visible = $category->visible;
3859 $data->visibleold = $data->visible;
3861 $newcourseid = $DB->insert_record('course', $data);
3862 $context = context_course::instance($newcourseid, MUST_EXIST);
3864 if ($editoroptions) {
3865 // Save the files used in the summary editor and store
3866 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3867 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3868 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3871 // update course format options
3872 course_get_format($newcourseid)->update_course_format_options($data);
3874 $course = course_get_format($newcourseid)->get_course();
3876 // Setup the blocks
3877 blocks_add_default_course_blocks($course);
3879 // Create a default section.
3880 course_create_sections_if_missing($course, 0);
3882 fix_course_sortorder();
3884 // new context created - better mark it as dirty
3885 mark_context_dirty($context->path);
3887 // Save any custom role names.
3888 save_local_role_names($course->id, (array)$data);
3890 // set up enrolments
3891 enrol_course_updated(true, $course, $data);
3893 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3895 // Trigger events
3896 events_trigger('course_created', $course);
3898 return $course;
3902 * Create a new course category and marks the context as dirty
3904 * This function does not set the sortorder for the new category and
3905 * @see{fix_course_sortorder} should be called after creating a new course
3906 * category
3908 * Please note that this function does not verify access control.
3910 * @param object $category All of the data required for an entry in the course_categories table
3911 * @return object new course category
3913 function create_course_category($category) {
3914 global $DB;
3916 $category->timemodified = time();
3917 $category->id = $DB->insert_record('course_categories', $category);
3918 $category = $DB->get_record('course_categories', array('id' => $category->id));
3920 // We should mark the context as dirty
3921 $category->context = context_coursecat::instance($category->id);
3922 $category->context->mark_dirty();
3924 return $category;
3928 * Update a course.
3930 * Please note this functions does not verify any access control,
3931 * the calling code is responsible for all validation (usually it is the form definition).
3933 * @param object $data - all the data needed for an entry in the 'course' table
3934 * @param array $editoroptions course description editor options
3935 * @return void
3937 function update_course($data, $editoroptions = NULL) {
3938 global $CFG, $DB;
3940 $data->timemodified = time();
3942 $oldcourse = course_get_format($data->id)->get_course();
3943 $context = context_course::instance($oldcourse->id);
3945 if ($editoroptions) {
3946 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3949 if (!isset($data->category) or empty($data->category)) {
3950 // prevent nulls and 0 in category field
3951 unset($data->category);
3953 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3955 if (!isset($data->visible)) {
3956 // data not from form, add missing visibility info
3957 $data->visible = $oldcourse->visible;
3960 if ($data->visible != $oldcourse->visible) {
3961 // reset the visibleold flag when manually hiding/unhiding course
3962 $data->visibleold = $data->visible;
3963 } else {
3964 if ($movecat) {
3965 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3966 if (empty($newcategory->visible)) {
3967 // make sure when moving into hidden category the course is hidden automatically
3968 $data->visible = 0;
3973 // Update with the new data
3974 $DB->update_record('course', $data);
3975 // make sure the modinfo cache is reset
3976 rebuild_course_cache($data->id);
3978 // update course format options with full course data
3979 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
3981 $course = $DB->get_record('course', array('id'=>$data->id));
3983 if ($movecat) {
3984 $newparent = context_coursecat::instance($course->category);
3985 context_moved($context, $newparent);
3988 fix_course_sortorder();
3990 // Test for and remove blocks which aren't appropriate anymore
3991 blocks_remove_inappropriate($course);
3993 // Save any custom role names.
3994 save_local_role_names($course->id, $data);
3996 // update enrol settings
3997 enrol_course_updated(false, $course, $data);
3999 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4001 // Trigger events
4002 events_trigger('course_updated', $course);
4004 if ($oldcourse->format !== $course->format) {
4005 // Remove all options stored for the previous format
4006 // We assume that new course format migrated everything it needed watching trigger
4007 // 'course_updated' and in method format_XXX::update_course_format_options()
4008 $DB->delete_records('course_format_options',
4009 array('courseid' => $course->id, 'format' => $oldcourse->format));
4014 * Average number of participants
4015 * @return integer
4017 function average_number_of_participants() {
4018 global $DB, $SITE;
4020 //count total of enrolments for visible course (except front page)
4021 $sql = 'SELECT COUNT(*) FROM (
4022 SELECT DISTINCT ue.userid, e.courseid
4023 FROM {user_enrolments} ue, {enrol} e, {course} c
4024 WHERE ue.enrolid = e.id
4025 AND e.courseid <> :siteid
4026 AND c.id = e.courseid
4027 AND c.visible = 1) total';
4028 $params = array('siteid' => $SITE->id);
4029 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4032 //count total of visible courses (minus front page)
4033 $coursetotal = $DB->count_records('course', array('visible' => 1));
4034 $coursetotal = $coursetotal - 1 ;
4036 //average of enrolment
4037 if (empty($coursetotal)) {
4038 $participantaverage = 0;
4039 } else {
4040 $participantaverage = $enrolmenttotal / $coursetotal;
4043 return $participantaverage;
4047 * Average number of course modules
4048 * @return integer
4050 function average_number_of_courses_modules() {
4051 global $DB, $SITE;
4053 //count total of visible course module (except front page)
4054 $sql = 'SELECT COUNT(*) FROM (
4055 SELECT cm.course, cm.module
4056 FROM {course} c, {course_modules} cm
4057 WHERE c.id = cm.course
4058 AND c.id <> :siteid
4059 AND cm.visible = 1
4060 AND c.visible = 1) total';
4061 $params = array('siteid' => $SITE->id);
4062 $moduletotal = $DB->count_records_sql($sql, $params);
4065 //count total of visible courses (minus front page)
4066 $coursetotal = $DB->count_records('course', array('visible' => 1));
4067 $coursetotal = $coursetotal - 1 ;
4069 //average of course module
4070 if (empty($coursetotal)) {
4071 $coursemoduleaverage = 0;
4072 } else {
4073 $coursemoduleaverage = $moduletotal / $coursetotal;
4076 return $coursemoduleaverage;
4080 * This class pertains to course requests and contains methods associated with
4081 * create, approving, and removing course requests.
4083 * Please note we do not allow embedded images here because there is no context
4084 * to store them with proper access control.
4086 * @copyright 2009 Sam Hemelryk
4087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4088 * @since Moodle 2.0
4090 * @property-read int $id
4091 * @property-read string $fullname
4092 * @property-read string $shortname
4093 * @property-read string $summary
4094 * @property-read int $summaryformat
4095 * @property-read int $summarytrust
4096 * @property-read string $reason
4097 * @property-read int $requester
4099 class course_request {
4102 * This is the stdClass that stores the properties for the course request
4103 * and is externally accessed through the __get magic method
4104 * @var stdClass
4106 protected $properties;
4109 * An array of options for the summary editor used by course request forms.
4110 * This is initially set by {@link summary_editor_options()}
4111 * @var array
4112 * @static
4114 protected static $summaryeditoroptions;
4117 * Static function to prepare the summary editor for working with a course
4118 * request.
4120 * @static
4121 * @param null|stdClass $data Optional, an object containing the default values
4122 * for the form, these may be modified when preparing the
4123 * editor so this should be called before creating the form
4124 * @return stdClass An object that can be used to set the default values for
4125 * an mforms form
4127 public static function prepare($data=null) {
4128 if ($data === null) {
4129 $data = new stdClass;
4131 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4132 return $data;
4136 * Static function to create a new course request when passed an array of properties
4137 * for it.
4139 * This function also handles saving any files that may have been used in the editor
4141 * @static
4142 * @param stdClass $data
4143 * @return course_request The newly created course request
4145 public static function create($data) {
4146 global $USER, $DB, $CFG;
4147 $data->requester = $USER->id;
4149 // Setting the default category if none set.
4150 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
4151 $data->category = $CFG->defaultrequestcategory;
4154 // Summary is a required field so copy the text over
4155 $data->summary = $data->summary_editor['text'];
4156 $data->summaryformat = $data->summary_editor['format'];
4158 $data->id = $DB->insert_record('course_request', $data);
4160 // Create a new course_request object and return it
4161 $request = new course_request($data);
4163 // Notify the admin if required.
4164 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4166 $a = new stdClass;
4167 $a->link = "$CFG->wwwroot/course/pending.php";
4168 $a->user = fullname($USER);
4169 $subject = get_string('courserequest');
4170 $message = get_string('courserequestnotifyemail', 'admin', $a);
4171 foreach ($users as $user) {
4172 $request->notify($user, $USER, 'courserequested', $subject, $message);
4176 return $request;
4180 * Returns an array of options to use with a summary editor
4182 * @uses course_request::$summaryeditoroptions
4183 * @return array An array of options to use with the editor
4185 public static function summary_editor_options() {
4186 global $CFG;
4187 if (self::$summaryeditoroptions === null) {
4188 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4190 return self::$summaryeditoroptions;
4194 * Loads the properties for this course request object. Id is required and if
4195 * only id is provided then we load the rest of the properties from the database
4197 * @param stdClass|int $properties Either an object containing properties
4198 * or the course_request id to load
4200 public function __construct($properties) {
4201 global $DB;
4202 if (empty($properties->id)) {
4203 if (empty($properties)) {
4204 throw new coding_exception('You must provide a course request id when creating a course_request object');
4206 $id = $properties;
4207 $properties = new stdClass;
4208 $properties->id = (int)$id;
4209 unset($id);
4211 if (empty($properties->requester)) {
4212 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4213 print_error('unknowncourserequest');
4215 } else {
4216 $this->properties = $properties;
4218 $this->properties->collision = null;
4222 * Returns the requested property
4224 * @param string $key
4225 * @return mixed
4227 public function __get($key) {
4228 return $this->properties->$key;
4232 * Override this to ensure empty($request->blah) calls return a reliable answer...
4234 * This is required because we define the __get method
4236 * @param mixed $key
4237 * @return bool True is it not empty, false otherwise
4239 public function __isset($key) {
4240 return (!empty($this->properties->$key));
4244 * Returns the user who requested this course
4246 * Uses a static var to cache the results and cut down the number of db queries
4248 * @staticvar array $requesters An array of cached users
4249 * @return stdClass The user who requested the course
4251 public function get_requester() {
4252 global $DB;
4253 static $requesters= array();
4254 if (!array_key_exists($this->properties->requester, $requesters)) {
4255 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4257 return $requesters[$this->properties->requester];
4261 * Checks that the shortname used by the course does not conflict with any other
4262 * courses that exist
4264 * @param string|null $shortnamemark The string to append to the requests shortname
4265 * should a conflict be found
4266 * @return bool true is there is a conflict, false otherwise
4268 public function check_shortname_collision($shortnamemark = '[*]') {
4269 global $DB;
4271 if ($this->properties->collision !== null) {
4272 return $this->properties->collision;
4275 if (empty($this->properties->shortname)) {
4276 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4277 $this->properties->collision = false;
4278 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4279 if (!empty($shortnamemark)) {
4280 $this->properties->shortname .= ' '.$shortnamemark;
4282 $this->properties->collision = true;
4283 } else {
4284 $this->properties->collision = false;
4286 return $this->properties->collision;
4290 * This function approves the request turning it into a course
4292 * This function converts the course request into a course, at the same time
4293 * transferring any files used in the summary to the new course and then removing
4294 * the course request and the files associated with it.
4296 * @return int The id of the course that was created from this request
4298 public function approve() {
4299 global $CFG, $DB, $USER;
4301 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4303 $courseconfig = get_config('moodlecourse');
4305 // Transfer appropriate settings
4306 $data = clone($this->properties);
4307 unset($data->id);
4308 unset($data->reason);
4309 unset($data->requester);
4311 // If the category is not set, if the current user does not have the rights to change the category, or if the
4312 // category does not exist, we set the default category to the course to be approved.
4313 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
4314 if (empty($data->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
4315 (!$category = get_course_category($data->category))) {
4316 $category = get_course_category($CFG->defaultrequestcategory);
4319 // Set category
4320 $data->category = $category->id;
4321 $data->sortorder = $category->sortorder; // place as the first in category
4323 // Set misc settings
4324 $data->requested = 1;
4326 // Apply course default settings
4327 $data->format = $courseconfig->format;
4328 $data->newsitems = $courseconfig->newsitems;
4329 $data->showgrades = $courseconfig->showgrades;
4330 $data->showreports = $courseconfig->showreports;
4331 $data->maxbytes = $courseconfig->maxbytes;
4332 $data->groupmode = $courseconfig->groupmode;
4333 $data->groupmodeforce = $courseconfig->groupmodeforce;
4334 $data->visible = $courseconfig->visible;
4335 $data->visibleold = $data->visible;
4336 $data->lang = $courseconfig->lang;
4338 $course = create_course($data);
4339 $context = context_course::instance($course->id, MUST_EXIST);
4341 // add enrol instances
4342 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4343 if ($manual = enrol_get_plugin('manual')) {
4344 $manual->add_default_instance($course);
4348 // enrol the requester as teacher if necessary
4349 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4350 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4353 $this->delete();
4355 $a = new stdClass();
4356 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4357 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4358 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4360 return $course->id;
4364 * Reject a course request
4366 * This function rejects a course request, emailing the requesting user the
4367 * provided notice and then removing the request from the database
4369 * @param string $notice The message to display to the user
4371 public function reject($notice) {
4372 global $USER, $DB;
4373 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4374 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4375 $this->delete();
4379 * Deletes the course request and any associated files
4381 public function delete() {
4382 global $DB;
4383 $DB->delete_records('course_request', array('id' => $this->properties->id));
4387 * Send a message from one user to another using events_trigger
4389 * @param object $touser
4390 * @param object $fromuser
4391 * @param string $name
4392 * @param string $subject
4393 * @param string $message
4395 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4396 $eventdata = new stdClass();
4397 $eventdata->component = 'moodle';
4398 $eventdata->name = $name;
4399 $eventdata->userfrom = $fromuser;
4400 $eventdata->userto = $touser;
4401 $eventdata->subject = $subject;
4402 $eventdata->fullmessage = $message;
4403 $eventdata->fullmessageformat = FORMAT_PLAIN;
4404 $eventdata->fullmessagehtml = '';
4405 $eventdata->smallmessage = '';
4406 $eventdata->notification = 1;
4407 message_send($eventdata);
4412 * Return a list of page types
4413 * @param string $pagetype current page type
4414 * @param stdClass $parentcontext Block's parent context
4415 * @param stdClass $currentcontext Current context of block
4417 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4418 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
4419 if (isset($currentcontext)) {
4420 // if above course context ,display all course fomats
4421 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4422 if ($course->id == SITEID) {
4423 return array('*'=>get_string('page-x', 'pagetype'));
4426 return array('*'=>get_string('page-x', 'pagetype'),
4427 'course-*'=>get_string('page-course-x', 'pagetype'),
4428 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4433 * Determine whether course ajax should be enabled for the specified course
4435 * @param stdClass $course The course to test against
4436 * @return boolean Whether course ajax is enabled or note
4438 function course_ajax_enabled($course) {
4439 global $CFG, $PAGE, $SITE;
4441 // Ajax must be enabled globally
4442 if (!$CFG->enableajax) {
4443 return false;
4446 // The user must be editing for AJAX to be included
4447 if (!$PAGE->user_is_editing()) {
4448 return false;
4451 // Check that the theme suports
4452 if (!$PAGE->theme->enablecourseajax) {
4453 return false;
4456 // Check that the course format supports ajax functionality
4457 // The site 'format' doesn't have information on course format support
4458 if ($SITE->id !== $course->id) {
4459 $courseformatajaxsupport = course_format_ajax_support($course->format);
4460 if (!$courseformatajaxsupport->capable) {
4461 return false;
4465 // All conditions have been met so course ajax should be enabled
4466 return true;
4470 * Include the relevant javascript and language strings for the resource
4471 * toolbox YUI module
4473 * @param integer $id The ID of the course being applied to
4474 * @param array $usedmodules An array containing the names of the modules in use on the page
4475 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4476 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4477 * * resourceurl The URL to post changes to for resource changes
4478 * * sectionurl The URL to post changes to for section changes
4479 * * pageparams Additional parameters to pass through in the post
4480 * @return bool
4482 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4483 global $PAGE, $SITE;
4485 // Ensure that ajax should be included
4486 if (!course_ajax_enabled($course)) {
4487 return false;
4490 if (!$config) {
4491 $config = new stdClass();
4494 // The URL to use for resource changes
4495 if (!isset($config->resourceurl)) {
4496 $config->resourceurl = '/course/rest.php';
4499 // The URL to use for section changes
4500 if (!isset($config->sectionurl)) {
4501 $config->sectionurl = '/course/rest.php';
4504 // Any additional parameters which need to be included on page submission
4505 if (!isset($config->pageparams)) {
4506 $config->pageparams = array();
4509 // Include toolboxes
4510 $PAGE->requires->yui_module('moodle-course-toolboxes',
4511 'M.course.init_resource_toolbox',
4512 array(array(
4513 'courseid' => $course->id,
4514 'ajaxurl' => $config->resourceurl,
4515 'config' => $config,
4518 $PAGE->requires->yui_module('moodle-course-toolboxes',
4519 'M.course.init_section_toolbox',
4520 array(array(
4521 'courseid' => $course->id,
4522 'format' => $course->format,
4523 'ajaxurl' => $config->sectionurl,
4524 'config' => $config,
4528 // Include course dragdrop
4529 if ($course->id != $SITE->id) {
4530 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4531 array(array(
4532 'courseid' => $course->id,
4533 'ajaxurl' => $config->sectionurl,
4534 'config' => $config,
4535 )), null, true);
4537 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4538 array(array(
4539 'courseid' => $course->id,
4540 'ajaxurl' => $config->resourceurl,
4541 'config' => $config,
4542 )), null, true);
4545 // Include blocks dragdrop
4546 $params = array(
4547 'courseid' => $course->id,
4548 'pagetype' => $PAGE->pagetype,
4549 'pagelayout' => $PAGE->pagelayout,
4550 'subpage' => $PAGE->subpage,
4551 'regions' => $PAGE->blocks->get_regions(),
4553 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4555 // Require various strings for the command toolbox
4556 $PAGE->requires->strings_for_js(array(
4557 'moveleft',
4558 'deletechecktype',
4559 'deletechecktypename',
4560 'edittitle',
4561 'edittitleinstructions',
4562 'show',
4563 'hide',
4564 'groupsnone',
4565 'groupsvisible',
4566 'groupsseparate',
4567 'clicktochangeinbrackets',
4568 'markthistopic',
4569 'markedthistopic',
4570 'move',
4571 'movesection',
4572 ), 'moodle');
4574 // Include format-specific strings
4575 if ($course->id != $SITE->id) {
4576 $PAGE->requires->strings_for_js(array(
4577 'showfromothers',
4578 'hidefromothers',
4579 ), 'format_' . $course->format);
4582 // For confirming resource deletion we need the name of the module in question
4583 foreach ($usedmodules as $module => $modname) {
4584 $PAGE->requires->string_for_js('pluginname', $module);
4587 // Load drag and drop upload AJAX.
4588 dndupload_add_to_course($course, $enabledmodules);
4590 // Add the module chooser
4591 $PAGE->requires->yui_module('moodle-course-modchooser',
4592 'M.course.init_chooser',
4593 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
4595 $PAGE->requires->strings_for_js(array(
4596 'addresourceoractivity',
4597 'modchooserenable',
4598 'modchooserdisable',
4599 ), 'moodle');
4601 return true;
4605 * Returns the sorted list of available course formats, filtered by enabled if necessary
4607 * @param bool $enabledonly return only formats that are enabled
4608 * @return array array of sorted format names
4610 function get_sorted_course_formats($enabledonly = false) {
4611 global $CFG;
4612 $formats = get_plugin_list('format');
4614 if (!empty($CFG->format_plugins_sortorder)) {
4615 $order = explode(',', $CFG->format_plugins_sortorder);
4616 $order = array_merge(array_intersect($order, array_keys($formats)),
4617 array_diff(array_keys($formats), $order));
4618 } else {
4619 $order = array_keys($formats);
4621 if (!$enabledonly) {
4622 return $order;
4624 $sortedformats = array();
4625 foreach ($order as $formatname) {
4626 if (!get_config('format_'.$formatname, 'disabled')) {
4627 $sortedformats[] = $formatname;
4630 return $sortedformats;
4634 * The URL to use for the specified course (with section)
4636 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
4637 * @param int|stdClass $section Section object from database or just field course_sections.section
4638 * if omitted the course view page is returned
4639 * @param array $options options for view URL. At the moment core uses:
4640 * 'navigation' (bool) if true and section has no separate page, the function returns null
4641 * 'sr' (int) used by multipage formats to specify to which section to return
4642 * @return moodle_url The url of course
4644 function course_get_url($courseorid, $section = null, $options = array()) {
4645 return course_get_format($courseorid)->get_view_url($section, $options);