3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
27 defined('MOODLE_INTERNAL') ||
die;
29 require_once($CFG->libdir
.'/completionlib.php');
30 require_once($CFG->libdir
.'/filelib.php');
32 define('COURSE_MAX_LOG_DISPLAY', 150); // days
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
36 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
37 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
38 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
39 define('FRONTPAGENEWS', '0');
40 define('FRONTPAGECOURSELIST', '1');
41 define('FRONTPAGECATEGORYNAMES', '2');
42 define('FRONTPAGETOPICONLY', '3');
43 define('FRONTPAGECATEGORYCOMBO', '4');
44 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
45 define('EXCELROWS', 65535);
46 define('FIRSTUSEDEXCELROW', 3);
48 define('MOD_CLASS_ACTIVITY', 0);
49 define('MOD_CLASS_RESOURCE', 1);
51 function make_log_url($module, $url) {
60 if (strpos($url, '../') === 0) {
61 $url = ltrim($url, '.');
63 $url = "/course/$url";
68 $url = "/$module/$url";
81 $url = "/message/$url";
93 $url = "/mod/$module/$url";
97 //now let's sanitise urls - there might be some ugly nasties:-(
98 $parts = explode('?', $url);
99 $script = array_shift($parts);
100 if (strpos($script, 'http') === 0) {
101 $script = clean_param($script, PARAM_URL
);
103 $script = clean_param($script, PARAM_PATH
);
108 $query = implode('', $parts);
109 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
110 $parts = explode('&', $query);
111 $eq = urlencode('=');
112 foreach ($parts as $key=>$part) {
113 $part = urlencode(urldecode($part));
114 $part = str_replace($eq, '=', $part);
115 $parts[$key] = $part;
117 $query = '?'.implode('&', $parts);
120 return $script.$query;
124 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
125 $modname="", $modid=0, $modaction="", $groupid=0) {
128 // It is assumed that $date is the GMT time of midnight for that day,
129 // and so the next 86400 seconds worth of logs are printed.
131 /// Setup for group handling.
133 // TODO: I don't understand group/context/etc. enough to be able to do
134 // something interesting with it here
135 // What is the context of a remote course?
137 /// If the group mode is separate, and this user does not have editing privileges,
138 /// then only the user's group can be viewed.
139 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
140 // $groupid = get_current_group($course->id);
142 /// If this course doesn't have groups, no groupid can be specified.
143 //else if (!$course->groupmode) {
152 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
154 LEFT JOIN {user} u ON l.userid = u.id
158 $where .= "l.hostid = :hostid";
159 $params['hostid'] = $hostid;
161 // TODO: Is 1 really a magic number referring to the sitename?
162 if ($course != SITEID ||
$modid != 0) {
163 $where .= " AND l.course=:courseid";
164 $params['courseid'] = $course;
168 $where .= " AND l.module = :modname";
169 $params['modname'] = $modname;
172 if ('site_errors' === $modid) {
173 $where .= " AND ( l.action='error' OR l.action='infected' )";
175 //TODO: This assumes that modids are the same across sites... probably
177 $where .= " AND l.cmid = :modid";
178 $params['modid'] = $modid;
182 $firstletter = substr($modaction, 0, 1);
183 if ($firstletter == '-') {
184 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
185 $params['modaction'] = '%'.substr($modaction, 1).'%';
187 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
188 $params['modaction'] = '%'.$modaction.'%';
193 $where .= " AND l.userid = :user";
194 $params['user'] = $user;
198 $enddate = $date +
86400;
199 $where .= " AND l.time > :date AND l.time < :enddate";
200 $params['date'] = $date;
201 $params['enddate'] = $enddate;
205 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
206 if(!empty($result['totalcount'])) {
207 $where .= " ORDER BY $order";
208 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
210 $result['logs'] = array();
215 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
216 $modname="", $modid=0, $modaction="", $groupid=0) {
217 global $DB, $SESSION, $USER;
218 // It is assumed that $date is the GMT time of midnight for that day,
219 // and so the next 86400 seconds worth of logs are printed.
221 /// Setup for group handling.
223 /// If the group mode is separate, and this user does not have editing privileges,
224 /// then only the user's group can be viewed.
225 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
226 if (isset($SESSION->currentgroup
[$course->id
])) {
227 $groupid = $SESSION->currentgroup
[$course->id
];
229 $groupid = groups_get_all_groups($course->id
, $USER->id
);
230 if (is_array($groupid)) {
231 $groupid = array_shift(array_keys($groupid));
232 $SESSION->currentgroup
[$course->id
] = $groupid;
238 /// If this course doesn't have groups, no groupid can be specified.
239 else if (!$course->groupmode
) {
246 if ($course->id
!= SITEID ||
$modid != 0) {
247 $joins[] = "l.course = :courseid";
248 $params['courseid'] = $course->id
;
252 $joins[] = "l.module = :modname";
253 $params['modname'] = $modname;
256 if ('site_errors' === $modid) {
257 $joins[] = "( l.action='error' OR l.action='infected' )";
259 $joins[] = "l.cmid = :modid";
260 $params['modid'] = $modid;
264 $firstletter = substr($modaction, 0, 1);
265 if ($firstletter == '-') {
266 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
267 $params['modaction'] = '%'.substr($modaction, 1).'%';
269 $joins[] = $DB->sql_like('l.action', ':modaction', false);
270 $params['modaction'] = '%'.$modaction.'%';
275 /// Getting all members of a group.
276 if ($groupid and !$user) {
277 if ($gusers = groups_get_members($groupid)) {
278 $gusers = array_keys($gusers);
279 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
281 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
285 $joins[] = "l.userid = :userid";
286 $params['userid'] = $user;
290 $enddate = $date +
86400;
291 $joins[] = "l.time > :date AND l.time < :enddate";
292 $params['date'] = $date;
293 $params['enddate'] = $enddate;
296 $selector = implode(' AND ', $joins);
298 $totalcount = 0; // Initialise
300 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
301 $result['totalcount'] = $totalcount;
306 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
307 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
309 global $CFG, $DB, $OUTPUT;
311 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
312 $modname, $modid, $modaction, $groupid)) {
313 echo $OUTPUT->notification("No logs found!");
314 echo $OUTPUT->footer();
320 if ($course->id
== SITEID
) {
322 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
323 foreach ($ccc as $cc) {
324 $courses[$cc->id
] = $cc->shortname
;
328 $courses[$course->id
] = $course->shortname
;
331 $totalcount = $logs['totalcount'];
334 $tt = getdate(time());
335 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
337 $strftimedatetime = get_string("strftimedatetime");
339 echo "<div class=\"info\">\n";
340 print_string("displayingrecords", "", $totalcount);
343 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
345 $table = new html_table();
346 $table->classes
= array('logtable','generalbox');
347 $table->align
= array('right', 'left', 'left');
348 $table->head
= array(
350 get_string('ip_address'),
351 get_string('fullnameuser'),
352 get_string('action'),
355 $table->data
= array();
357 if ($course->id
== SITEID
) {
358 array_unshift($table->align
, 'left');
359 array_unshift($table->head
, get_string('course'));
362 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
363 if (empty($logs['logs'])) {
364 $logs['logs'] = array();
367 foreach ($logs['logs'] as $log) {
369 if (isset($ldcache[$log->module
][$log->action
])) {
370 $ld = $ldcache[$log->module
][$log->action
];
372 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
373 $ldcache[$log->module
][$log->action
] = $ld;
375 if ($ld && is_numeric($log->info
)) {
376 // ugly hack to make sure fullname is shown correctly
377 if ($ld->mtable
== 'user' && $ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname')) {
378 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
380 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
385 $log->info
= format_string($log->info
);
387 // If $log->url has been trimmed short by the db size restriction
388 // code in add_to_log, keep a note so we don't add a link to a broken url
389 $tl=textlib_get_instance();
390 $brokenurl=($tl->strlen($log->url
)==100 && $tl->substr($log->url
,97)=='...');
393 if ($course->id
== SITEID
) {
394 if (empty($log->course
)) {
395 $row[] = get_string('site');
397 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>";
401 $row[] = userdate($log->time
, '%a').' '.userdate($log->time
, $strftimedatetime);
403 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
404 $row[] = $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
406 $row[] = html_writer
::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
))));
408 $displayaction="$log->module $log->action";
410 $row[] = $displayaction;
412 $link = make_log_url($log->module
,$log->url
);
413 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
416 $table->data
[] = $row;
419 echo html_writer
::table($table);
420 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
424 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
425 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
427 global $CFG, $DB, $OUTPUT;
429 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
430 $modname, $modid, $modaction, $groupid)) {
431 echo $OUTPUT->notification("No logs found!");
432 echo $OUTPUT->footer();
436 if ($course->id
== SITEID
) {
438 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
439 foreach ($ccc as $cc) {
440 $courses[$cc->id
] = $cc->shortname
;
445 $totalcount = $logs['totalcount'];
448 $tt = getdate(time());
449 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
451 $strftimedatetime = get_string("strftimedatetime");
453 echo "<div class=\"info\">\n";
454 print_string("displayingrecords", "", $totalcount);
457 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
459 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
461 if ($course->id
== SITEID
) {
462 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
464 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
465 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
466 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
467 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
468 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
471 if (empty($logs['logs'])) {
477 foreach ($logs['logs'] as $log) {
479 $log->info
= $log->coursename
;
480 $row = ($row +
1) %
2;
482 if (isset($ldcache[$log->module
][$log->action
])) {
483 $ld = $ldcache[$log->module
][$log->action
];
485 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
486 $ldcache[$log->module
][$log->action
] = $ld;
488 if (0 && $ld && !empty($log->info
)) {
489 // ugly hack to make sure fullname is shown correctly
490 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
491 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
493 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
498 $log->info
= format_string($log->info
);
500 echo '<tr class="r'.$row.'">';
501 if ($course->id
== SITEID
) {
502 $courseshortname = format_string($courses[$log->course
], true, array('context' => get_context_instance(CONTEXT_COURSE
, SITEID
)));
503 echo "<td class=\"r$row c0\" >\n";
504 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
507 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
508 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
509 echo "<td class=\"r$row c2\" >\n";
510 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
511 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
513 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
514 echo "<td class=\"r$row c3\" >\n";
515 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
517 echo "<td class=\"r$row c4\">\n";
518 echo $log->action
.': '.$log->module
;
520 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
525 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
529 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
530 $modid, $modaction, $groupid) {
533 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
534 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
536 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
537 $modname, $modid, $modaction, $groupid)) {
543 if ($course->id
== SITEID
) {
545 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
546 foreach ($ccc as $cc) {
547 $courses[$cc->id
] = $cc->shortname
;
551 $courses[$course->id
] = $course->shortname
;
556 $tt = getdate(time());
557 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
559 $strftimedatetime = get_string("strftimedatetime");
561 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
563 header("Content-Type: application/download\n");
564 header("Content-Disposition: attachment; filename=$filename");
565 header("Expires: 0");
566 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
567 header("Pragma: public");
569 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
572 if (empty($logs['logs'])) {
576 foreach ($logs['logs'] as $log) {
577 if (isset($ldcache[$log->module
][$log->action
])) {
578 $ld = $ldcache[$log->module
][$log->action
];
580 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
581 $ldcache[$log->module
][$log->action
] = $ld;
583 if ($ld && !empty($log->info
)) {
584 // ugly hack to make sure fullname is shown correctly
585 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
586 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
588 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
593 $log->info
= format_string($log->info
);
594 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
596 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
597 $firstField = format_string($courses[$log->course
], true, array('context' => $coursecontext));
598 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
599 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
600 $text = implode("\t", $row);
607 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
608 $modid, $modaction, $groupid) {
612 require_once("$CFG->libdir/excellib.class.php");
614 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
615 $modname, $modid, $modaction, $groupid)) {
621 if ($course->id
== SITEID
) {
623 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
624 foreach ($ccc as $cc) {
625 $courses[$cc->id
] = $cc->shortname
;
629 $courses[$course->id
] = $course->shortname
;
634 $tt = getdate(time());
635 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
637 $strftimedatetime = get_string("strftimedatetime");
639 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
640 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
643 $workbook = new MoodleExcelWorkbook('-');
644 $workbook->send($filename);
646 $worksheet = array();
647 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
648 get_string('fullnameuser'), get_string('action'), get_string('info'));
650 // Creating worksheets
651 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
652 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
653 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
654 $worksheet[$wsnumber]->set_column(1, 1, 30);
655 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
656 userdate(time(), $strftimedatetime));
658 foreach ($headers as $item) {
659 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
664 if (empty($logs['logs'])) {
669 $formatDate =& $workbook->add_format();
670 $formatDate->set_num_format(get_string('log_excel_date_format'));
672 $row = FIRSTUSEDEXCELROW
;
674 $myxls =& $worksheet[$wsnumber];
675 foreach ($logs['logs'] as $log) {
676 if (isset($ldcache[$log->module
][$log->action
])) {
677 $ld = $ldcache[$log->module
][$log->action
];
679 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
680 $ldcache[$log->module
][$log->action
] = $ld;
682 if ($ld && !empty($log->info
)) {
683 // ugly hack to make sure fullname is shown correctly
684 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
685 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
687 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
692 $log->info
= format_string($log->info
);
693 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
696 if ($row > EXCELROWS
) {
698 $myxls =& $worksheet[$wsnumber];
699 $row = FIRSTUSEDEXCELROW
;
703 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
705 $myxls->write($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)), '');
706 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
707 $myxls->write($row, 2, $log->ip
, '');
708 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
709 $myxls->write($row, 3, $fullname, '');
710 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
711 $myxls->write($row, 5, $log->info
, '');
720 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
721 $modid, $modaction, $groupid) {
725 require_once("$CFG->libdir/odslib.class.php");
727 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
728 $modname, $modid, $modaction, $groupid)) {
734 if ($course->id
== SITEID
) {
736 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
737 foreach ($ccc as $cc) {
738 $courses[$cc->id
] = $cc->shortname
;
742 $courses[$course->id
] = $course->shortname
;
747 $tt = getdate(time());
748 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
750 $strftimedatetime = get_string("strftimedatetime");
752 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
753 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
756 $workbook = new MoodleODSWorkbook('-');
757 $workbook->send($filename);
759 $worksheet = array();
760 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
761 get_string('fullnameuser'), get_string('action'), get_string('info'));
763 // Creating worksheets
764 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
765 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
766 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
767 $worksheet[$wsnumber]->set_column(1, 1, 30);
768 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
769 userdate(time(), $strftimedatetime));
771 foreach ($headers as $item) {
772 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
777 if (empty($logs['logs'])) {
782 $formatDate =& $workbook->add_format();
783 $formatDate->set_num_format(get_string('log_excel_date_format'));
785 $row = FIRSTUSEDEXCELROW
;
787 $myxls =& $worksheet[$wsnumber];
788 foreach ($logs['logs'] as $log) {
789 if (isset($ldcache[$log->module
][$log->action
])) {
790 $ld = $ldcache[$log->module
][$log->action
];
792 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
793 $ldcache[$log->module
][$log->action
] = $ld;
795 if ($ld && !empty($log->info
)) {
796 // ugly hack to make sure fullname is shown correctly
797 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
798 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
800 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
805 $log->info
= format_string($log->info
);
806 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
809 if ($row > EXCELROWS
) {
811 $myxls =& $worksheet[$wsnumber];
812 $row = FIRSTUSEDEXCELROW
;
816 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
818 $myxls->write_string($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)));
819 $myxls->write_date($row, 1, $log->time
);
820 $myxls->write_string($row, 2, $log->ip
);
821 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
822 $myxls->write_string($row, 3, $fullname);
823 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
824 $myxls->write_string($row, 5, $log->info
);
834 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
836 if (empty($CFG->gdversion
)) {
837 echo "(".get_string("gdneed").")";
839 // MDL-10818, do not display broken graph when user has no permission to view graph
840 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
841 ($course->showreports
and $USER->id
== $userid)) {
842 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
843 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
849 function print_overview($courses, array $remote_courses=array()) {
850 global $CFG, $USER, $DB, $OUTPUT;
852 $htmlarray = array();
853 if ($modules = $DB->get_records('modules')) {
854 foreach ($modules as $mod) {
855 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
856 include_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
857 $fname = $mod->name
.'_print_overview';
858 if (function_exists($fname)) {
859 $fname($courses,$htmlarray);
864 foreach ($courses as $course) {
865 $fullname = format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
866 echo $OUTPUT->box_start('coursebox');
867 $attributes = array('title' => s($fullname));
868 if (empty($course->visible
)) {
869 $attributes['class'] = 'dimmed';
871 echo $OUTPUT->heading(html_writer
::link(
872 new moodle_url('/course/view.php', array('id' => $course->id
)), $fullname, $attributes), 3);
873 if (array_key_exists($course->id
,$htmlarray)) {
874 foreach ($htmlarray[$course->id
] as $modname => $html) {
878 echo $OUTPUT->box_end();
881 if (!empty($remote_courses)) {
882 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
884 foreach ($remote_courses as $course) {
885 echo $OUTPUT->box_start('coursebox');
886 $attributes = array('title' => s($course->fullname
));
887 echo $OUTPUT->heading(html_writer
::link(
888 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid
, 'wantsurl' => '/course/view.php?id='.$course->remoteid
)),
889 format_string($course->shortname
),
890 $attributes) . ' (' . format_string($course->hostname
) . ')', 3);
891 echo $OUTPUT->box_end();
897 * This function trawls through the logs looking for
898 * anything new since the user's last login
900 function print_recent_activity($course) {
901 // $course is an object
902 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
904 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
906 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
908 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD
, -2); // better db caching for guests - 100 seconds
910 if (!isguestuser()) {
911 if (!empty($USER->lastcourseaccess
[$course->id
])) {
912 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
913 $timestart = $USER->lastcourseaccess
[$course->id
];
918 echo '<div class="activitydate">';
919 echo get_string('activitysince', '', userdate($timestart));
921 echo '<div class="activityhead">';
923 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
929 /// Firstly, have there been any new enrolments?
931 $users = get_recent_enrolments($course->id
, $timestart);
933 //Accessibility: new users now appear in an <OL> list.
935 echo '<div class="newusers">';
936 echo $OUTPUT->heading(get_string("newusers").':', 3);
938 echo "<ol class=\"list\">\n";
939 foreach ($users as $user) {
940 $fullname = fullname($user, $viewfullnames);
941 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
943 echo "</ol>\n</div>\n";
946 /// Next, have there been any modifications to the course structure?
948 $modinfo =& get_fast_modinfo($course);
950 $changelist = array();
952 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
953 module = 'course' AND
954 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
955 array($timestart, $course->id
), "id ASC");
958 $actions = array('add mod', 'update mod', 'delete mod');
959 $newgones = array(); // added and later deleted items
960 foreach ($logs as $key => $log) {
961 if (!in_array($log->action
, $actions)) {
964 $info = explode(' ', $log->info
);
966 // note: in most cases I replaced hardcoding of label with use of
967 // $cm->has_view() but it was not possible to do this here because
968 // we don't necessarily have the $cm for it
969 if ($info[0] == 'label') { // Labels are ignored in recent activity
973 if (count($info) != 2) {
974 debugging("Incorrect log entry info: id = ".$log->id
, DEBUG_DEVELOPER
);
979 $instanceid = $info[1];
981 if ($log->action
== 'delete mod') {
982 // unfortunately we do not know if the mod was visible
983 if (!array_key_exists($log->info
, $newgones)) {
984 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
985 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
988 if (!isset($modinfo->instances
[$modname][$instanceid])) {
989 if ($log->action
== 'add mod') {
990 // do not display added and later deleted activities
991 $newgones[$log->info
] = true;
995 $cm = $modinfo->instances
[$modname][$instanceid];
996 if (!$cm->uservisible
) {
1000 if ($log->action
== 'add mod') {
1001 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1002 $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>");
1004 } else if ($log->action
== 'update mod' and empty($changelist[$log->info
])) {
1005 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1006 $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>");
1012 if (!empty($changelist)) {
1013 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1015 foreach ($changelist as $changeinfo => $change) {
1016 echo '<p class="activity">'.$change['text'].'</p>';
1020 /// Now display new things from each module
1022 $usedmodules = array();
1023 foreach($modinfo->cms
as $cm) {
1024 if (isset($usedmodules[$cm->modname
])) {
1027 if (!$cm->uservisible
) {
1030 $usedmodules[$cm->modname
] = $cm->modname
;
1033 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1034 if (file_exists($CFG->dirroot
.'/mod/'.$modname.'/lib.php')) {
1035 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
1036 $print_recent_activity = $modname.'_print_recent_activity';
1037 if (function_exists($print_recent_activity)) {
1038 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1039 $content = $print_recent_activity($course, $viewfullnames, $timestart) ||
$content;
1042 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1047 echo '<p class="message">'.get_string('nothingnew').'</p>';
1052 * For a given course, returns an array of course activity objects
1053 * Each item in the array contains he following properties:
1055 function get_array_of_activities($courseid) {
1056 // cm - course module id
1057 // mod - name of the module (eg forum)
1058 // section - the number of the section (eg week or topic)
1059 // name - the name of the instance
1060 // visible - is the instance visible or not
1061 // groupingid - grouping id
1062 // groupmembersonly - is this instance visible to group members only
1063 // extra - contains extra string to include in any link
1065 if(!empty($CFG->enableavailability
)) {
1066 require_once($CFG->libdir
.'/conditionlib.php');
1069 $course = $DB->get_record('course', array('id'=>$courseid));
1071 if (empty($course)) {
1072 throw new moodle_exception('courseidnotfound');
1077 $rawmods = get_course_mods($courseid);
1078 if (empty($rawmods)) {
1079 return $mod; // always return array
1082 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1083 foreach ($sections as $section) {
1084 if (!empty($section->sequence
)) {
1085 $sequence = explode(",", $section->sequence
);
1086 foreach ($sequence as $seq) {
1087 if (empty($rawmods[$seq])) {
1090 $mod[$seq] = new stdClass();
1091 $mod[$seq]->id
= $rawmods[$seq]->instance
;
1092 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1093 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1095 // Oh dear. Inconsistent names left here for backward compatibility.
1096 $mod[$seq]->section
= $section->section
;
1097 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
1099 $mod[$seq]->module
= $rawmods[$seq]->module
;
1100 $mod[$seq]->added
= $rawmods[$seq]->added
;
1101 $mod[$seq]->score
= $rawmods[$seq]->score
;
1102 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
1103 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1104 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
1105 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
1106 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
1107 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
1108 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
1109 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
1110 $mod[$seq]->extra
= "";
1111 $mod[$seq]->completiongradeitemnumber
=
1112 $rawmods[$seq]->completiongradeitemnumber
;
1113 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
1114 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
1115 $mod[$seq]->availablefrom
= $rawmods[$seq]->availablefrom
;
1116 $mod[$seq]->availableuntil
= $rawmods[$seq]->availableuntil
;
1117 $mod[$seq]->showavailability
= $rawmods[$seq]->showavailability
;
1118 if (!empty($CFG->enableavailability
)) {
1119 condition_info
::fill_availability_conditions($rawmods[$seq]);
1120 $mod[$seq]->conditionscompletion
= $rawmods[$seq]->conditionscompletion
;
1121 $mod[$seq]->conditionsgrade
= $rawmods[$seq]->conditionsgrade
;
1124 $modname = $mod[$seq]->mod
;
1125 $functionname = $modname."_get_coursemodule_info";
1127 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1131 include_once("$CFG->dirroot/mod/$modname/lib.php");
1133 if (function_exists($functionname)) {
1134 if ($info = $functionname($rawmods[$seq])) {
1135 if (!empty($info->icon
)) {
1136 $mod[$seq]->icon
= $info->icon
;
1138 if (!empty($info->iconcomponent
)) {
1139 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
1141 if (!empty($info->name
)) {
1142 $mod[$seq]->name
= $info->name
;
1144 if ($info instanceof cached_cm_info
) {
1145 // When using cached_cm_info you can include three new fields
1146 // that aren't available for legacy code
1147 if (!empty($info->content
)) {
1148 $mod[$seq]->content
= $info->content
;
1150 if (!empty($info->extraclasses
)) {
1151 $mod[$seq]->extraclasses
= $info->extraclasses
;
1153 if (!empty($info->onclick
)) {
1154 $mod[$seq]->onclick
= $info->onclick
;
1156 if (!empty($info->customdata
)) {
1157 $mod[$seq]->customdata
= $info->customdata
;
1160 // When using a stdclass, the (horrible) deprecated ->extra field
1161 // is available for BC
1162 if (!empty($info->extra
)) {
1163 $mod[$seq]->extra
= $info->extra
;
1168 if (!isset($mod[$seq]->name
)) {
1169 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
1172 // Minimise the database size by unsetting default options when they are
1173 // 'empty'. This list corresponds to code in the cm_info constructor.
1174 foreach(array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1175 'indent', 'completion', 'extra', 'extraclasses', 'onclick', 'content',
1176 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1177 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1178 'completionview', 'completionexpected', 'score') as $property) {
1179 if (property_exists($mod[$seq], $property) &&
1180 empty($mod[$seq]->{$property})) {
1181 unset($mod[$seq]->{$property});
1184 // Special case: this value is usually set to null, but may be 0
1185 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1186 is_null($mod[$seq]->completiongradeitemnumber
)) {
1187 unset($mod[$seq]->completiongradeitemnumber
);
1198 * Returns a number of useful structures for course displays
1200 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1201 global $CFG, $DB, $COURSE;
1203 $mods = array(); // course modules indexed by id
1204 $modnames = array(); // all course module names (except resource!)
1205 $modnamesplural= array(); // all course module names (plural form)
1206 $modnamesused = array(); // course module names used
1208 if ($allmods = $DB->get_records("modules")) {
1209 foreach ($allmods as $mod) {
1210 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1213 if ($mod->visible
) {
1214 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1215 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1218 textlib_get_instance()->asort($modnames);
1220 print_error("nomodules", 'debug');
1223 $course = ($courseid==$COURSE->id
) ?
$COURSE : $DB->get_record('course',array('id'=>$courseid));
1224 $modinfo = get_fast_modinfo($course);
1226 if ($rawmods=$modinfo->cms
) {
1227 foreach($rawmods as $mod) { // Index the mods
1228 if (empty($modnames[$mod->modname
])) {
1231 $mods[$mod->id
] = $mod;
1232 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1233 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1237 if (!groups_course_module_visible($mod)) {
1240 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1242 if ($modnamesused) {
1243 textlib_get_instance()->asort($modnamesused);
1249 * Returns an array of sections for the requested course id
1251 * This function stores the sections against the course id within a staticvar encase
1252 * of subsequent requests. This is used all over + in some standard libs and course
1253 * format callbacks so subsequent requests are a reality.
1255 * @staticvar array $coursesections
1256 * @param int $courseid
1257 * @return array Array of sections
1259 function get_all_sections($courseid) {
1261 static $coursesections = array();
1262 if (!array_key_exists($courseid, $coursesections)) {
1263 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1264 "section, id, course, name, summary, summaryformat, sequence, visible");
1266 return $coursesections[$courseid];
1270 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1271 * It also sets the $USER->display cache to array($courseid=>return value)
1273 * @param int $courseid The course id
1274 * @return int Course section to display, 0 means all
1276 function course_get_display($courseid) {
1279 if (!isloggedin() or isguestuser()) {
1280 //do not get settings in db for guests
1281 return 0; //return the implicit setting
1284 if (!isset($USER->display
[$courseid])) {
1285 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id
, 'course'=>$courseid))) {
1286 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1288 //use display cache for one course only - we need to keep session small
1289 $USER->display
= array($courseid => $display);
1292 return $USER->display
[$courseid];
1296 * Show one section only or all sections.
1298 * @param int $courseid The course id
1299 * @param mixed $display show only this section, 0 or 'all' means show all sections
1300 * @return int Course section to display, 0 means all
1302 function course_set_display($courseid, $display) {
1305 if ($display === 'all' or empty($display)) {
1309 if (!isloggedin() or isguestuser()) {
1310 //do not store settings in db for guests
1314 if ($display == 0) {
1315 //show all, do not store anything in database
1316 $DB->delete_records('course_display', array('userid' => $USER->id
, 'course' => $courseid));
1319 if ($DB->record_exists('course_display', array('userid' => $USER->id
, 'course' => $courseid))) {
1320 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id
, 'course' => $courseid));
1322 $record = new stdClass();
1323 $record->userid
= $USER->id
;
1324 $record->course
= $courseid;
1325 $record->display
= $display;
1326 $DB->insert_record('course_display', $record);
1330 //use display cache for one course only - we need to keep session small
1331 $USER->display
= array($courseid => $display);
1337 * Set highlighted section. Only one section can be highlighted at the time.
1339 * @param int $courseid course id
1340 * @param int $marker highlight section with this number, 0 means remove higlightin
1343 function course_set_marker($courseid, $marker) {
1345 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1349 * For a given course section, marks it visible or hidden,
1350 * and does the same for every activity in that section
1352 function set_section_visible($courseid, $sectionnumber, $visibility) {
1355 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1356 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1357 if (!empty($section->sequence
)) {
1358 $modules = explode(",", $section->sequence
);
1359 foreach ($modules as $moduleid) {
1360 set_coursemodule_visible($moduleid, $visibility, true);
1363 rebuild_course_cache($courseid);
1368 * Obtains shared data that is used in print_section when displaying a
1369 * course-module entry.
1371 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1373 * This data is also used in other areas of the code.
1374 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1375 * @param object $course Moodle course object
1376 * @return array An array with the following values in this order:
1377 * $content (optional extra content for after link),
1378 * $instancename (text of link)
1380 function get_print_section_cm_text(cm_info
$cm, $course) {
1383 // Get course context
1384 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1386 // Get content from modinfo if specified. Content displays either
1387 // in addition to the standard link (below), or replaces it if
1388 // the link is turned off by setting ->url to null.
1389 if (($content = $cm->get_content()) !== '') {
1390 $labelformatoptions = new stdClass();
1391 $labelformatoptions->noclean
= true;
1392 $labelformatoptions->overflowdiv
= true;
1393 $labelformatoptions->context
= $coursecontext;
1394 $content = format_text($content, FORMAT_HTML
, $labelformatoptions);
1399 $stringoptions = new stdClass
;
1400 $stringoptions->context
= $coursecontext;
1401 $instancename = format_string($cm->name
, true, $stringoptions);
1402 return array($content, $instancename);
1406 * Prints a section full of activity modules
1408 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1409 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1411 static $initialised;
1413 static $groupbuttons;
1414 static $groupbuttonslink;
1417 static $strmovehere;
1418 static $strmovefull;
1419 static $strunreadpostsone;
1421 static $modulenames;
1423 if (!isset($initialised)) {
1424 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1425 $groupbuttonslink = (!$course->groupmodeforce
);
1426 $isediting = $PAGE->user_is_editing();
1427 $ismoving = $isediting && ismoving($course->id
);
1429 $strmovehere = get_string("movehere");
1430 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1432 $modulenames = array();
1433 $initialised = true;
1436 $tl = textlib_get_instance();
1438 $modinfo = get_fast_modinfo($course);
1439 $completioninfo = new completion_info($course);
1441 //Accessibility: replace table with list <ul>, but don't output empty list.
1442 if (!empty($section->sequence
)) {
1444 // Fix bug #5027, don't want style=\"width:$width\".
1445 echo "<ul class=\"section img-text\">\n";
1446 $sectionmods = explode(",", $section->sequence
);
1448 foreach ($sectionmods as $modnumber) {
1449 if (empty($mods[$modnumber])) {
1456 $mod = $mods[$modnumber];
1458 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1459 // do not display moving mod
1463 if (isset($modinfo->cms
[$modnumber])) {
1464 // We can continue (because it will not be displayed at all)
1466 // 1) The activity is not visible to users
1468 // 2a) The 'showavailability' option is not set (if that is set,
1469 // we need to display the activity so we can show
1470 // availability info)
1472 // 2b) The 'availableinfo' is empty, i.e. the activity was
1473 // hidden in a way that leaves no info, such as using the
1475 if (!$modinfo->cms
[$modnumber]->uservisible
&&
1476 (empty($modinfo->cms
[$modnumber]->showavailability
) ||
1477 empty($modinfo->cms
[$modnumber]->availableinfo
))) {
1478 // visibility shortcut
1482 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1483 // module not installed
1486 if (!coursemodule_visible_for_user($mod) &&
1487 empty($mod->showavailability
)) {
1488 // full visibility check
1493 if (!isset($modulenames[$mod->modname
])) {
1494 $modulenames[$mod->modname
] = get_string('modulename', $mod->modname
);
1496 $modulename = $modulenames[$mod->modname
];
1498 // In some cases the activity is visible to user, but it is
1499 // dimmed. This is done if viewhiddenactivities is true and if:
1500 // 1. the activity is not visible, or
1501 // 2. the activity has dates set which do not include current, or
1502 // 3. the activity has any other conditions set (regardless of whether
1503 // current user meets them)
1504 $canviewhidden = has_capability(
1505 'moodle/course:viewhiddenactivities',
1506 get_context_instance(CONTEXT_MODULE
, $mod->id
));
1507 $accessiblebutdim = false;
1508 if ($canviewhidden) {
1509 $accessiblebutdim = !$mod->visible
;
1510 if (!empty($CFG->enableavailability
)) {
1511 $accessiblebutdim = $accessiblebutdim ||
1512 $mod->availablefrom
> time() ||
1513 ($mod->availableuntil
&& $mod->availableuntil
< time()) ||
1514 count($mod->conditionsgrade
) > 0 ||
1515 count($mod->conditionscompletion
) > 0;
1519 $liclasses = array();
1520 $liclasses[] = 'activity';
1521 $liclasses[] = $mod->modname
;
1522 $liclasses[] = 'modtype_'.$mod->modname
;
1523 $extraclasses = $mod->get_extra_classes();
1524 if ($extraclasses) {
1525 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1527 echo html_writer
::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1529 echo '<a title="'.$strmovefull.'"'.
1530 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.sesskey().'">'.
1531 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1532 ' alt="'.$strmovehere.'" /></a><br />
1536 $classes = array('mod-indent');
1537 if (!empty($mod->indent
)) {
1538 $classes[] = 'mod-indent-'.$mod->indent
;
1539 if ($mod->indent
> 15) {
1540 $classes[] = 'mod-indent-huge';
1543 echo html_writer
::start_tag('div', array('class'=>join(' ', $classes)));
1545 // Get data about this course-module
1546 list($content, $instancename) =
1547 get_print_section_cm_text($modinfo->cms
[$modnumber], $course);
1549 //Accessibility: for files get description via icon, this is very ugly hack!
1551 $altname = $mod->modfullname
;
1552 if (!empty($customicon)) {
1553 $archetype = plugin_supports('mod', $mod->modname
, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1554 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1555 $mimetype = mimeinfo_from_icon('type', $customicon);
1556 $altname = get_mimetype_description($mimetype);
1559 // Avoid unnecessary duplication: if e.g. a forum name already
1560 // includes the word forum (or Forum, etc) then it is unhelpful
1561 // to include that in the accessible description that is added.
1562 if (false !== strpos($tl->strtolower($instancename),
1563 $tl->strtolower($altname))) {
1566 // File type after name, for alphabetic lists (screen reader).
1568 $altname = get_accesshide(' '.$altname);
1571 // We may be displaying this just in order to show information
1572 // about visibility, without the actual link
1574 if ($mod->uservisible
) {
1575 // Nope - in this case the link is fully working for user
1578 if ($accessiblebutdim) {
1579 $linkclasses .= ' dimmed';
1580 $textclasses .= ' dimmed_text';
1581 $accesstext = '<span class="accesshide">'.
1582 get_string('hiddenfromstudents').': </span>';
1587 $linkcss = 'class="' . trim($linkclasses) . '" ';
1592 $textcss = 'class="' . trim($textclasses) . '" ';
1597 // Get on-click attribute value if specified
1598 $onclick = $mod->get_on_click();
1600 $onclick = ' onclick="' . $onclick . '"';
1603 if ($url = $mod->get_url()) {
1604 // Display link itself
1605 echo '<a ' . $linkcss . $mod->extra
. $onclick .
1606 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1607 '" class="activityicon" alt="' .
1608 $modulename . '" /> ' .
1609 $accesstext . '<span class="instancename">' .
1610 $instancename . $altname . '</span></a>';
1612 // If specified, display extra content after link
1614 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1615 '">' . $content . '</div>';
1618 // No link, so display only content
1619 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1620 $accesstext . $content . '</div>';
1623 if (!empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1624 if (!isset($groupings)) {
1625 $groupings = groups_get_all_groupings($course->id
);
1627 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1630 $textclasses = $extraclasses;
1631 $textclasses .= ' dimmed_text';
1633 $textcss = 'class="' . trim($textclasses) . '" ';
1637 $accesstext = '<span class="accesshide">' .
1638 get_string('notavailableyet', 'condition') .
1641 if ($url = $mod->get_url()) {
1642 // Display greyed-out text of link
1643 echo '<div ' . $textcss . $mod->extra
.
1644 ' >' . '<img src="' . $mod->get_icon_url() .
1645 '" class="activityicon" alt="' .
1647 '" /> <span>'. $instancename . $altname .
1650 // Do not display content after link when it is greyed out like this.
1652 // No link, so display only content (also greyed)
1653 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1654 $accesstext . $content . '</div>';
1658 // Module can put text after the link (e.g. forum unread)
1659 echo $mod->get_after_link();
1661 // If there is content but NO link (eg label), then display the
1662 // content here (BEFORE any icons). In this case cons must be
1663 // displayed after the content so that it makes more sense visually
1664 // and for accessibility reasons, e.g. if you have a one-line label
1665 // it should work similarly (at least in terms of ordering) to an
1672 if ($groupbuttons and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
1673 if (! $mod->groupmodelink
= $groupbuttonslink) {
1674 $mod->groupmode
= $course->groupmode
;
1678 $mod->groupmode
= false;
1680 echo ' ';
1681 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1682 echo $mod->get_after_edit_icons();
1686 $completion = $hidecompletion
1687 ? COMPLETION_TRACKING_NONE
1688 : $completioninfo->is_enabled($mod);
1689 if ($completion!=COMPLETION_TRACKING_NONE
&& isloggedin() &&
1690 !isguestuser() && $mod->uservisible
) {
1691 $completiondata = $completioninfo->get_data($mod,true);
1692 $completionicon = '';
1694 switch ($completion) {
1695 case COMPLETION_TRACKING_MANUAL
:
1696 $completionicon = 'manual-enabled'; break;
1697 case COMPLETION_TRACKING_AUTOMATIC
:
1698 $completionicon = 'auto-enabled'; break;
1701 } else if ($completion==COMPLETION_TRACKING_MANUAL
) {
1702 switch($completiondata->completionstate
) {
1703 case COMPLETION_INCOMPLETE
:
1704 $completionicon = 'manual-n'; break;
1705 case COMPLETION_COMPLETE
:
1706 $completionicon = 'manual-y'; break;
1708 } else { // Automatic
1709 switch($completiondata->completionstate
) {
1710 case COMPLETION_INCOMPLETE
:
1711 $completionicon = 'auto-n'; break;
1712 case COMPLETION_COMPLETE
:
1713 $completionicon = 'auto-y'; break;
1714 case COMPLETION_COMPLETE_PASS
:
1715 $completionicon = 'auto-pass'; break;
1716 case COMPLETION_COMPLETE_FAIL
:
1717 $completionicon = 'auto-fail'; break;
1720 if ($completionicon) {
1721 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1722 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion', $mod->name
));
1723 if ($completion == COMPLETION_TRACKING_MANUAL
&& !$isediting) {
1724 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion', $mod->name
));
1726 $completiondata->completionstate
==COMPLETION_COMPLETE
1727 ? COMPLETION_INCOMPLETE
1728 : COMPLETION_COMPLETE
;
1729 // In manual mode the icon is a toggle form...
1731 // If this completion state is used by the
1732 // conditional activities system, we need to turn
1734 if (!empty($CFG->enableavailability
) &&
1735 condition_info
::completion_value_used_as_condition($course, $mod)) {
1736 $extraclass = ' preventjs';
1741 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot
."/course/togglecompletion.php'><div>
1742 <input type='hidden' name='id' value='{$mod->id}' />
1743 <input type='hidden' name='modulename' value='".s($mod->name
)."' />
1744 <input type='hidden' name='sesskey' value='".sesskey()."' />
1745 <input type='hidden' name='completionstate' value='$newstate' />
1746 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1749 // In auto mode, or when editing, the icon is just an image
1750 echo "<span class='autocompletion'>";
1751 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1756 // If there is content AND a link, then display the content here
1757 // (AFTER any icons). Otherwise it was displayed before
1762 // Show availability information (for someone who isn't allowed to
1763 // see the activity itself, or for staff)
1764 if (!$mod->uservisible
) {
1765 echo '<div class="availabilityinfo">'.$mod->availableinfo
.'</div>';
1766 } else if ($canviewhidden && !empty($CFG->enableavailability
)) {
1767 $ci = new condition_info($mod);
1768 $fullinfo = $ci->get_full_information();
1770 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1771 ?
'userrestriction_visible'
1772 : 'userrestriction_hidden','condition',
1773 $fullinfo).'</div>';
1777 echo html_writer
::end_tag('div');
1778 echo html_writer
::end_tag('li')."\n";
1781 } elseif ($ismoving) {
1782 echo "<ul class=\"section\">\n";
1786 echo '<li><a title="'.$strmovefull.'"'.
1787 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.sesskey().'">'.
1788 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1789 ' alt="'.$strmovehere.'" /></a></li>
1792 if (!empty($section->sequence
) ||
$ismoving) {
1793 echo "</ul><!--class='section'-->\n\n";
1798 * Prints the menus to add activities and resources.
1800 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1801 global $CFG, $OUTPUT;
1803 // check to see if user can add menus
1804 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1808 $urlbase = "/course/mod.php?id=$course->id§ion=$section&sesskey=".sesskey().'&add=';
1810 $resources = array();
1811 $activities = array();
1813 foreach($modnames as $modname=>$modnamestr) {
1814 if (!course_allowed_module($course, $modname)) {
1818 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1819 if (!file_exists($libfile)) {
1822 include_once($libfile);
1823 $gettypesfunc = $modname.'_get_types';
1824 if (function_exists($gettypesfunc)) {
1825 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1826 if ($types = $gettypesfunc()) {
1830 foreach($types as $type) {
1831 if ($type->typestr
=== '--') {
1834 if (strpos($type->typestr
, '--') === 0) {
1835 $groupname = str_replace('--', '', $type->typestr
);
1838 $type->type
= str_replace('&', '&', $type->type
);
1839 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1840 $atype = MOD_CLASS_RESOURCE
;
1842 $menu[$urlbase.$type->type
] = $type->typestr
;
1844 if (!is_null($groupname)) {
1845 if ($atype == MOD_CLASS_RESOURCE
) {
1846 $resources[] = array($groupname=>$menu);
1848 $activities[] = array($groupname=>$menu);
1851 if ($atype == MOD_CLASS_RESOURCE
) {
1852 $resources = array_merge($resources, $menu);
1854 $activities = array_merge($activities, $menu);
1859 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1860 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1861 $resources[$urlbase.$modname] = $modnamestr;
1863 // all other archetypes are considered activity
1864 $activities[$urlbase.$modname] = $modnamestr;
1869 $straddactivity = get_string('addactivity');
1870 $straddresource = get_string('addresource');
1872 $output = '<div class="section_add_menus">';
1875 $output .= '<div class="horizontal">';
1878 if (!empty($resources)) {
1879 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1880 $select->set_help_icon('resources');
1881 $output .= $OUTPUT->render($select);
1884 if (!empty($activities)) {
1885 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1886 $select->set_help_icon('activities');
1887 $output .= $OUTPUT->render($select);
1891 $output .= '</div>';
1894 $output .= '</div>';
1904 * Return the course category context for the category with id $categoryid, except
1905 * that if $categoryid is 0, return the system context.
1907 * @param integer $categoryid a category id or 0.
1908 * @return object the corresponding context
1910 function get_category_or_system_context($categoryid) {
1912 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1914 return get_context_instance(CONTEXT_SYSTEM
);
1919 * Gets the child categories of a given courses category. Uses a static cache
1920 * to make repeat calls efficient.
1922 * @param int $parentid the id of a course category.
1923 * @return array all the child course categories.
1925 function get_child_categories($parentid) {
1926 static $allcategories = null;
1928 // only fill in this variable the first time
1929 if (null == $allcategories) {
1930 $allcategories = array();
1932 $categories = get_categories();
1933 foreach ($categories as $category) {
1934 if (empty($allcategories[$category->parent
])) {
1935 $allcategories[$category->parent
] = array();
1937 $allcategories[$category->parent
][] = $category;
1941 if (empty($allcategories[$parentid])) {
1944 return $allcategories[$parentid];
1949 * This function recursively travels the categories, building up a nice list
1950 * for display. It also makes an array that list all the parents for each
1953 * For example, if you have a tree of categories like:
1954 * Miscellaneous (id = 1)
1955 * Subcategory (id = 2)
1956 * Sub-subcategory (id = 4)
1957 * Other category (id = 3)
1958 * Then after calling this function you will have
1959 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1960 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1961 * 3 => 'Other category');
1962 * $parents = array(2 => array(1), 4 => array(1, 2));
1964 * If you specify $requiredcapability, then only categories where the current
1965 * user has that capability will be added to $list, although all categories
1966 * will still be added to $parents, and if you only have $requiredcapability
1967 * in a child category, not the parent, then the child catgegory will still be
1970 * If you specify the option $excluded, then that category, and all its children,
1971 * are omitted from the tree. This is useful when you are doing something like
1972 * moving categories, where you do not want to allow people to move a category
1973 * to be the child of itself.
1975 * @param array $list For output, accumulates an array categoryid => full category path name
1976 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1977 * @param string/array $requiredcapability if given, only categories where the current
1978 * user has this capability will be added to $list. Can also be an array of capabilities,
1979 * in which case they are all required.
1980 * @param integer $excludeid Omit this category and its children from the lists built.
1981 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1982 * @param string $path For internal use, as part of recursive calls.
1984 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1985 $excludeid = 0, $category = NULL, $path = "") {
1987 // initialize the arrays if needed
1988 if (!is_array($list)) {
1991 if (!is_array($parents)) {
1995 if (empty($category)) {
1996 // Start at the top level.
1997 $category = new stdClass
;
2000 // This is the excluded category, don't include it.
2001 if ($excludeid > 0 && $excludeid == $category->id
) {
2005 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2006 $categoryname = format_string($category->name
, true, array('context' => $context));
2010 $path = $path.' / '.$categoryname;
2012 $path = $categoryname;
2015 // Add this category to $list, if the permissions check out.
2016 if (empty($requiredcapability)) {
2017 $list[$category->id
] = $path;
2020 $requiredcapability = (array)$requiredcapability;
2021 if (has_all_capabilities($requiredcapability, $context)) {
2022 $list[$category->id
] = $path;
2027 // Add all the children recursively, while updating the parents array.
2028 if ($categories = get_child_categories($category->id
)) {
2029 foreach ($categories as $cat) {
2030 if (!empty($category->id
)) {
2031 if (isset($parents[$category->id
])) {
2032 $parents[$cat->id
] = $parents[$category->id
];
2034 $parents[$cat->id
][] = $category->id
;
2036 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2042 * This function generates a structured array of courses and categories.
2044 * The depth of categories is limited by $CFG->maxcategorydepth however there
2045 * is no limit on the number of courses!
2047 * Suitable for use with the course renderers course_category_tree method:
2048 * $renderer = $PAGE->get_renderer('core','course');
2049 * echo $renderer->course_category_tree(get_course_category_tree());
2051 * @global moodle_database $DB
2055 function get_course_category_tree($id = 0, $depth = 0) {
2057 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
));
2058 $categories = get_child_categories($id);
2059 $categoryids = array();
2060 foreach ($categories as $key => &$category) {
2061 if (!$category->visible
&& !$viewhiddencats) {
2062 unset($categories[$key]);
2065 $categoryids[$category->id
] = $category;
2066 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
2067 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
2068 foreach ($subcategories as $subid=>$subcat) {
2069 $categoryids[$subid] = $subcat;
2071 $category->courses
= array();
2076 // This is a recursive call so return the required array
2077 return array($categories, $categoryids);
2080 // The depth is 0 this function has just been called so we can finish it off
2082 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
2083 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2085 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2089 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2090 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2091 // loop throught them
2092 foreach ($courses as $course) {
2093 if ($course->id
== SITEID
) {
2096 context_instance_preload($course);
2097 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
2098 $categoryids[$course->category
]->courses
[$course->id
] = $course;
2106 * Recursive function to print out all the categories in a nice format
2107 * with or without courses included
2109 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2112 // maxcategorydepth == 0 meant no limit
2113 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
2117 if (!$displaylist) {
2118 make_categories_list($displaylist, $parentslist);
2122 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
2123 print_category_info($category, $depth, $showcourses);
2125 return; // Don't bother printing children of invisible categories
2129 $category = new stdClass();
2130 $category->id
= "0";
2133 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
2134 $countcats = count($categories);
2138 foreach ($categories as $cat) {
2140 if ($count == $countcats) {
2143 $up = $first ?
false : true;
2144 $down = $last ?
false : true;
2147 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
2153 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2155 function make_categories_options() {
2156 make_categories_list($cats,$parents);
2157 foreach ($cats as $key => $value) {
2158 if (array_key_exists($key,$parents)) {
2159 if ($indent = count($parents[$key])) {
2160 for ($i = 0; $i < $indent; $i++
) {
2161 $cats[$key] = ' '.$cats[$key];
2170 * Prints the category info in indented fashion
2171 * This function is only used by print_whole_category_list() above
2173 function print_category_info($category, $depth=0, $showcourses = false) {
2174 global $CFG, $DB, $OUTPUT;
2176 $strsummary = get_string('summary');
2179 if (!$category->visible
) {
2180 $catlinkcss = array('class'=>'dimmed');
2182 static $coursecount = null;
2183 if (null === $coursecount) {
2184 // only need to check this once
2185 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
2188 if ($showcourses and $coursecount) {
2189 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2191 $catimage = " ";
2194 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2195 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2196 $fullname = format_string($category->name
, true, array('context' => $context));
2198 if ($showcourses and $coursecount) {
2199 echo '<div class="categorylist clearfix">';
2201 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
2202 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2203 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
2207 for ($i=0; $i< $depth; $i++
) {
2208 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
2214 echo html_writer
::tag('div', $html, array('class'=>'category'));
2215 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2217 // does the depth exceed maxcategorydepth
2218 // maxcategorydepth == 0 or unset meant no limit
2219 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
2220 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
2221 foreach ($courses as $course) {
2223 if (!$course->visible
) {
2224 $linkcss = array('class'=>'dimmed');
2227 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($course->fullname
), $linkcss);
2231 if ($icons = enrol_get_course_info_icons($course)) {
2232 foreach ($icons as $pix_icon) {
2233 $courseicon = $OUTPUT->render($pix_icon).' ';
2237 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
2239 if ($course->summary
) {
2240 $link = new moodle_url('/course/info.php?id='.$course->id
);
2241 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2242 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2243 array('title'=>$strsummary));
2245 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
2249 for ($i=0; $i <= $depth; $i++
) {
2250 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2251 $coursecontent = '';
2253 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
2258 echo '<div class="categorylist">';
2260 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2261 if (count($courses) > 0) {
2262 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2266 for ($i=0; $i< $depth; $i++
) {
2267 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
2274 echo html_writer
::tag('div', $html, array('class'=>'category'));
2275 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2281 * Print the buttons relating to course requests.
2283 * @param object $systemcontext the system context.
2285 function print_course_request_buttons($systemcontext) {
2286 global $CFG, $DB, $OUTPUT;
2287 if (empty($CFG->enablecourserequests
)) {
2290 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2291 /// Print a button to request a new course
2292 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2294 /// Print a button to manage pending requests
2295 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2296 $disabled = !$DB->record_exists('course_request', array());
2297 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2302 * Does the user have permission to edit things in this category?
2304 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2305 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2307 function can_edit_in_category($categoryid = 0) {
2308 $context = get_category_or_system_context($categoryid);
2309 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2313 * Prints the turn editing on/off button on course/index.php or course/category.php.
2315 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2316 * @return string HTML of the editing button, or empty string, if this user is not allowed
2319 function update_category_button($categoryid = 0) {
2320 global $CFG, $PAGE, $OUTPUT;
2322 // Check permissions.
2323 if (!can_edit_in_category($categoryid)) {
2327 // Work out the appropriate action.
2328 if ($PAGE->user_is_editing()) {
2329 $label = get_string('turneditingoff');
2332 $label = get_string('turneditingon');
2336 // Generate the button HTML.
2337 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2339 $options['id'] = $categoryid;
2340 $page = 'category.php';
2342 $page = 'index.php';
2344 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2348 * Category is 0 (for all courses) or an object
2350 function print_courses($category) {
2351 global $CFG, $OUTPUT;
2353 if (!is_object($category) && $category==0) {
2354 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2355 if (is_array($categories) && count($categories) == 1) {
2356 $category = array_shift($categories);
2357 $courses = get_courses_wmanagers($category->id
,
2359 array('summary','summaryformat'));
2361 $courses = get_courses_wmanagers('all',
2363 array('summary','summaryformat'));
2367 $courses = get_courses_wmanagers($category->id
,
2369 array('summary','summaryformat'));
2373 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
2374 foreach ($courses as $course) {
2375 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2376 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2377 echo html_writer
::start_tag('li');
2378 print_course($course);
2379 echo html_writer
::end_tag('li');
2382 echo html_writer
::end_tag('ul');
2384 echo $OUTPUT->heading(get_string("nocoursesyet"));
2385 $context = get_context_instance(CONTEXT_SYSTEM
);
2386 if (has_capability('moodle/course:create', $context)) {
2388 if (!empty($category->id
)) {
2389 $options['category'] = $category->id
;
2391 $options['category'] = $CFG->defaultrequestcategory
;
2393 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
2394 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2395 echo html_writer
::end_tag('div');
2401 * Print a description of a course, suitable for browsing in a list.
2403 * @param object $course the course object.
2404 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2406 function print_course($course, $highlightterms = '') {
2407 global $CFG, $USER, $DB, $OUTPUT;
2409 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2411 // Rewrite file URLs so that they are correct
2412 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
2414 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
2415 echo html_writer
::start_tag('div', array('class'=>'info'));
2416 echo html_writer
::start_tag('h3', array('class'=>'name'));
2418 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
2419 $linktext = highlight($highlightterms, format_string($course->fullname
));
2420 $linkparams = array('title'=>get_string('entercourse'));
2421 if (empty($course->visible
)) {
2422 $linkparams['class'] = 'dimmed';
2424 echo html_writer
::link($linkhref, $linktext, $linkparams);
2425 echo html_writer
::end_tag('h3');
2427 /// first find all roles that are supposed to be displayed
2428 if (!empty($CFG->coursecontact
)) {
2429 $managerroles = explode(',', $CFG->coursecontact
);
2430 $namesarray = array();
2431 if (isset($course->managers
)) {
2432 if (count($course->managers
)) {
2433 $rusers = $course->managers
;
2434 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2436 /// Rename some of the role names if needed
2437 if (isset($context)) {
2438 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2441 // keep a note of users displayed to eliminate duplicates
2442 $usersshown = array();
2443 foreach ($rusers as $ra) {
2445 // if we've already displayed user don't again
2446 if (in_array($ra->user
->id
,$usersshown)) {
2449 $usersshown[] = $ra->user
->id
;
2451 $fullname = fullname($ra->user
, $canviewfullnames);
2453 if (isset($aliasnames[$ra->roleid
])) {
2454 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2457 $namesarray[] = format_string($ra->rolename
).': '.
2458 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->user
->id
, 'course'=>SITEID
)), $fullname);
2462 $rusers = get_role_users($managerroles, $context,
2463 true, '', 'r.sortorder ASC, u.lastname ASC');
2464 if (is_array($rusers) && count($rusers)) {
2465 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2467 /// Rename some of the role names if needed
2468 if (isset($context)) {
2469 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2472 foreach ($rusers as $teacher) {
2473 $fullname = fullname($teacher, $canviewfullnames);
2475 /// Apply role names
2476 if (isset($aliasnames[$teacher->roleid
])) {
2477 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2480 $namesarray[] = format_string($teacher->rolename
).': '.
2481 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$teacher->id
, 'course'=>SITEID
)), $fullname);
2486 if (!empty($namesarray)) {
2487 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
2488 foreach ($namesarray as $name) {
2489 echo html_writer
::tag('li', $name);
2491 echo html_writer
::end_tag('ul');
2494 echo html_writer
::end_tag('div'); // End of info div
2496 echo html_writer
::start_tag('div', array('class'=>'summary'));
2497 $options = new stdClass();
2498 $options->noclean
= true;
2499 $options->para
= false;
2500 $options->overflowdiv
= true;
2501 if (!isset($course->summaryformat
)) {
2502 $course->summaryformat
= FORMAT_MOODLE
;
2504 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
2505 if ($icons = enrol_get_course_info_icons($course)) {
2506 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
2507 foreach ($icons as $icon) {
2508 echo $OUTPUT->render($icon);
2510 echo html_writer
::end_tag('div'); // End of enrolmenticons div
2512 echo html_writer
::end_tag('div'); // End of summary div
2513 echo html_writer
::end_tag('div'); // End of coursebox div
2517 * Prints custom user information on the home page.
2518 * Over time this can include all sorts of information
2520 function print_my_moodle() {
2521 global $USER, $CFG, $DB, $OUTPUT;
2523 if (!isloggedin() or isguestuser()) {
2524 print_error('nopermissions', '', '', 'See My Moodle');
2527 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2529 $rcourses = array();
2530 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2531 $rcourses = get_my_remotecourses($USER->id
);
2532 $rhosts = get_my_remotehosts();
2535 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2537 if (!empty($courses)) {
2538 echo '<ul class="unlist">';
2539 foreach ($courses as $course) {
2540 if ($course->id
== SITEID
) {
2544 print_course($course);
2551 if (!empty($rcourses)) {
2552 // at the IDP, we know of all the remote courses
2553 foreach ($rcourses as $course) {
2554 print_remote_course($course, "100%");
2556 } elseif (!empty($rhosts)) {
2557 // non-IDP, we know of all the remote servers, but not courses
2558 foreach ($rhosts as $host) {
2559 print_remote_host($host, "100%");
2565 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2566 echo "<table width=\"100%\"><tr><td align=\"center\">";
2567 print_course_search("", false, "short");
2568 echo "</td><td align=\"center\">";
2569 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2570 echo "</td></tr></table>\n";
2574 if ($DB->count_records("course_categories") > 1) {
2575 echo $OUTPUT->box_start("categorybox");
2576 print_whole_category_list();
2577 echo $OUTPUT->box_end();
2585 function print_course_search($value="", $return=false, $format="plain") {
2591 $id = 'coursesearch';
2597 $strsearchcourses= get_string("searchcourses");
2599 if ($format == 'plain') {
2600 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2601 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2602 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2603 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2604 $output .= '<input type="submit" value="'.get_string('go').'" />';
2605 $output .= '</fieldset></form>';
2606 } else if ($format == 'short') {
2607 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2608 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2609 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2610 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2611 $output .= '<input type="submit" value="'.get_string('go').'" />';
2612 $output .= '</fieldset></form>';
2613 } else if ($format == 'navbar') {
2614 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2615 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2616 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2617 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2618 $output .= '<input type="submit" value="'.get_string('go').'" />';
2619 $output .= '</fieldset></form>';
2628 function print_remote_course($course, $width="100%") {
2633 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2635 echo '<div class="coursebox remotecoursebox clearfix">';
2636 echo '<div class="info">';
2637 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2638 $linkcss.' href="'.$url.'">'
2639 . format_string($course->fullname
) .'</a><br />'
2640 . format_string($course->hostname
) . ' : '
2641 . format_string($course->cat_name
) . ' : '
2642 . format_string($course->shortname
). '</div>';
2643 echo '</div><div class="summary">';
2644 $options = new stdClass();
2645 $options->noclean
= true;
2646 $options->para
= false;
2647 $options->overflowdiv
= true;
2648 echo format_text($course->summary
, $course->summaryformat
, $options);
2653 function print_remote_host($host, $width="100%") {
2658 echo '<div class="coursebox clearfix">';
2659 echo '<div class="info">';
2660 echo '<div class="name">';
2661 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2662 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2663 . s($host['name']).'</a> - ';
2664 echo $host['count'] . ' ' . get_string('courses');
2671 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2673 function add_course_module($mod) {
2676 $mod->added
= time();
2679 return $DB->insert_record("course_modules", $mod);
2683 * Returns course section - creates new if does not exist yet.
2684 * @param int $relative section number
2685 * @param int $courseid
2686 * @return object $course_section object
2688 function get_course_section($section, $courseid) {
2691 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2694 $cw = new stdClass();
2695 $cw->course
= $courseid;
2696 $cw->section
= $section;
2698 $cw->summaryformat
= FORMAT_HTML
;
2700 $id = $DB->insert_record("course_sections", $cw);
2701 return $DB->get_record("course_sections", array("id"=>$id));
2704 * Given a full mod object with section and course already defined, adds this module to that section.
2706 * @param object $mod
2707 * @param int $beforemod An existing ID which we will insert the new module before
2708 * @return int The course_sections ID where the mod is inserted
2710 function add_mod_to_section($mod, $beforemod=NULL) {
2713 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course
, "section"=>$mod->section
))) {
2715 $section->sequence
= trim($section->sequence
);
2717 if (empty($section->sequence
)) {
2718 $newsequence = "$mod->coursemodule";
2720 } else if ($beforemod) {
2721 $modarray = explode(",", $section->sequence
);
2723 if ($key = array_keys($modarray, $beforemod->id
)) {
2724 $insertarray = array($mod->id
, $beforemod->id
);
2725 array_splice($modarray, $key[0], 1, $insertarray);
2726 $newsequence = implode(",", $modarray);
2728 } else { // Just tack it on the end anyway
2729 $newsequence = "$section->sequence,$mod->coursemodule";
2733 $newsequence = "$section->sequence,$mod->coursemodule";
2736 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2737 return $section->id
; // Return course_sections ID that was used.
2739 } else { // Insert a new record
2740 $section->course
= $mod->course
;
2741 $section->section
= $mod->section
;
2742 $section->summary
= "";
2743 $section->summaryformat
= FORMAT_HTML
;
2744 $section->sequence
= $mod->coursemodule
;
2745 return $DB->insert_record("course_sections", $section);
2749 function set_coursemodule_groupmode($id, $groupmode) {
2751 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2754 function set_coursemodule_idnumber($id, $idnumber) {
2756 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2760 * $prevstateoverrides = true will set the visibility of the course module
2761 * to what is defined in visibleold. This enables us to remember the current
2762 * visibility when making a whole section hidden, so that when we toggle
2763 * that section back to visible, we are able to return the visibility of
2764 * the course module back to what it was originally.
2766 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2768 require_once($CFG->libdir
.'/gradelib.php');
2770 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2773 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2776 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2777 foreach($events as $event) {
2786 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2787 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2789 foreach ($grade_items as $grade_item) {
2790 $grade_item->set_hidden(!$visible);
2794 if ($prevstateoverrides) {
2795 if ($visible == '0') {
2796 // Remember the current visible state so we can toggle this back.
2797 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id'=>$id));
2799 // Get the previous saved visible states.
2800 return $DB->set_field('course_modules', 'visible', $cm->visibleold
, array('id'=>$id));
2803 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2807 * Delete a course module and any associated data at the course level (events)
2808 * Until 1.5 this function simply marked a deleted flag ... now it
2809 * deletes it completely.
2812 function delete_course_module($id) {
2814 require_once($CFG->libdir
.'/gradelib.php');
2815 require_once($CFG->dirroot
.'/blog/lib.php');
2817 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2820 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
));
2821 //delete events from calendar
2822 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2823 foreach($events as $event) {
2824 delete_event($event->id
);
2827 //delete grade items, outcome items and grades attached to modules
2828 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2829 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2830 foreach ($grade_items as $grade_item) {
2831 $grade_item->delete('moddelete');
2834 // Delete completion and availability data; it is better to do this even if the
2835 // features are not turned on, in case they were turned on previously (these will be
2836 // very quick on an empty table)
2837 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2838 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2839 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
2840 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
2842 delete_context(CONTEXT_MODULE
, $cm->id
);
2843 return $DB->delete_records('course_modules', array('id'=>$cm->id
));
2846 function delete_mod_from_section($mod, $section) {
2849 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2851 $modarray = explode(",", $section->sequence
);
2853 if ($key = array_keys ($modarray, $mod)) {
2854 array_splice($modarray, $key[0], 1);
2855 $newsequence = implode(",", $modarray);
2856 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2866 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2868 * @param object $course course object
2869 * @param int $section Section number (not id!!!)
2870 * @param int $move (-1 or 1)
2871 * @return boolean true if section moved successfully
2873 function move_section($course, $section, $move) {
2874 /// Moves a whole course section up and down within the course
2881 $sectiondest = $section +
$move;
2883 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2887 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$section))) {
2891 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$sectiondest))) {
2895 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id
));
2896 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id
));
2898 // Update highlighting if the move affects highlighted section
2899 if ($course->marker
== $section) {
2900 course_set_marker($course->id
, $sectiondest);
2901 } elseif ($course->marker
== $sectiondest) {
2902 course_set_marker($course->id
, $section);
2905 // if the focus is on the section that is being moved, then move the focus along
2906 if (course_get_display($course->id
) == $section) {
2907 course_set_display($course->id
, $sectiondest);
2910 // Check for duplicates and fix order if needed.
2911 // There is a very rare case that some sections in the same course have the same section id.
2912 $sections = $DB->get_records('course_sections', array('course'=>$course->id
), 'section ASC');
2914 foreach ($sections as $section) {
2915 if ($section->section
!= $n) {
2916 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id
));
2924 * Moves a section within a course, from a position to another.
2925 * Be very careful: $section and $destination refer to section number,
2928 * @param object $course
2929 * @param int $section Section number (not id!!!)
2930 * @param int $destination
2931 * @return boolean Result
2933 function move_section_to($course, $section, $destination) {
2934 /// Moves a whole course section up and down within the course
2937 if (!$destination && $destination != 0) {
2941 if ($destination > $course->numsections
) {
2945 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2946 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2947 'section ASC, id ASC', 'id, section')) {
2951 $sections = reorder_sections($sections, $section, $destination);
2953 // Update all sections
2954 foreach ($sections as $id => $position) {
2955 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2958 // if the focus is on the section that is being moved, then move the focus along
2959 if (course_get_display($course->id
) == $section) {
2960 course_set_display($course->id
, $destination);
2966 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2967 * an original position number and a target position number, rebuilds the array so that the
2968 * move is made without any duplication of section positions.
2969 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2970 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2972 * @param array $sections
2973 * @param int $origin_position
2974 * @param int $target_position
2977 function reorder_sections($sections, $origin_position, $target_position) {
2978 if (!is_array($sections)) {
2982 // We can't move section position 0
2983 if ($origin_position < 1) {
2984 echo "We can't move section position 0";
2988 // Locate origin section in sections array
2989 if (!$origin_key = array_search($origin_position, $sections)) {
2990 echo "searched position not in sections array";
2991 return false; // searched position not in sections array
2994 // Extract origin section
2995 $origin_section = $sections[$origin_key];
2996 unset($sections[$origin_key]);
2998 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3000 $append_array = array();
3001 foreach ($sections as $id => $position) {
3003 $append_array[$id] = $position;
3004 unset($sections[$id]);
3006 if ($position == $target_position) {
3011 // Append moved section
3012 $sections[$origin_key] = $origin_section;
3014 // Append rest of array (if applicable)
3015 if (!empty($append_array)) {
3016 foreach ($append_array as $id => $position) {
3017 $sections[$id] = $position;
3021 // Renumber positions
3023 foreach ($sections as $id => $p) {
3024 $sections[$id] = $position;
3033 * Move the module object $mod to the specified $section
3034 * If $beforemod exists then that is the module
3035 * before which $modid should be inserted
3036 * All parameters are objects
3038 function moveto_module($mod, $section, $beforemod=NULL) {
3039 global $DB, $OUTPUT;
3041 /// Remove original module from original section
3042 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
3043 echo $OUTPUT->notification("Could not delete module from existing section");
3046 /// Update module itself if necessary
3048 if ($mod->section
!= $section->id
) {
3049 $mod->section
= $section->id
;
3050 $DB->update_record("course_modules", $mod);
3051 // if moving to a hidden section then hide module
3052 if (!$section->visible
) {
3053 set_coursemodule_visible($mod->id
, 0);
3057 /// Add the module into the new section
3059 $mod->course
= $section->course
;
3060 $mod->section
= $section->section
; // need relative reference
3061 $mod->coursemodule
= $mod->id
;
3063 if (! add_mod_to_section($mod, $beforemod)) {
3070 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
3071 global $CFG, $USER, $DB, $OUTPUT;
3076 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3077 // no permission to edit
3078 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
3083 $str->assign
= get_string("assignroles", 'role');
3084 $str->delete
= get_string("delete");
3085 $str->move
= get_string("move");
3086 $str->moveup
= get_string("moveup");
3087 $str->movedown
= get_string("movedown");
3088 $str->moveright
= get_string("moveright");
3089 $str->moveleft
= get_string("moveleft");
3090 $str->update
= get_string("update");
3091 $str->duplicate
= get_string("duplicate");
3092 $str->hide
= get_string("hide");
3093 $str->show
= get_string("show");
3094 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3095 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3096 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3097 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3098 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3099 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3100 $sesskey = sesskey();
3103 if ($section >= 0) {
3104 $section = '&sr='.$section; // Section return
3110 $path = $CFG->wwwroot
.'/course';
3114 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3115 if ($mod->visible
) {
3116 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
3117 '&sesskey='.$sesskey.$section.'"><img'.
3118 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
3119 ' alt="'.$str->hide
.'" /></a>'."\n";
3121 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
3122 '&sesskey='.$sesskey.$section.'"><img'.
3123 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
3124 ' alt="'.$str->show
.'" /></a>'."\n";
3130 if ($mod->groupmode
!== false) {
3131 if ($mod->groupmode
== SEPARATEGROUPS
) {
3132 $grouptitle = $str->groupsseparate
;
3133 $forcedgrouptitle = $str->forcedgroupsseparate
;
3134 $groupclass = 'editing_groupsseparate';
3135 $groupimage = $OUTPUT->pix_url('t/groups') . '';
3136 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
3137 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
3138 $grouptitle = $str->groupsvisible
;
3139 $forcedgrouptitle = $str->forcedgroupsvisible
;
3140 $groupclass = 'editing_groupsvisible';
3141 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
3142 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
3144 $grouptitle = $str->groupsnone
;
3145 $forcedgrouptitle = $str->forcedgroupsnone
;
3146 $groupclass = 'editing_groupsnone';
3147 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
3148 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
3150 if ($mod->groupmodelink
) {
3151 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.'" href="'.$grouplink.'">'.
3152 '<img src="'.$groupimage.'" class="iconsmall" '.
3153 'alt="'.$grouptitle.'" /></a>';
3155 $groupmode = '<img title="'.$forcedgrouptitle.'"'.
3156 ' src="'.$groupimage.'" class="iconsmall" '.
3157 'alt="'.$forcedgrouptitle.'" />';
3163 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3165 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
3166 '&sesskey='.$sesskey.$section.'"><img'.
3167 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
3168 ' alt="'.$str->move
.'" /></a>'."\n";
3170 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3171 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
3172 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
3173 ' alt="'.$str->moveup
.'" /></a>'."\n".
3174 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3175 '&move=1&sesskey='.$sesskey.$section.'"><img'.
3176 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
3177 ' alt="'.$str->movedown
.'" /></a>'."\n";
3184 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3186 if (right_to_left()) { // Exchange arrows on RTL
3187 $rightarrow = 't/left';
3188 $leftarrow = 't/right';
3190 $rightarrow = 't/right';
3191 $leftarrow = 't/left';
3195 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3196 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
3197 ' src="'.$OUTPUT->pix_url($leftarrow).'" class="iconsmall" '.
3198 ' alt="'.$str->moveleft
.'" /></a>'."\n";
3201 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3202 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
3203 ' src="'.$OUTPUT->pix_url($rightarrow).'" class="iconsmall" '.
3204 ' alt="'.$str->moveright
.'" /></a>'."\n";
3207 if (has_capability('moodle/role:assign', $modcontext)){
3208 $context = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3209 $assign = '<a class="editing_assign" title="'.$str->assign
.'" href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.
3210 $context->id
.'"><img src="'.$OUTPUT->pix_url('i/roles') . '" alt="'.$str->assign
.'" class="iconsmall"/></a>';
3215 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3216 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3217 if (has_all_capabilities($dupecaps, get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3218 $duplicatemodule = '<a class="editing_duplicate" title="'.$str->duplicate
.'" href="'.$path.'/mod.php?duplicate='.$mod->id
.
3219 '&sesskey='.$sesskey.$section.'"><img'.
3220 ' src="'.$OUTPUT->pix_url('t/copy') . '" class="iconsmall" '.
3221 ' alt="'.$str->duplicate
.'" /></a>'."\n";
3223 $duplicatemodule = '';
3226 return '<span class="commands">'."\n".$leftright.$move.
3227 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
3228 '&sesskey='.$sesskey.$section.'"><img'.
3229 ' src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" '.
3230 ' alt="'.$str->update
.'" /></a>'."\n".
3232 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
3233 '&sesskey='.$sesskey.$section.'"><img'.
3234 ' src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" '.
3235 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
3239 * given a course object with shortname & fullname, this function will
3240 * truncate the the number of chars allowed and add ... if it was too long
3242 function course_format_name ($course,$max=100) {
3244 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3245 $shortname = format_string($course->shortname
, true, array('context' => $context));
3246 $fullname = format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
3248 $str = $shortname.': '. $fullname;
3249 if (strlen($str) <= $max) {
3252 return $textlib->substr($str, 0, $max-3).'...';
3256 function update_restricted_mods($course, $mods) {
3259 /// Delete all the current restricted list
3260 $DB->delete_records('course_allowed_modules', array('course'=>$course->id
));
3262 if (empty($course->restrictmodules
)) {
3263 return; // We're done
3266 /// Insert the new list of restricted mods
3267 foreach ($mods as $mod) {
3269 continue; // this is the 'allow none' option
3271 $am = new stdClass();
3272 $am->course
= $course->id
;
3274 $DB->insert_record('course_allowed_modules',$am);
3279 * This function will take an int (module id) or a string (module name)
3280 * and return true or false, whether it's allowed in the given course (object)
3281 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3282 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3285 function course_allowed_module($course,$mod) {
3288 if (empty($course->restrictmodules
)) {
3292 // Admins and admin-like people who can edit everything can also add anything.
3293 // Originally there was a course:update test only, but it did not match the test in course edit form
3294 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3298 if (is_numeric($mod)) {
3300 } else if (is_string($mod)) {
3301 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3303 if (empty($modid)) {
3307 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id
, 'module'=>$modid));
3311 * Recursively delete category including all subcategories and courses.
3312 * @param stdClass $category
3313 * @param boolean $showfeedback display some notices
3314 * @return array return deleted courses
3316 function category_delete_full($category, $showfeedback=true) {
3318 require_once($CFG->libdir
.'/gradelib.php');
3319 require_once($CFG->libdir
.'/questionlib.php');
3320 require_once($CFG->dirroot
.'/cohort/lib.php');
3322 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3323 foreach ($children as $childcat) {
3324 category_delete_full($childcat, $showfeedback);
3328 $deletedcourses = array();
3329 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
3330 foreach ($courses as $course) {
3331 if (!delete_course($course, false)) {
3332 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
3334 $deletedcourses[] = $course;
3338 // move or delete cohorts in this context
3339 cohort_delete_category($category);
3341 // now delete anything that may depend on course category context
3342 grade_course_category_delete($category->id
, 0, $showfeedback);
3343 if (!question_delete_course_category($category, 0, $showfeedback)) {
3344 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
3347 // finally delete the category and it's context
3348 $DB->delete_records('course_categories', array('id'=>$category->id
));
3349 delete_context(CONTEXT_COURSECAT
, $category->id
);
3351 events_trigger('course_category_deleted', $category);
3353 return $deletedcourses;
3357 * Delete category, but move contents to another category.
3358 * @param object $ccategory
3359 * @param int $newparentid category id
3360 * @return bool status
3362 function category_delete_move($category, $newparentid, $showfeedback=true) {
3363 global $CFG, $DB, $OUTPUT;
3364 require_once($CFG->libdir
.'/gradelib.php');
3365 require_once($CFG->libdir
.'/questionlib.php');
3366 require_once($CFG->dirroot
.'/cohort/lib.php');
3368 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3372 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3373 foreach ($children as $childcat) {
3374 move_category($childcat, $newparentcat);
3378 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
3379 if (!move_courses(array_keys($courses), $newparentid)) {
3380 echo $OUTPUT->notification("Error moving courses");
3383 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3386 // move or delete cohorts in this context
3387 cohort_delete_category($category);
3389 // now delete anything that may depend on course category context
3390 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3391 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3392 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3396 // finally delete the category and it's context
3397 $DB->delete_records('course_categories', array('id'=>$category->id
));
3398 delete_context(CONTEXT_COURSECAT
, $category->id
);
3400 events_trigger('course_category_deleted', $category);
3402 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3408 * Efficiently moves many courses around while maintaining
3409 * sortorder in order.
3411 * @param array $courseids is an array of course ids
3412 * @param int $categoryid
3413 * @return bool success
3415 function move_courses($courseids, $categoryid) {
3416 global $CFG, $DB, $OUTPUT;
3418 if (empty($courseids)) {
3423 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3427 $courseids = array_reverse($courseids);
3428 $newparent = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3431 foreach ($courseids as $courseid) {
3432 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3433 $course = new stdClass();
3434 $course->id
= $courseid;
3435 $course->category
= $category->id
;
3436 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
3437 if ($category->visible
== 0) {
3438 // hide the course when moving into hidden category,
3439 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3440 $course->visible
= 0;
3443 $DB->update_record('course', $course);
3445 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3446 context_moved($context, $newparent);
3449 fix_course_sortorder();
3455 * Hide course category and child course and subcategories
3456 * @param stdClass $category
3459 function course_category_hide($category) {
3462 $category->visible
= 0;
3463 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
3464 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
3465 $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
3466 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
3467 // get all child categories and hide too
3468 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3469 foreach ($subcats as $cat) {
3470 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
3471 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
3472 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
3473 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
3479 * Show course category and child course and subcategories
3480 * @param stdClass $category
3483 function course_category_show($category) {
3486 $category->visible
= 1;
3487 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
3488 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
3489 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
3490 // get all child categories and unhide too
3491 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3492 foreach ($subcats as $cat) {
3493 if ($cat->visibleold
) {
3494 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
3496 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
3502 * Efficiently moves a category - NOTE that this can have
3503 * a huge impact access-control-wise...
3505 function move_category($category, $newparentcat) {
3508 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3511 if (empty($newparentcat->id
)) {
3512 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id
));
3514 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3517 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id'=>$category->id
));
3518 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3520 if (!$newparentcat->visible
and $category->visible
) {
3521 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3526 context_moved($context, $newparent);
3528 // now make it last in new category
3529 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
3531 // and fix the sortorders
3532 fix_course_sortorder();
3535 course_category_hide($category);
3540 * Returns the display name of the given section that the course prefers.
3542 * This function utilizes a callback that can be implemented within the course
3543 * formats lib.php file to customize the display name that is used to reference
3546 * By default (if callback is not defined) the method
3547 * {@see get_numeric_section_name} is called instead.
3549 * @param stdClass $course The course to get the section name for
3550 * @param stdClass $section Section object from database
3551 * @return Display name that the course format prefers, e.g. "Week 2"
3553 * @see get_generic_section_name
3555 function get_section_name(stdClass
$course, stdClass
$section) {
3558 /// Inelegant hack for bug 3408
3559 if ($course->format
== 'site') {
3560 return get_string('site');
3563 // Use course formatter callback if it exists
3564 $namingfile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3565 $namingfunction = 'callback_'.$course->format
.'_get_section_name';
3566 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3567 require_once $namingfile;
3569 if (function_exists($namingfunction)) {
3570 return $namingfunction($course, $section);
3573 // else, default behavior:
3574 return get_generic_section_name($course->format
, $section);
3578 * Gets the generic section name for a courses section.
3580 * @param string $format Course format ID e.g. 'weeks' $course->format
3581 * @param stdClass $section Section object from database
3582 * @return Display name that the course format prefers, e.g. "Week 2"
3584 function get_generic_section_name($format, stdClass
$section) {
3585 return get_string('sectionname', "format_$format") . ' ' . $section->section
;
3589 function course_format_uses_sections($format) {
3592 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3593 $featurefunction = 'callback_'.$format.'_uses_sections';
3594 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3595 require_once $featurefile;
3597 if (function_exists($featurefunction)) {
3598 return $featurefunction();
3605 * Returns the information about the ajax support in the given source format
3607 * The returned object's property (boolean)capable indicates that
3608 * the course format supports Moodle course ajax features.
3609 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3611 * @param string $format
3614 function course_format_ajax_support($format) {
3617 // set up default values
3618 $ajaxsupport = new stdClass();
3619 $ajaxsupport->capable
= false;
3620 $ajaxsupport->testedbrowsers
= array();
3622 // get the information from the course format library
3623 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3624 $featurefunction = 'callback_'.$format.'_ajax_support';
3625 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3626 require_once $featurefile;
3628 if (function_exists($featurefunction)) {
3629 $formatsupport = $featurefunction();
3630 if (isset($formatsupport->capable
)) {
3631 $ajaxsupport->capable
= $formatsupport->capable
;
3633 if (is_array($formatsupport->testedbrowsers
)) {
3634 $ajaxsupport->testedbrowsers
= $formatsupport->testedbrowsers
;
3638 return $ajaxsupport;
3642 * Can the current user delete this course?
3643 * Course creators have exception,
3644 * 1 day after the creation they can sill delete the course.
3645 * @param int $courseid
3648 function can_delete_course($courseid) {
3651 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3653 if (has_capability('moodle/course:delete', $context)) {
3657 // hack: now try to find out if creator created this course recently (1 day)
3658 if (!has_capability('moodle/course:create', $context)) {
3662 $since = time() - 60*60*24;
3664 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3665 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3667 return $DB->record_exists_select('log', $select, $params);
3671 * Save the Your name for 'Some role' strings.
3673 * @param integer $courseid the id of this course.
3674 * @param array $data the data that came from the course settings form.
3676 function save_local_role_names($courseid, $data) {
3678 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3680 foreach ($data as $fieldname => $value) {
3681 if (strpos($fieldname, 'role_') !== 0) {
3684 list($ignored, $roleid) = explode('_', $fieldname);
3686 // make up our mind whether we want to delete, update or insert
3688 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3690 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3691 $rolename->name
= $value;
3692 $DB->update_record('role_names', $rolename);
3695 $rolename = new stdClass
;
3696 $rolename->contextid
= $context->id
;
3697 $rolename->roleid
= $roleid;
3698 $rolename->name
= $value;
3699 $DB->insert_record('role_names', $rolename);
3705 * Create a course and either return a $course object
3707 * Please note this functions does not verify any access control,
3708 * the calling code is responsible for all validation (usually it is the form definition).
3710 * @param array $editoroptions course description editor options
3711 * @param object $data - all the data needed for an entry in the 'course' table
3712 * @return object new course instance
3714 function create_course($data, $editoroptions = NULL) {
3717 //check the categoryid - must be given for all new courses
3718 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3720 //check if the shortname already exist
3721 if (!empty($data->shortname
)) {
3722 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3723 throw new moodle_exception('shortnametaken');
3727 //check if the id number already exist
3728 if (!empty($data->idnumber
)) {
3729 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3730 throw new moodle_exception('idnumbertaken');
3734 $data->timecreated
= time();
3735 $data->timemodified
= $data->timecreated
;
3737 // place at beginning of any category
3738 $data->sortorder
= 0;
3740 if ($editoroptions) {
3741 // summary text is updated later, we need context to store the files first
3742 $data->summary
= '';
3743 $data->summary_format
= FORMAT_HTML
;
3746 if (!isset($data->visible
)) {
3747 // data not from form, add missing visibility info
3748 $data->visible
= $category->visible
;
3750 $data->visibleold
= $data->visible
;
3752 $newcourseid = $DB->insert_record('course', $data);
3753 $context = get_context_instance(CONTEXT_COURSE
, $newcourseid, MUST_EXIST
);
3755 if ($editoroptions) {
3756 // Save the files used in the summary editor and store
3757 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3758 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3759 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3762 $course = $DB->get_record('course', array('id'=>$newcourseid));
3765 blocks_add_default_course_blocks($course);
3767 $section = new stdClass();
3768 $section->course
= $course->id
; // Create a default section.
3769 $section->section
= 0;
3770 $section->summaryformat
= FORMAT_HTML
;
3771 $DB->insert_record('course_sections', $section);
3773 fix_course_sortorder();
3775 // update module restrictions
3776 if ($course->restrictmodules
) {
3777 if (isset($data->allowedmods
)) {
3778 update_restricted_mods($course, $data->allowedmods
);
3780 if (!empty($CFG->defaultallowedmodules
)) {
3781 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules
));
3786 // new context created - better mark it as dirty
3787 mark_context_dirty($context->path
);
3789 // Save any custom role names.
3790 save_local_role_names($course->id
, (array)$data);
3792 // set up enrolments
3793 enrol_course_updated(true, $course, $data);
3795 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3798 events_trigger('course_created', $course);
3806 * Please note this functions does not verify any access control,
3807 * the calling code is responsible for all validation (usually it is the form definition).
3809 * @param object $data - all the data needed for an entry in the 'course' table
3810 * @param array $editoroptions course description editor options
3813 function update_course($data, $editoroptions = NULL) {
3816 $data->timemodified
= time();
3818 $oldcourse = $DB->get_record('course', array('id'=>$data->id
), '*', MUST_EXIST
);
3819 $context = get_context_instance(CONTEXT_COURSE
, $oldcourse->id
);
3821 if ($editoroptions) {
3822 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3825 if (!isset($data->category
) or empty($data->category
)) {
3826 // prevent nulls and 0 in category field
3827 unset($data->category
);
3829 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3831 if (!isset($data->visible
)) {
3832 // data not from form, add missing visibility info
3833 $data->visible
= $oldcourse->visible
;
3836 if ($data->visible
!= $oldcourse->visible
) {
3837 // reset the visibleold flag when manually hiding/unhiding course
3838 $data->visibleold
= $data->visible
;
3841 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3842 if (empty($newcategory->visible
)) {
3843 // make sure when moving into hidden category the course is hidden automatically
3849 // Update with the new data
3850 $DB->update_record('course', $data);
3852 $course = $DB->get_record('course', array('id'=>$data->id
));
3855 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3856 context_moved($context, $newparent);
3859 fix_course_sortorder();
3861 // Test for and remove blocks which aren't appropriate anymore
3862 blocks_remove_inappropriate($course);
3864 // update module restrictions
3865 if (isset($data->allowedmods
)) {
3866 update_restricted_mods($course, $data->allowedmods
);
3869 // Save any custom role names.
3870 save_local_role_names($course->id
, $data);
3872 // update enrol settings
3873 enrol_course_updated(false, $course, $data);
3875 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3878 events_trigger('course_updated', $course);
3882 * Average number of participants
3885 function average_number_of_participants() {
3888 //count total of enrolments for visible course (except front page)
3889 $sql = 'SELECT COUNT(*) FROM (
3890 SELECT DISTINCT ue.userid, e.courseid
3891 FROM {user_enrolments} ue, {enrol} e, {course} c
3892 WHERE ue.enrolid = e.id
3893 AND e.courseid <> :siteid
3894 AND c.id = e.courseid
3895 AND c.visible = 1) as total';
3896 $params = array('siteid' => $SITE->id
);
3897 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3900 //count total of visible courses (minus front page)
3901 $coursetotal = $DB->count_records('course', array('visible' => 1));
3902 $coursetotal = $coursetotal - 1 ;
3904 //average of enrolment
3905 if (empty($coursetotal)) {
3906 $participantaverage = 0;
3908 $participantaverage = $enrolmenttotal / $coursetotal;
3911 return $participantaverage;
3915 * Average number of course modules
3918 function average_number_of_courses_modules() {
3921 //count total of visible course module (except front page)
3922 $sql = 'SELECT COUNT(*) FROM (
3923 SELECT cm.course, cm.module
3924 FROM {course} c, {course_modules} cm
3925 WHERE c.id = cm.course
3928 AND c.visible = 1) as total';
3929 $params = array('siteid' => $SITE->id
);
3930 $moduletotal = $DB->count_records_sql($sql, $params);
3933 //count total of visible courses (minus front page)
3934 $coursetotal = $DB->count_records('course', array('visible' => 1));
3935 $coursetotal = $coursetotal - 1 ;
3937 //average of course module
3938 if (empty($coursetotal)) {
3939 $coursemoduleaverage = 0;
3941 $coursemoduleaverage = $moduletotal / $coursetotal;
3944 return $coursemoduleaverage;
3948 * This class pertains to course requests and contains methods associated with
3949 * create, approving, and removing course requests.
3951 * Please note we do not allow embedded images here because there is no context
3952 * to store them with proper access control.
3954 * @copyright 2009 Sam Hemelryk
3955 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3958 * @property-read int $id
3959 * @property-read string $fullname
3960 * @property-read string $shortname
3961 * @property-read string $summary
3962 * @property-read int $summaryformat
3963 * @property-read int $summarytrust
3964 * @property-read string $reason
3965 * @property-read int $requester
3967 class course_request
{
3970 * This is the stdClass that stores the properties for the course request
3971 * and is externally accessed through the __get magic method
3974 protected $properties;
3977 * An array of options for the summary editor used by course request forms.
3978 * This is initially set by {@link summary_editor_options()}
3982 protected static $summaryeditoroptions;
3985 * Static function to prepare the summary editor for working with a course
3989 * @param null|stdClass $data Optional, an object containing the default values
3990 * for the form, these may be modified when preparing the
3991 * editor so this should be called before creating the form
3992 * @return stdClass An object that can be used to set the default values for
3995 public static function prepare($data=null) {
3996 if ($data === null) {
3997 $data = new stdClass
;
3999 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
4004 * Static function to create a new course request when passed an array of properties
4007 * This function also handles saving any files that may have been used in the editor
4010 * @param stdClass $data
4011 * @return course_request The newly created course request
4013 public static function create($data) {
4014 global $USER, $DB, $CFG;
4015 $data->requester
= $USER->id
;
4017 // Summary is a required field so copy the text over
4018 $data->summary
= $data->summary_editor
['text'];
4019 $data->summaryformat
= $data->summary_editor
['format'];
4021 $data->id
= $DB->insert_record('course_request', $data);
4023 // Create a new course_request object and return it
4024 $request = new course_request($data);
4026 // Notify the admin if required.
4027 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
4030 $a->link
= "$CFG->wwwroot/course/pending.php";
4031 $a->user
= fullname($USER);
4032 $subject = get_string('courserequest');
4033 $message = get_string('courserequestnotifyemail', 'admin', $a);
4034 foreach ($users as $user) {
4035 $request->notify($user, $USER, 'courserequested', $subject, $message);
4043 * Returns an array of options to use with a summary editor
4045 * @uses course_request::$summaryeditoroptions
4046 * @return array An array of options to use with the editor
4048 public static function summary_editor_options() {
4050 if (self
::$summaryeditoroptions === null) {
4051 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4053 return self
::$summaryeditoroptions;
4057 * Loads the properties for this course request object. Id is required and if
4058 * only id is provided then we load the rest of the properties from the database
4060 * @param stdClass|int $properties Either an object containing properties
4061 * or the course_request id to load
4063 public function __construct($properties) {
4065 if (empty($properties->id
)) {
4066 if (empty($properties)) {
4067 throw new coding_exception('You must provide a course request id when creating a course_request object');
4070 $properties = new stdClass
;
4071 $properties->id
= (int)$id;
4074 if (empty($properties->requester
)) {
4075 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
4076 print_error('unknowncourserequest');
4079 $this->properties
= $properties;
4081 $this->properties
->collision
= null;
4085 * Returns the requested property
4087 * @param string $key
4090 public function __get($key) {
4091 return $this->properties
->$key;
4095 * Override this to ensure empty($request->blah) calls return a reliable answer...
4097 * This is required because we define the __get method
4100 * @return bool True is it not empty, false otherwise
4102 public function __isset($key) {
4103 return (!empty($this->properties
->$key));
4107 * Returns the user who requested this course
4109 * Uses a static var to cache the results and cut down the number of db queries
4111 * @staticvar array $requesters An array of cached users
4112 * @return stdClass The user who requested the course
4114 public function get_requester() {
4116 static $requesters= array();
4117 if (!array_key_exists($this->properties
->requester
, $requesters)) {
4118 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
4120 return $requesters[$this->properties
->requester
];
4124 * Checks that the shortname used by the course does not conflict with any other
4125 * courses that exist
4127 * @param string|null $shortnamemark The string to append to the requests shortname
4128 * should a conflict be found
4129 * @return bool true is there is a conflict, false otherwise
4131 public function check_shortname_collision($shortnamemark = '[*]') {
4134 if ($this->properties
->collision
!== null) {
4135 return $this->properties
->collision
;
4138 if (empty($this->properties
->shortname
)) {
4139 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
4140 $this->properties
->collision
= false;
4141 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
4142 if (!empty($shortnamemark)) {
4143 $this->properties
->shortname
.= ' '.$shortnamemark;
4145 $this->properties
->collision
= true;
4147 $this->properties
->collision
= false;
4149 return $this->properties
->collision
;
4153 * This function approves the request turning it into a course
4155 * This function converts the course request into a course, at the same time
4156 * transferring any files used in the summary to the new course and then removing
4157 * the course request and the files associated with it.
4159 * @return int The id of the course that was created from this request
4161 public function approve() {
4162 global $CFG, $DB, $USER;
4164 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
4166 $category = get_course_category($CFG->defaultrequestcategory
);
4167 $courseconfig = get_config('moodlecourse');
4169 // Transfer appropriate settings
4170 $data = clone($this->properties
);
4172 unset($data->reason
);
4173 unset($data->requester
);
4176 $data->category
= $category->id
;
4177 $data->sortorder
= $category->sortorder
; // place as the first in category
4179 // Set misc settings
4180 $data->requested
= 1;
4181 if (!empty($CFG->restrictmodulesfor
) && $CFG->restrictmodulesfor
!= 'none' && !empty($CFG->restrictbydefault
)) {
4182 $data->restrictmodules
= 1;
4185 // Apply course default settings
4186 $data->format
= $courseconfig->format
;
4187 $data->numsections
= $courseconfig->numsections
;
4188 $data->hiddensections
= $courseconfig->hiddensections
;
4189 $data->newsitems
= $courseconfig->newsitems
;
4190 $data->showgrades
= $courseconfig->showgrades
;
4191 $data->showreports
= $courseconfig->showreports
;
4192 $data->maxbytes
= $courseconfig->maxbytes
;
4193 $data->groupmode
= $courseconfig->groupmode
;
4194 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
4195 $data->visible
= $courseconfig->visible
;
4196 $data->visibleold
= $data->visible
;
4197 $data->lang
= $courseconfig->lang
;
4199 $course = create_course($data);
4200 $context = get_context_instance(CONTEXT_COURSE
, $course->id
, MUST_EXIST
);
4202 // add enrol instances
4203 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
4204 if ($manual = enrol_get_plugin('manual')) {
4205 $manual->add_default_instance($course);
4209 // enrol the requester as teacher if necessary
4210 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4211 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
4216 $a = new stdClass();
4217 $a->name
= format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
4218 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
4219 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4225 * Reject a course request
4227 * This function rejects a course request, emailing the requesting user the
4228 * provided notice and then removing the request from the database
4230 * @param string $notice The message to display to the user
4232 public function reject($notice) {
4234 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
4235 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4240 * Deletes the course request and any associated files
4242 public function delete() {
4244 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
4248 * Send a message from one user to another using events_trigger
4250 * @param object $touser
4251 * @param object $fromuser
4252 * @param string $name
4253 * @param string $subject
4254 * @param string $message
4256 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4257 $eventdata = new stdClass();
4258 $eventdata->component
= 'moodle';
4259 $eventdata->name
= $name;
4260 $eventdata->userfrom
= $fromuser;
4261 $eventdata->userto
= $touser;
4262 $eventdata->subject
= $subject;
4263 $eventdata->fullmessage
= $message;
4264 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
4265 $eventdata->fullmessagehtml
= '';
4266 $eventdata->smallmessage
= '';
4267 $eventdata->notification
= 1;
4268 message_send($eventdata);
4273 * Return a list of page types
4274 * @param string $pagetype current page type
4275 * @param stdClass $parentcontext Block's parent context
4276 * @param stdClass $currentcontext Current context of block
4278 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4279 // if above course context ,display all course fomats
4280 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
4281 if ($course->id
== SITEID
) {
4282 return array('*'=>get_string('page-x', 'pagetype'));
4284 return array('*'=>get_string('page-x', 'pagetype'),
4285 'course-*'=>get_string('page-course-x', 'pagetype'),
4286 'course-view-*'=>get_string('page-course-view-x', 'pagetype')