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 * For a given course section, marks it visible or hidden,
1338 * and does the same for every activity in that section
1340 function set_section_visible($courseid, $sectionnumber, $visibility) {
1343 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1344 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1345 if (!empty($section->sequence
)) {
1346 $modules = explode(",", $section->sequence
);
1347 foreach ($modules as $moduleid) {
1348 set_coursemodule_visible($moduleid, $visibility, true);
1351 rebuild_course_cache($courseid);
1356 * Obtains shared data that is used in print_section when displaying a
1357 * course-module entry.
1359 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1361 * This data is also used in other areas of the code.
1362 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1363 * @param object $course Moodle course object
1364 * @return array An array with the following values in this order:
1365 * $content (optional extra content for after link),
1366 * $instancename (text of link)
1368 function get_print_section_cm_text(cm_info
$cm, $course) {
1371 // Get course context
1372 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1374 // Get content from modinfo if specified. Content displays either
1375 // in addition to the standard link (below), or replaces it if
1376 // the link is turned off by setting ->url to null.
1377 if (($content = $cm->get_content()) !== '') {
1378 $labelformatoptions = new stdClass();
1379 $labelformatoptions->noclean
= true;
1380 $labelformatoptions->overflowdiv
= true;
1381 $labelformatoptions->context
= $coursecontext;
1382 $content = format_text($content, FORMAT_HTML
, $labelformatoptions);
1387 $stringoptions = new stdClass
;
1388 $stringoptions->context
= $coursecontext;
1389 $instancename = format_string($cm->name
, true, $stringoptions);
1390 return array($content, $instancename);
1394 * Prints a section full of activity modules
1396 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1397 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1399 static $initialised;
1401 static $groupbuttons;
1402 static $groupbuttonslink;
1405 static $strmovehere;
1406 static $strmovefull;
1407 static $strunreadpostsone;
1409 static $modulenames;
1411 if (!isset($initialised)) {
1412 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1413 $groupbuttonslink = (!$course->groupmodeforce
);
1414 $isediting = $PAGE->user_is_editing();
1415 $ismoving = $isediting && ismoving($course->id
);
1417 $strmovehere = get_string("movehere");
1418 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1420 $modulenames = array();
1421 $initialised = true;
1424 $tl = textlib_get_instance();
1426 $modinfo = get_fast_modinfo($course);
1427 $completioninfo = new completion_info($course);
1429 //Accessibility: replace table with list <ul>, but don't output empty list.
1430 if (!empty($section->sequence
)) {
1432 // Fix bug #5027, don't want style=\"width:$width\".
1433 echo "<ul class=\"section img-text\">\n";
1434 $sectionmods = explode(",", $section->sequence
);
1436 foreach ($sectionmods as $modnumber) {
1437 if (empty($mods[$modnumber])) {
1444 $mod = $mods[$modnumber];
1446 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1447 // do not display moving mod
1451 if (isset($modinfo->cms
[$modnumber])) {
1452 // We can continue (because it will not be displayed at all)
1454 // 1) The activity is not visible to users
1456 // 2a) The 'showavailability' option is not set (if that is set,
1457 // we need to display the activity so we can show
1458 // availability info)
1460 // 2b) The 'availableinfo' is empty, i.e. the activity was
1461 // hidden in a way that leaves no info, such as using the
1463 if (!$modinfo->cms
[$modnumber]->uservisible
&&
1464 (empty($modinfo->cms
[$modnumber]->showavailability
) ||
1465 empty($modinfo->cms
[$modnumber]->availableinfo
))) {
1466 // visibility shortcut
1470 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1471 // module not installed
1474 if (!coursemodule_visible_for_user($mod) &&
1475 empty($mod->showavailability
)) {
1476 // full visibility check
1481 if (!isset($modulenames[$mod->modname
])) {
1482 $modulenames[$mod->modname
] = get_string('modulename', $mod->modname
);
1484 $modulename = $modulenames[$mod->modname
];
1486 // In some cases the activity is visible to user, but it is
1487 // dimmed. This is done if viewhiddenactivities is true and if:
1488 // 1. the activity is not visible, or
1489 // 2. the activity has dates set which do not include current, or
1490 // 3. the activity has any other conditions set (regardless of whether
1491 // current user meets them)
1492 $canviewhidden = has_capability(
1493 'moodle/course:viewhiddenactivities',
1494 get_context_instance(CONTEXT_MODULE
, $mod->id
));
1495 $accessiblebutdim = false;
1496 if ($canviewhidden) {
1497 $accessiblebutdim = !$mod->visible
;
1498 if (!empty($CFG->enableavailability
)) {
1499 $accessiblebutdim = $accessiblebutdim ||
1500 $mod->availablefrom
> time() ||
1501 ($mod->availableuntil
&& $mod->availableuntil
< time()) ||
1502 count($mod->conditionsgrade
) > 0 ||
1503 count($mod->conditionscompletion
) > 0;
1507 $liclasses = array();
1508 $liclasses[] = 'activity';
1509 $liclasses[] = $mod->modname
;
1510 $liclasses[] = 'modtype_'.$mod->modname
;
1511 $extraclasses = $mod->get_extra_classes();
1512 if ($extraclasses) {
1513 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1515 echo html_writer
::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1517 echo '<a title="'.$strmovefull.'"'.
1518 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.sesskey().'">'.
1519 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1520 ' alt="'.$strmovehere.'" /></a><br />
1524 $classes = array('mod-indent');
1525 if (!empty($mod->indent
)) {
1526 $classes[] = 'mod-indent-'.$mod->indent
;
1527 if ($mod->indent
> 15) {
1528 $classes[] = 'mod-indent-huge';
1531 echo html_writer
::start_tag('div', array('class'=>join(' ', $classes)));
1533 // Get data about this course-module
1534 list($content, $instancename) =
1535 get_print_section_cm_text($modinfo->cms
[$modnumber], $course);
1537 //Accessibility: for files get description via icon, this is very ugly hack!
1539 $altname = $mod->modfullname
;
1540 if (!empty($customicon)) {
1541 $archetype = plugin_supports('mod', $mod->modname
, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1542 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1543 $mimetype = mimeinfo_from_icon('type', $customicon);
1544 $altname = get_mimetype_description($mimetype);
1547 // Avoid unnecessary duplication: if e.g. a forum name already
1548 // includes the word forum (or Forum, etc) then it is unhelpful
1549 // to include that in the accessible description that is added.
1550 if (false !== strpos($tl->strtolower($instancename),
1551 $tl->strtolower($altname))) {
1554 // File type after name, for alphabetic lists (screen reader).
1556 $altname = get_accesshide(' '.$altname);
1559 // We may be displaying this just in order to show information
1560 // about visibility, without the actual link
1562 if ($mod->uservisible
) {
1563 // Nope - in this case the link is fully working for user
1566 if ($accessiblebutdim) {
1567 $linkclasses .= ' dimmed';
1568 $textclasses .= ' dimmed_text';
1569 $accesstext = '<span class="accesshide">'.
1570 get_string('hiddenfromstudents').': </span>';
1575 $linkcss = 'class="' . trim($linkclasses) . '" ';
1580 $textcss = 'class="' . trim($textclasses) . '" ';
1585 // Get on-click attribute value if specified
1586 $onclick = $mod->get_on_click();
1588 $onclick = ' onclick="' . $onclick . '"';
1591 if ($url = $mod->get_url()) {
1592 // Display link itself
1593 echo '<a ' . $linkcss . $mod->extra
. $onclick .
1594 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1595 '" class="activityicon" alt="' .
1596 $modulename . '" /> ' .
1597 $accesstext . '<span class="instancename">' .
1598 $instancename . $altname . '</span></a>';
1600 // If specified, display extra content after link
1602 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1603 '">' . $content . '</div>';
1606 // No link, so display only content
1607 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1608 $accesstext . $content . '</div>';
1611 if (!empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1612 if (!isset($groupings)) {
1613 $groupings = groups_get_all_groupings($course->id
);
1615 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1618 $textclasses = $extraclasses;
1619 $textclasses .= ' dimmed_text';
1621 $textcss = 'class="' . trim($textclasses) . '" ';
1625 $accesstext = '<span class="accesshide">' .
1626 get_string('notavailableyet', 'condition') .
1629 if ($url = $mod->get_url()) {
1630 // Display greyed-out text of link
1631 echo '<div ' . $textcss . $mod->extra
.
1632 ' >' . '<img src="' . $mod->get_icon_url() .
1633 '" class="activityicon" alt="' .
1635 '" /> <span>'. $instancename . $altname .
1638 // Do not display content after link when it is greyed out like this.
1640 // No link, so display only content (also greyed)
1641 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1642 $accesstext . $content . '</div>';
1646 // Module can put text after the link (e.g. forum unread)
1647 echo $mod->get_after_link();
1649 // If there is content but NO link (eg label), then display the
1650 // content here (BEFORE any icons). In this case cons must be
1651 // displayed after the content so that it makes more sense visually
1652 // and for accessibility reasons, e.g. if you have a one-line label
1653 // it should work similarly (at least in terms of ordering) to an
1660 if ($groupbuttons and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
1661 if (! $mod->groupmodelink
= $groupbuttonslink) {
1662 $mod->groupmode
= $course->groupmode
;
1666 $mod->groupmode
= false;
1668 echo ' ';
1669 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1670 echo $mod->get_after_edit_icons();
1674 $completion = $hidecompletion
1675 ? COMPLETION_TRACKING_NONE
1676 : $completioninfo->is_enabled($mod);
1677 if ($completion!=COMPLETION_TRACKING_NONE
&& isloggedin() &&
1678 !isguestuser() && $mod->uservisible
) {
1679 $completiondata = $completioninfo->get_data($mod,true);
1680 $completionicon = '';
1682 switch ($completion) {
1683 case COMPLETION_TRACKING_MANUAL
:
1684 $completionicon = 'manual-enabled'; break;
1685 case COMPLETION_TRACKING_AUTOMATIC
:
1686 $completionicon = 'auto-enabled'; break;
1689 } else if ($completion==COMPLETION_TRACKING_MANUAL
) {
1690 switch($completiondata->completionstate
) {
1691 case COMPLETION_INCOMPLETE
:
1692 $completionicon = 'manual-n'; break;
1693 case COMPLETION_COMPLETE
:
1694 $completionicon = 'manual-y'; break;
1696 } else { // Automatic
1697 switch($completiondata->completionstate
) {
1698 case COMPLETION_INCOMPLETE
:
1699 $completionicon = 'auto-n'; break;
1700 case COMPLETION_COMPLETE
:
1701 $completionicon = 'auto-y'; break;
1702 case COMPLETION_COMPLETE_PASS
:
1703 $completionicon = 'auto-pass'; break;
1704 case COMPLETION_COMPLETE_FAIL
:
1705 $completionicon = 'auto-fail'; break;
1708 if ($completionicon) {
1709 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1710 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1711 if ($completion == COMPLETION_TRACKING_MANUAL
&& !$isediting) {
1712 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1714 $completiondata->completionstate
==COMPLETION_COMPLETE
1715 ? COMPLETION_INCOMPLETE
1716 : COMPLETION_COMPLETE
;
1717 // In manual mode the icon is a toggle form...
1719 // If this completion state is used by the
1720 // conditional activities system, we need to turn
1722 if (!empty($CFG->enableavailability
) &&
1723 condition_info
::completion_value_used_as_condition($course, $mod)) {
1724 $extraclass = ' preventjs';
1729 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot
."/course/togglecompletion.php'><div>
1730 <input type='hidden' name='id' value='{$mod->id}' />
1731 <input type='hidden' name='sesskey' value='".sesskey()."' />
1732 <input type='hidden' name='completionstate' value='$newstate' />
1733 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1736 // In auto mode, or when editing, the icon is just an image
1737 echo "<span class='autocompletion'>";
1738 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1743 // If there is content AND a link, then display the content here
1744 // (AFTER any icons). Otherwise it was displayed before
1749 // Show availability information (for someone who isn't allowed to
1750 // see the activity itself, or for staff)
1751 if (!$mod->uservisible
) {
1752 echo '<div class="availabilityinfo">'.$mod->availableinfo
.'</div>';
1753 } else if ($canviewhidden && !empty($CFG->enableavailability
)) {
1754 $ci = new condition_info($mod);
1755 $fullinfo = $ci->get_full_information();
1757 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1758 ?
'userrestriction_visible'
1759 : 'userrestriction_hidden','condition',
1760 $fullinfo).'</div>';
1764 echo html_writer
::end_tag('div');
1765 echo html_writer
::end_tag('li')."\n";
1768 } elseif ($ismoving) {
1769 echo "<ul class=\"section\">\n";
1773 echo '<li><a title="'.$strmovefull.'"'.
1774 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.sesskey().'">'.
1775 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1776 ' alt="'.$strmovehere.'" /></a></li>
1779 if (!empty($section->sequence
) ||
$ismoving) {
1780 echo "</ul><!--class='section'-->\n\n";
1785 * Prints the menus to add activities and resources.
1787 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1788 global $CFG, $OUTPUT;
1790 // check to see if user can add menus
1791 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1795 $urlbase = "/course/mod.php?id=$course->id§ion=$section&sesskey=".sesskey().'&add=';
1797 $resources = array();
1798 $activities = array();
1800 foreach($modnames as $modname=>$modnamestr) {
1801 if (!course_allowed_module($course, $modname)) {
1805 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1806 if (!file_exists($libfile)) {
1809 include_once($libfile);
1810 $gettypesfunc = $modname.'_get_types';
1811 if (function_exists($gettypesfunc)) {
1812 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1813 if ($types = $gettypesfunc()) {
1817 foreach($types as $type) {
1818 if ($type->typestr
=== '--') {
1821 if (strpos($type->typestr
, '--') === 0) {
1822 $groupname = str_replace('--', '', $type->typestr
);
1825 $type->type
= str_replace('&', '&', $type->type
);
1826 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1827 $atype = MOD_CLASS_RESOURCE
;
1829 $menu[$urlbase.$type->type
] = $type->typestr
;
1831 if (!is_null($groupname)) {
1832 if ($atype == MOD_CLASS_RESOURCE
) {
1833 $resources[] = array($groupname=>$menu);
1835 $activities[] = array($groupname=>$menu);
1838 if ($atype == MOD_CLASS_RESOURCE
) {
1839 $resources = array_merge($resources, $menu);
1841 $activities = array_merge($activities, $menu);
1846 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1847 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1848 $resources[$urlbase.$modname] = $modnamestr;
1850 // all other archetypes are considered activity
1851 $activities[$urlbase.$modname] = $modnamestr;
1856 $straddactivity = get_string('addactivity');
1857 $straddresource = get_string('addresource');
1859 $output = '<div class="section_add_menus">';
1862 $output .= '<div class="horizontal">';
1865 if (!empty($resources)) {
1866 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1867 $select->set_help_icon('resources');
1868 $output .= $OUTPUT->render($select);
1871 if (!empty($activities)) {
1872 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1873 $select->set_help_icon('activities');
1874 $output .= $OUTPUT->render($select);
1878 $output .= '</div>';
1881 $output .= '</div>';
1891 * Return the course category context for the category with id $categoryid, except
1892 * that if $categoryid is 0, return the system context.
1894 * @param integer $categoryid a category id or 0.
1895 * @return object the corresponding context
1897 function get_category_or_system_context($categoryid) {
1899 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1901 return get_context_instance(CONTEXT_SYSTEM
);
1906 * Gets the child categories of a given courses category. Uses a static cache
1907 * to make repeat calls efficient.
1909 * @param int $parentid the id of a course category.
1910 * @return array all the child course categories.
1912 function get_child_categories($parentid) {
1913 static $allcategories = null;
1915 // only fill in this variable the first time
1916 if (null == $allcategories) {
1917 $allcategories = array();
1919 $categories = get_categories();
1920 foreach ($categories as $category) {
1921 if (empty($allcategories[$category->parent
])) {
1922 $allcategories[$category->parent
] = array();
1924 $allcategories[$category->parent
][] = $category;
1928 if (empty($allcategories[$parentid])) {
1931 return $allcategories[$parentid];
1936 * This function recursively travels the categories, building up a nice list
1937 * for display. It also makes an array that list all the parents for each
1940 * For example, if you have a tree of categories like:
1941 * Miscellaneous (id = 1)
1942 * Subcategory (id = 2)
1943 * Sub-subcategory (id = 4)
1944 * Other category (id = 3)
1945 * Then after calling this function you will have
1946 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1947 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1948 * 3 => 'Other category');
1949 * $parents = array(2 => array(1), 4 => array(1, 2));
1951 * If you specify $requiredcapability, then only categories where the current
1952 * user has that capability will be added to $list, although all categories
1953 * will still be added to $parents, and if you only have $requiredcapability
1954 * in a child category, not the parent, then the child catgegory will still be
1957 * If you specify the option $excluded, then that category, and all its children,
1958 * are omitted from the tree. This is useful when you are doing something like
1959 * moving categories, where you do not want to allow people to move a category
1960 * to be the child of itself.
1962 * @param array $list For output, accumulates an array categoryid => full category path name
1963 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1964 * @param string/array $requiredcapability if given, only categories where the current
1965 * user has this capability will be added to $list. Can also be an array of capabilities,
1966 * in which case they are all required.
1967 * @param integer $excludeid Omit this category and its children from the lists built.
1968 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1969 * @param string $path For internal use, as part of recursive calls.
1971 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1972 $excludeid = 0, $category = NULL, $path = "") {
1974 // initialize the arrays if needed
1975 if (!is_array($list)) {
1978 if (!is_array($parents)) {
1982 if (empty($category)) {
1983 // Start at the top level.
1984 $category = new stdClass
;
1987 // This is the excluded category, don't include it.
1988 if ($excludeid > 0 && $excludeid == $category->id
) {
1992 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
1993 $categoryname = format_string($category->name
, true, array('context' => $context));
1997 $path = $path.' / '.$categoryname;
1999 $path = $categoryname;
2002 // Add this category to $list, if the permissions check out.
2003 if (empty($requiredcapability)) {
2004 $list[$category->id
] = $path;
2007 $requiredcapability = (array)$requiredcapability;
2008 if (has_all_capabilities($requiredcapability, $context)) {
2009 $list[$category->id
] = $path;
2014 // Add all the children recursively, while updating the parents array.
2015 if ($categories = get_child_categories($category->id
)) {
2016 foreach ($categories as $cat) {
2017 if (!empty($category->id
)) {
2018 if (isset($parents[$category->id
])) {
2019 $parents[$cat->id
] = $parents[$category->id
];
2021 $parents[$cat->id
][] = $category->id
;
2023 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2029 * This function generates a structured array of courses and categories.
2031 * The depth of categories is limited by $CFG->maxcategorydepth however there
2032 * is no limit on the number of courses!
2034 * Suitable for use with the course renderers course_category_tree method:
2035 * $renderer = $PAGE->get_renderer('core','course');
2036 * echo $renderer->course_category_tree(get_course_category_tree());
2038 * @global moodle_database $DB
2042 function get_course_category_tree($id = 0, $depth = 0) {
2044 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
));
2045 $categories = get_child_categories($id);
2046 $categoryids = array();
2047 foreach ($categories as $key => &$category) {
2048 if (!$category->visible
&& !$viewhiddencats) {
2049 unset($categories[$key]);
2052 $categoryids[$category->id
] = $category;
2053 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
2054 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
2055 foreach ($subcategories as $subid=>$subcat) {
2056 $categoryids[$subid] = $subcat;
2058 $category->courses
= array();
2063 // This is a recursive call so return the required array
2064 return array($categories, $categoryids);
2067 // The depth is 0 this function has just been called so we can finish it off
2069 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
2070 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2072 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2076 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2077 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2078 // loop throught them
2079 foreach ($courses as $course) {
2080 if ($course->id
== SITEID
) {
2083 context_instance_preload($course);
2084 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
2085 $categoryids[$course->category
]->courses
[$course->id
] = $course;
2093 * Recursive function to print out all the categories in a nice format
2094 * with or without courses included
2096 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2099 // maxcategorydepth == 0 meant no limit
2100 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
2104 if (!$displaylist) {
2105 make_categories_list($displaylist, $parentslist);
2109 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
2110 print_category_info($category, $depth, $showcourses);
2112 return; // Don't bother printing children of invisible categories
2116 $category = new stdClass();
2117 $category->id
= "0";
2120 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
2121 $countcats = count($categories);
2125 foreach ($categories as $cat) {
2127 if ($count == $countcats) {
2130 $up = $first ?
false : true;
2131 $down = $last ?
false : true;
2134 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
2140 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2142 function make_categories_options() {
2143 make_categories_list($cats,$parents);
2144 foreach ($cats as $key => $value) {
2145 if (array_key_exists($key,$parents)) {
2146 if ($indent = count($parents[$key])) {
2147 for ($i = 0; $i < $indent; $i++
) {
2148 $cats[$key] = ' '.$cats[$key];
2157 * Prints the category info in indented fashion
2158 * This function is only used by print_whole_category_list() above
2160 function print_category_info($category, $depth=0, $showcourses = false) {
2161 global $CFG, $DB, $OUTPUT;
2163 $strsummary = get_string('summary');
2166 if (!$category->visible
) {
2167 $catlinkcss = array('class'=>'dimmed');
2169 static $coursecount = null;
2170 if (null === $coursecount) {
2171 // only need to check this once
2172 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
2175 if ($showcourses and $coursecount) {
2176 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2178 $catimage = " ";
2181 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2182 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2183 $fullname = format_string($category->name
, true, array('context' => $context));
2185 if ($showcourses and $coursecount) {
2186 echo '<div class="categorylist clearfix">';
2188 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
2189 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2190 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
2194 for ($i=0; $i< $depth; $i++
) {
2195 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
2201 echo html_writer
::tag('div', $html, array('class'=>'category'));
2202 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2204 // does the depth exceed maxcategorydepth
2205 // maxcategorydepth == 0 or unset meant no limit
2206 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
2207 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
2208 foreach ($courses as $course) {
2210 if (!$course->visible
) {
2211 $linkcss = array('class'=>'dimmed');
2214 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($course->fullname
), $linkcss);
2218 if ($icons = enrol_get_course_info_icons($course)) {
2219 foreach ($icons as $pix_icon) {
2220 $courseicon = $OUTPUT->render($pix_icon).' ';
2224 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
2226 if ($course->summary
) {
2227 $link = new moodle_url('/course/info.php?id='.$course->id
);
2228 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2229 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2230 array('title'=>$strsummary));
2232 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
2236 for ($i=0; $i <= $depth; $i++
) {
2237 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2238 $coursecontent = '';
2240 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
2245 echo '<div class="categorylist">';
2247 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2248 if (count($courses) > 0) {
2249 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2253 for ($i=0; $i< $depth; $i++
) {
2254 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
2261 echo html_writer
::tag('div', $html, array('class'=>'category'));
2262 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2268 * Print the buttons relating to course requests.
2270 * @param object $systemcontext the system context.
2272 function print_course_request_buttons($systemcontext) {
2273 global $CFG, $DB, $OUTPUT;
2274 if (empty($CFG->enablecourserequests
)) {
2277 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2278 /// Print a button to request a new course
2279 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2281 /// Print a button to manage pending requests
2282 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2283 $disabled = !$DB->record_exists('course_request', array());
2284 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2289 * Does the user have permission to edit things in this category?
2291 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2292 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2294 function can_edit_in_category($categoryid = 0) {
2295 $context = get_category_or_system_context($categoryid);
2296 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2300 * Prints the turn editing on/off button on course/index.php or course/category.php.
2302 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2303 * @return string HTML of the editing button, or empty string, if this user is not allowed
2306 function update_category_button($categoryid = 0) {
2307 global $CFG, $PAGE, $OUTPUT;
2309 // Check permissions.
2310 if (!can_edit_in_category($categoryid)) {
2314 // Work out the appropriate action.
2315 if ($PAGE->user_is_editing()) {
2316 $label = get_string('turneditingoff');
2319 $label = get_string('turneditingon');
2323 // Generate the button HTML.
2324 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2326 $options['id'] = $categoryid;
2327 $page = 'category.php';
2329 $page = 'index.php';
2331 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2335 * Category is 0 (for all courses) or an object
2337 function print_courses($category) {
2338 global $CFG, $OUTPUT;
2340 if (!is_object($category) && $category==0) {
2341 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2342 if (is_array($categories) && count($categories) == 1) {
2343 $category = array_shift($categories);
2344 $courses = get_courses_wmanagers($category->id
,
2346 array('summary','summaryformat'));
2348 $courses = get_courses_wmanagers('all',
2350 array('summary','summaryformat'));
2354 $courses = get_courses_wmanagers($category->id
,
2356 array('summary','summaryformat'));
2360 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
2361 foreach ($courses as $course) {
2362 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2363 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2364 echo html_writer
::start_tag('li');
2365 print_course($course);
2366 echo html_writer
::end_tag('li');
2369 echo html_writer
::end_tag('ul');
2371 echo $OUTPUT->heading(get_string("nocoursesyet"));
2372 $context = get_context_instance(CONTEXT_SYSTEM
);
2373 if (has_capability('moodle/course:create', $context)) {
2375 if (!empty($category->id
)) {
2376 $options['category'] = $category->id
;
2378 $options['category'] = $CFG->defaultrequestcategory
;
2380 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
2381 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2382 echo html_writer
::end_tag('div');
2388 * Print a description of a course, suitable for browsing in a list.
2390 * @param object $course the course object.
2391 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2393 function print_course($course, $highlightterms = '') {
2394 global $CFG, $USER, $DB, $OUTPUT;
2396 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2398 // Rewrite file URLs so that they are correct
2399 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
2401 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
2402 echo html_writer
::start_tag('div', array('class'=>'info'));
2403 echo html_writer
::start_tag('h3', array('class'=>'name'));
2405 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
2406 $linktext = highlight($highlightterms, format_string($course->fullname
));
2407 $linkparams = array('title'=>get_string('entercourse'));
2408 if (empty($course->visible
)) {
2409 $linkparams['class'] = 'dimmed';
2411 echo html_writer
::link($linkhref, $linktext, $linkparams);
2412 echo html_writer
::end_tag('h3');
2414 /// first find all roles that are supposed to be displayed
2415 if (!empty($CFG->coursecontact
)) {
2416 $managerroles = explode(',', $CFG->coursecontact
);
2417 $namesarray = array();
2418 if (isset($course->managers
)) {
2419 if (count($course->managers
)) {
2420 $rusers = $course->managers
;
2421 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2423 /// Rename some of the role names if needed
2424 if (isset($context)) {
2425 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2428 // keep a note of users displayed to eliminate duplicates
2429 $usersshown = array();
2430 foreach ($rusers as $ra) {
2432 // if we've already displayed user don't again
2433 if (in_array($ra->user
->id
,$usersshown)) {
2436 $usersshown[] = $ra->user
->id
;
2438 $fullname = fullname($ra->user
, $canviewfullnames);
2440 if (isset($aliasnames[$ra->roleid
])) {
2441 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2444 $namesarray[] = format_string($ra->rolename
).': '.
2445 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->user
->id
, 'course'=>SITEID
)), $fullname);
2449 $rusers = get_role_users($managerroles, $context,
2450 true, '', 'r.sortorder ASC, u.lastname ASC');
2451 if (is_array($rusers) && count($rusers)) {
2452 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2454 /// Rename some of the role names if needed
2455 if (isset($context)) {
2456 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2459 foreach ($rusers as $teacher) {
2460 $fullname = fullname($teacher, $canviewfullnames);
2462 /// Apply role names
2463 if (isset($aliasnames[$teacher->roleid
])) {
2464 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2467 $namesarray[] = format_string($teacher->rolename
).': '.
2468 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$teacher->id
, 'course'=>SITEID
)), $fullname);
2473 if (!empty($namesarray)) {
2474 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
2475 foreach ($namesarray as $name) {
2476 echo html_writer
::tag('li', $name);
2478 echo html_writer
::end_tag('ul');
2481 echo html_writer
::end_tag('div'); // End of info div
2483 echo html_writer
::start_tag('div', array('class'=>'summary'));
2484 $options = new stdClass();
2485 $options->noclean
= true;
2486 $options->para
= false;
2487 $options->overflowdiv
= true;
2488 if (!isset($course->summaryformat
)) {
2489 $course->summaryformat
= FORMAT_MOODLE
;
2491 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
2492 if ($icons = enrol_get_course_info_icons($course)) {
2493 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
2494 foreach ($icons as $icon) {
2495 echo $OUTPUT->render($icon);
2497 echo html_writer
::end_tag('div'); // End of enrolmenticons div
2499 echo html_writer
::end_tag('div'); // End of summary div
2500 echo html_writer
::end_tag('div'); // End of coursebox div
2504 * Prints custom user information on the home page.
2505 * Over time this can include all sorts of information
2507 function print_my_moodle() {
2508 global $USER, $CFG, $DB, $OUTPUT;
2510 if (!isloggedin() or isguestuser()) {
2511 print_error('nopermissions', '', '', 'See My Moodle');
2514 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2516 $rcourses = array();
2517 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2518 $rcourses = get_my_remotecourses($USER->id
);
2519 $rhosts = get_my_remotehosts();
2522 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2524 if (!empty($courses)) {
2525 echo '<ul class="unlist">';
2526 foreach ($courses as $course) {
2527 if ($course->id
== SITEID
) {
2531 print_course($course);
2538 if (!empty($rcourses)) {
2539 // at the IDP, we know of all the remote courses
2540 foreach ($rcourses as $course) {
2541 print_remote_course($course, "100%");
2543 } elseif (!empty($rhosts)) {
2544 // non-IDP, we know of all the remote servers, but not courses
2545 foreach ($rhosts as $host) {
2546 print_remote_host($host, "100%");
2552 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2553 echo "<table width=\"100%\"><tr><td align=\"center\">";
2554 print_course_search("", false, "short");
2555 echo "</td><td align=\"center\">";
2556 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2557 echo "</td></tr></table>\n";
2561 if ($DB->count_records("course_categories") > 1) {
2562 echo $OUTPUT->box_start("categorybox");
2563 print_whole_category_list();
2564 echo $OUTPUT->box_end();
2572 function print_course_search($value="", $return=false, $format="plain") {
2578 $id = 'coursesearch';
2584 $strsearchcourses= get_string("searchcourses");
2586 if ($format == 'plain') {
2587 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2588 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2589 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2590 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2591 $output .= '<input type="submit" value="'.get_string('go').'" />';
2592 $output .= '</fieldset></form>';
2593 } else if ($format == 'short') {
2594 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2595 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2596 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2597 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2598 $output .= '<input type="submit" value="'.get_string('go').'" />';
2599 $output .= '</fieldset></form>';
2600 } else if ($format == 'navbar') {
2601 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2602 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2603 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2604 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2605 $output .= '<input type="submit" value="'.get_string('go').'" />';
2606 $output .= '</fieldset></form>';
2615 function print_remote_course($course, $width="100%") {
2620 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2622 echo '<div class="coursebox remotecoursebox clearfix">';
2623 echo '<div class="info">';
2624 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2625 $linkcss.' href="'.$url.'">'
2626 . format_string($course->fullname
) .'</a><br />'
2627 . format_string($course->hostname
) . ' : '
2628 . format_string($course->cat_name
) . ' : '
2629 . format_string($course->shortname
). '</div>';
2630 echo '</div><div class="summary">';
2631 $options = new stdClass();
2632 $options->noclean
= true;
2633 $options->para
= false;
2634 $options->overflowdiv
= true;
2635 echo format_text($course->summary
, $course->summaryformat
, $options);
2640 function print_remote_host($host, $width="100%") {
2645 echo '<div class="coursebox clearfix">';
2646 echo '<div class="info">';
2647 echo '<div class="name">';
2648 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2649 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2650 . s($host['name']).'</a> - ';
2651 echo $host['count'] . ' ' . get_string('courses');
2658 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2660 function add_course_module($mod) {
2663 $mod->added
= time();
2666 return $DB->insert_record("course_modules", $mod);
2670 * Returns course section - creates new if does not exist yet.
2671 * @param int $relative section number
2672 * @param int $courseid
2673 * @return object $course_section object
2675 function get_course_section($section, $courseid) {
2678 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2681 $cw = new stdClass();
2682 $cw->course
= $courseid;
2683 $cw->section
= $section;
2685 $cw->summaryformat
= FORMAT_HTML
;
2687 $id = $DB->insert_record("course_sections", $cw);
2688 return $DB->get_record("course_sections", array("id"=>$id));
2691 * Given a full mod object with section and course already defined, adds this module to that section.
2693 * @param object $mod
2694 * @param int $beforemod An existing ID which we will insert the new module before
2695 * @return int The course_sections ID where the mod is inserted
2697 function add_mod_to_section($mod, $beforemod=NULL) {
2700 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course
, "section"=>$mod->section
))) {
2702 $section->sequence
= trim($section->sequence
);
2704 if (empty($section->sequence
)) {
2705 $newsequence = "$mod->coursemodule";
2707 } else if ($beforemod) {
2708 $modarray = explode(",", $section->sequence
);
2710 if ($key = array_keys($modarray, $beforemod->id
)) {
2711 $insertarray = array($mod->id
, $beforemod->id
);
2712 array_splice($modarray, $key[0], 1, $insertarray);
2713 $newsequence = implode(",", $modarray);
2715 } else { // Just tack it on the end anyway
2716 $newsequence = "$section->sequence,$mod->coursemodule";
2720 $newsequence = "$section->sequence,$mod->coursemodule";
2723 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2724 return $section->id
; // Return course_sections ID that was used.
2726 } else { // Insert a new record
2727 $section->course
= $mod->course
;
2728 $section->section
= $mod->section
;
2729 $section->summary
= "";
2730 $section->summaryformat
= FORMAT_HTML
;
2731 $section->sequence
= $mod->coursemodule
;
2732 return $DB->insert_record("course_sections", $section);
2736 function set_coursemodule_groupmode($id, $groupmode) {
2738 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2741 function set_coursemodule_idnumber($id, $idnumber) {
2743 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2747 * $prevstateoverrides = true will set the visibility of the course module
2748 * to what is defined in visibleold. This enables us to remember the current
2749 * visibility when making a whole section hidden, so that when we toggle
2750 * that section back to visible, we are able to return the visibility of
2751 * the course module back to what it was originally.
2753 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2755 require_once($CFG->libdir
.'/gradelib.php');
2757 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2760 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2763 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2764 foreach($events as $event) {
2773 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2774 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2776 foreach ($grade_items as $grade_item) {
2777 $grade_item->set_hidden(!$visible);
2781 if ($prevstateoverrides) {
2782 if ($visible == '0') {
2783 // Remember the current visible state so we can toggle this back.
2784 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id'=>$id));
2786 // Get the previous saved visible states.
2787 return $DB->set_field('course_modules', 'visible', $cm->visibleold
, array('id'=>$id));
2790 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2794 * Delete a course module and any associated data at the course level (events)
2795 * Until 1.5 this function simply marked a deleted flag ... now it
2796 * deletes it completely.
2799 function delete_course_module($id) {
2801 require_once($CFG->libdir
.'/gradelib.php');
2802 require_once($CFG->dirroot
.'/blog/lib.php');
2804 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2807 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
));
2808 //delete events from calendar
2809 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2810 foreach($events as $event) {
2811 delete_event($event->id
);
2814 //delete grade items, outcome items and grades attached to modules
2815 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2816 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2817 foreach ($grade_items as $grade_item) {
2818 $grade_item->delete('moddelete');
2821 // Delete completion and availability data; it is better to do this even if the
2822 // features are not turned on, in case they were turned on previously (these will be
2823 // very quick on an empty table)
2824 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2825 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2827 delete_context(CONTEXT_MODULE
, $cm->id
);
2828 return $DB->delete_records('course_modules', array('id'=>$cm->id
));
2831 function delete_mod_from_section($mod, $section) {
2834 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2836 $modarray = explode(",", $section->sequence
);
2838 if ($key = array_keys ($modarray, $mod)) {
2839 array_splice($modarray, $key[0], 1);
2840 $newsequence = implode(",", $modarray);
2841 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2851 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2853 * @param object $course
2854 * @param int $section
2855 * @param int $move (-1 or 1)
2857 function move_section($course, $section, $move) {
2858 /// Moves a whole course section up and down within the course
2865 $sectiondest = $section +
$move;
2867 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2871 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$section))) {
2875 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$sectiondest))) {
2879 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id
));
2880 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id
));
2882 // if the focus is on the section that is being moved, then move the focus along
2883 if (course_get_display($course->id
) == $section) {
2884 course_set_display($course->id
, $sectiondest);
2887 // Check for duplicates and fix order if needed.
2888 // There is a very rare case that some sections in the same course have the same section id.
2889 $sections = $DB->get_records('course_sections', array('course'=>$course->id
), 'section ASC');
2891 foreach ($sections as $section) {
2892 if ($section->section
!= $n) {
2893 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id
));
2901 * Moves a section within a course, from a position to another.
2902 * Be very careful: $section and $destination refer to section number,
2905 * @param object $course
2906 * @param int $section Section number (not id!!!)
2907 * @param int $destination
2908 * @return boolean Result
2910 function move_section_to($course, $section, $destination) {
2911 /// Moves a whole course section up and down within the course
2914 if (!$destination && $destination != 0) {
2918 if ($destination > $course->numsections
) {
2922 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2923 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2924 'section ASC, id ASC', 'id, section')) {
2928 $sections = reorder_sections($sections, $section, $destination);
2930 // Update all sections
2931 foreach ($sections as $id => $position) {
2932 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2935 // if the focus is on the section that is being moved, then move the focus along
2936 if (course_get_display($course->id
) == $section) {
2937 course_set_display($course->id
, $destination);
2943 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2944 * an original position number and a target position number, rebuilds the array so that the
2945 * move is made without any duplication of section positions.
2946 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2947 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2949 * @param array $sections
2950 * @param int $origin_position
2951 * @param int $target_position
2954 function reorder_sections($sections, $origin_position, $target_position) {
2955 if (!is_array($sections)) {
2959 // We can't move section position 0
2960 if ($origin_position < 1) {
2961 echo "We can't move section position 0";
2965 // Locate origin section in sections array
2966 if (!$origin_key = array_search($origin_position, $sections)) {
2967 echo "searched position not in sections array";
2968 return false; // searched position not in sections array
2971 // Extract origin section
2972 $origin_section = $sections[$origin_key];
2973 unset($sections[$origin_key]);
2975 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2977 $append_array = array();
2978 foreach ($sections as $id => $position) {
2980 $append_array[$id] = $position;
2981 unset($sections[$id]);
2983 if ($position == $target_position) {
2988 // Append moved section
2989 $sections[$origin_key] = $origin_section;
2991 // Append rest of array (if applicable)
2992 if (!empty($append_array)) {
2993 foreach ($append_array as $id => $position) {
2994 $sections[$id] = $position;
2998 // Renumber positions
3000 foreach ($sections as $id => $p) {
3001 $sections[$id] = $position;
3010 * Move the module object $mod to the specified $section
3011 * If $beforemod exists then that is the module
3012 * before which $modid should be inserted
3013 * All parameters are objects
3015 function moveto_module($mod, $section, $beforemod=NULL) {
3016 global $DB, $OUTPUT;
3018 /// Remove original module from original section
3019 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
3020 echo $OUTPUT->notification("Could not delete module from existing section");
3023 /// Update module itself if necessary
3025 if ($mod->section
!= $section->id
) {
3026 $mod->section
= $section->id
;
3027 $DB->update_record("course_modules", $mod);
3028 // if moving to a hidden section then hide module
3029 if (!$section->visible
) {
3030 set_coursemodule_visible($mod->id
, 0);
3034 /// Add the module into the new section
3036 $mod->course
= $section->course
;
3037 $mod->section
= $section->section
; // need relative reference
3038 $mod->coursemodule
= $mod->id
;
3040 if (! add_mod_to_section($mod, $beforemod)) {
3047 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
3048 global $CFG, $USER, $DB, $OUTPUT;
3053 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3054 // no permission to edit
3055 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
3060 $str->assign
= get_string("assignroles", 'role');
3061 $str->delete
= get_string("delete");
3062 $str->move
= get_string("move");
3063 $str->moveup
= get_string("moveup");
3064 $str->movedown
= get_string("movedown");
3065 $str->moveright
= get_string("moveright");
3066 $str->moveleft
= get_string("moveleft");
3067 $str->update
= get_string("update");
3068 $str->duplicate
= get_string("duplicate");
3069 $str->hide
= get_string("hide");
3070 $str->show
= get_string("show");
3071 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3072 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3073 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3074 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3075 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3076 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3077 $sesskey = sesskey();
3080 if ($section >= 0) {
3081 $section = '&sr='.$section; // Section return
3087 $path = $CFG->wwwroot
.'/course';
3091 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3092 if ($mod->visible
) {
3093 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
3094 '&sesskey='.$sesskey.$section.'"><img'.
3095 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
3096 ' alt="'.$str->hide
.'" /></a>'."\n";
3098 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
3099 '&sesskey='.$sesskey.$section.'"><img'.
3100 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
3101 ' alt="'.$str->show
.'" /></a>'."\n";
3107 if ($mod->groupmode
!== false) {
3108 if ($mod->groupmode
== SEPARATEGROUPS
) {
3109 $grouptitle = $str->groupsseparate
;
3110 $forcedgrouptitle = $str->forcedgroupsseparate
;
3111 $groupclass = 'editing_groupsseparate';
3112 $groupimage = $OUTPUT->pix_url('t/groups') . '';
3113 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
3114 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
3115 $grouptitle = $str->groupsvisible
;
3116 $forcedgrouptitle = $str->forcedgroupsvisible
;
3117 $groupclass = 'editing_groupsvisible';
3118 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
3119 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
3121 $grouptitle = $str->groupsnone
;
3122 $forcedgrouptitle = $str->forcedgroupsnone
;
3123 $groupclass = 'editing_groupsnone';
3124 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
3125 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
3127 if ($mod->groupmodelink
) {
3128 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.'" href="'.$grouplink.'">'.
3129 '<img src="'.$groupimage.'" class="iconsmall" '.
3130 'alt="'.$grouptitle.'" /></a>';
3132 $groupmode = '<img title="'.$forcedgrouptitle.'"'.
3133 ' src="'.$groupimage.'" class="iconsmall" '.
3134 'alt="'.$forcedgrouptitle.'" />';
3140 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3142 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
3143 '&sesskey='.$sesskey.$section.'"><img'.
3144 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
3145 ' alt="'.$str->move
.'" /></a>'."\n";
3147 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3148 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
3149 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
3150 ' alt="'.$str->moveup
.'" /></a>'."\n".
3151 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3152 '&move=1&sesskey='.$sesskey.$section.'"><img'.
3153 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
3154 ' alt="'.$str->movedown
.'" /></a>'."\n";
3161 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3163 if (right_to_left()) { // Exchange arrows on RTL
3164 $rightarrow = 't/left';
3165 $leftarrow = 't/right';
3167 $rightarrow = 't/right';
3168 $leftarrow = 't/left';
3172 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3173 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
3174 ' src="'.$OUTPUT->pix_url($leftarrow).'" class="iconsmall" '.
3175 ' alt="'.$str->moveleft
.'" /></a>'."\n";
3178 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3179 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
3180 ' src="'.$OUTPUT->pix_url($rightarrow).'" class="iconsmall" '.
3181 ' alt="'.$str->moveright
.'" /></a>'."\n";
3184 if (has_capability('moodle/role:assign', $modcontext)){
3185 $context = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3186 $assign = '<a class="editing_assign" title="'.$str->assign
.'" href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.
3187 $context->id
.'"><img src="'.$OUTPUT->pix_url('i/roles') . '" alt="'.$str->assign
.'" class="iconsmall"/></a>';
3192 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3193 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3194 if (has_all_capabilities($dupecaps, get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3195 $duplicatemodule = '<a class="editing_duplicate" title="'.$str->duplicate
.'" href="'.$path.'/mod.php?duplicate='.$mod->id
.
3196 '&sesskey='.$sesskey.$section.'"><img'.
3197 ' src="'.$OUTPUT->pix_url('t/copy') . '" class="iconsmall" '.
3198 ' alt="'.$str->duplicate
.'" /></a>'."\n";
3200 $duplicatemodule = '';
3203 return '<span class="commands">'."\n".$leftright.$move.
3204 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
3205 '&sesskey='.$sesskey.$section.'"><img'.
3206 ' src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" '.
3207 ' alt="'.$str->update
.'" /></a>'."\n".
3209 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
3210 '&sesskey='.$sesskey.$section.'"><img'.
3211 ' src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" '.
3212 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
3216 * given a course object with shortname & fullname, this function will
3217 * truncate the the number of chars allowed and add ... if it was too long
3219 function course_format_name ($course,$max=100) {
3221 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3222 $shortname = format_string($course->shortname
, true, array('context' => $context));
3223 $fullname = format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
3225 $str = $shortname.': '. $fullname;
3226 if (strlen($str) <= $max) {
3229 return $textlib->substr($str, 0, $max-3).'...';
3233 function update_restricted_mods($course, $mods) {
3236 /// Delete all the current restricted list
3237 $DB->delete_records('course_allowed_modules', array('course'=>$course->id
));
3239 if (empty($course->restrictmodules
)) {
3240 return; // We're done
3243 /// Insert the new list of restricted mods
3244 foreach ($mods as $mod) {
3246 continue; // this is the 'allow none' option
3248 $am = new stdClass();
3249 $am->course
= $course->id
;
3251 $DB->insert_record('course_allowed_modules',$am);
3256 * This function will take an int (module id) or a string (module name)
3257 * and return true or false, whether it's allowed in the given course (object)
3258 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3259 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3262 function course_allowed_module($course,$mod) {
3265 if (empty($course->restrictmodules
)) {
3269 // Admins and admin-like people who can edit everything can also add anything.
3270 // Originally there was a course:update test only, but it did not match the test in course edit form
3271 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3275 if (is_numeric($mod)) {
3277 } else if (is_string($mod)) {
3278 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3280 if (empty($modid)) {
3284 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id
, 'module'=>$modid));
3288 * Recursively delete category including all subcategories and courses.
3289 * @param stdClass $category
3290 * @param boolean $showfeedback display some notices
3291 * @return array return deleted courses
3293 function category_delete_full($category, $showfeedback=true) {
3295 require_once($CFG->libdir
.'/gradelib.php');
3296 require_once($CFG->libdir
.'/questionlib.php');
3297 require_once($CFG->dirroot
.'/cohort/lib.php');
3299 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3300 foreach ($children as $childcat) {
3301 category_delete_full($childcat, $showfeedback);
3305 $deletedcourses = array();
3306 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
3307 foreach ($courses as $course) {
3308 if (!delete_course($course, false)) {
3309 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
3311 $deletedcourses[] = $course;
3315 // move or delete cohorts in this context
3316 cohort_delete_category($category);
3318 // now delete anything that may depend on course category context
3319 grade_course_category_delete($category->id
, 0, $showfeedback);
3320 if (!question_delete_course_category($category, 0, $showfeedback)) {
3321 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
3324 // finally delete the category and it's context
3325 $DB->delete_records('course_categories', array('id'=>$category->id
));
3326 delete_context(CONTEXT_COURSECAT
, $category->id
);
3328 events_trigger('course_category_deleted', $category);
3330 return $deletedcourses;
3334 * Delete category, but move contents to another category.
3335 * @param object $ccategory
3336 * @param int $newparentid category id
3337 * @return bool status
3339 function category_delete_move($category, $newparentid, $showfeedback=true) {
3340 global $CFG, $DB, $OUTPUT;
3341 require_once($CFG->libdir
.'/gradelib.php');
3342 require_once($CFG->libdir
.'/questionlib.php');
3343 require_once($CFG->dirroot
.'/cohort/lib.php');
3345 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3349 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3350 foreach ($children as $childcat) {
3351 move_category($childcat, $newparentcat);
3355 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
3356 if (!move_courses(array_keys($courses), $newparentid)) {
3357 echo $OUTPUT->notification("Error moving courses");
3360 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3363 // move or delete cohorts in this context
3364 cohort_delete_category($category);
3366 // now delete anything that may depend on course category context
3367 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3368 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3369 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3373 // finally delete the category and it's context
3374 $DB->delete_records('course_categories', array('id'=>$category->id
));
3375 delete_context(CONTEXT_COURSECAT
, $category->id
);
3377 events_trigger('course_category_deleted', $category);
3379 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3385 * Efficiently moves many courses around while maintaining
3386 * sortorder in order.
3388 * @param array $courseids is an array of course ids
3389 * @param int $categoryid
3390 * @return bool success
3392 function move_courses($courseids, $categoryid) {
3393 global $CFG, $DB, $OUTPUT;
3395 if (empty($courseids)) {
3400 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3404 $courseids = array_reverse($courseids);
3405 $newparent = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3408 foreach ($courseids as $courseid) {
3409 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3410 $course = new stdClass();
3411 $course->id
= $courseid;
3412 $course->category
= $category->id
;
3413 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
3414 if ($category->visible
== 0) {
3415 // hide the course when moving into hidden category,
3416 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3417 $course->visible
= 0;
3420 $DB->update_record('course', $course);
3422 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3423 context_moved($context, $newparent);
3426 fix_course_sortorder();
3432 * Hide course category and child course and subcategories
3433 * @param stdClass $category
3436 function course_category_hide($category) {
3439 $category->visible
= 0;
3440 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
3441 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
3442 $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
3443 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
3444 // get all child categories and hide too
3445 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3446 foreach ($subcats as $cat) {
3447 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
3448 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
3449 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
3450 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
3456 * Show course category and child course and subcategories
3457 * @param stdClass $category
3460 function course_category_show($category) {
3463 $category->visible
= 1;
3464 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
3465 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
3466 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
3467 // get all child categories and unhide too
3468 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3469 foreach ($subcats as $cat) {
3470 if ($cat->visibleold
) {
3471 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
3473 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
3479 * Efficiently moves a category - NOTE that this can have
3480 * a huge impact access-control-wise...
3482 function move_category($category, $newparentcat) {
3485 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3488 if (empty($newparentcat->id
)) {
3489 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id
));
3491 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3494 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id'=>$category->id
));
3495 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3497 if (!$newparentcat->visible
and $category->visible
) {
3498 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3503 context_moved($context, $newparent);
3505 // now make it last in new category
3506 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
3508 // and fix the sortorders
3509 fix_course_sortorder();
3512 course_category_hide($category);
3517 * Returns the display name of the given section that the course prefers.
3519 * This function utilizes a callback that can be implemented within the course
3520 * formats lib.php file to customize the display name that is used to reference
3523 * By default (if callback is not defined) the method
3524 * {@see get_numeric_section_name} is called instead.
3526 * @param stdClass $course The course to get the section name for
3527 * @param stdClass $section Section object from database
3528 * @return Display name that the course format prefers, e.g. "Week 2"
3530 * @see get_generic_section_name
3532 function get_section_name(stdClass
$course, stdClass
$section) {
3535 /// Inelegant hack for bug 3408
3536 if ($course->format
== 'site') {
3537 return get_string('site');
3540 // Use course formatter callback if it exists
3541 $namingfile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3542 $namingfunction = 'callback_'.$course->format
.'_get_section_name';
3543 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3544 require_once $namingfile;
3546 if (function_exists($namingfunction)) {
3547 return $namingfunction($course, $section);
3550 // else, default behavior:
3551 return get_generic_section_name($course->format
, $section);
3555 * Gets the generic section name for a courses section.
3557 * @param string $format Course format ID e.g. 'weeks' $course->format
3558 * @param stdClass $section Section object from database
3559 * @return Display name that the course format prefers, e.g. "Week 2"
3561 function get_generic_section_name($format, stdClass
$section) {
3562 return get_string('sectionname', "format_$format") . ' ' . $section->section
;
3566 function course_format_uses_sections($format) {
3569 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3570 $featurefunction = 'callback_'.$format.'_uses_sections';
3571 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3572 require_once $featurefile;
3574 if (function_exists($featurefunction)) {
3575 return $featurefunction();
3582 * Returns the information about the ajax support in the given source format
3584 * The returned object's property (boolean)capable indicates that
3585 * the course format supports Moodle course ajax features.
3586 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3588 * @param string $format
3591 function course_format_ajax_support($format) {
3594 // set up default values
3595 $ajaxsupport = new stdClass();
3596 $ajaxsupport->capable
= false;
3597 $ajaxsupport->testedbrowsers
= array();
3599 // get the information from the course format library
3600 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3601 $featurefunction = 'callback_'.$format.'_ajax_support';
3602 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3603 require_once $featurefile;
3605 if (function_exists($featurefunction)) {
3606 $formatsupport = $featurefunction();
3607 if (isset($formatsupport->capable
)) {
3608 $ajaxsupport->capable
= $formatsupport->capable
;
3610 if (is_array($formatsupport->testedbrowsers
)) {
3611 $ajaxsupport->testedbrowsers
= $formatsupport->testedbrowsers
;
3615 return $ajaxsupport;
3619 * Can the current user delete this course?
3620 * Course creators have exception,
3621 * 1 day after the creation they can sill delete the course.
3622 * @param int $courseid
3625 function can_delete_course($courseid) {
3628 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3630 if (has_capability('moodle/course:delete', $context)) {
3634 // hack: now try to find out if creator created this course recently (1 day)
3635 if (!has_capability('moodle/course:create', $context)) {
3639 $since = time() - 60*60*24;
3641 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3642 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3644 return $DB->record_exists_select('log', $select, $params);
3648 * Save the Your name for 'Some role' strings.
3650 * @param integer $courseid the id of this course.
3651 * @param array $data the data that came from the course settings form.
3653 function save_local_role_names($courseid, $data) {
3655 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3657 foreach ($data as $fieldname => $value) {
3658 if (strpos($fieldname, 'role_') !== 0) {
3661 list($ignored, $roleid) = explode('_', $fieldname);
3663 // make up our mind whether we want to delete, update or insert
3665 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3667 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3668 $rolename->name
= $value;
3669 $DB->update_record('role_names', $rolename);
3672 $rolename = new stdClass
;
3673 $rolename->contextid
= $context->id
;
3674 $rolename->roleid
= $roleid;
3675 $rolename->name
= $value;
3676 $DB->insert_record('role_names', $rolename);
3682 * Create a course and either return a $course object
3684 * Please note this functions does not verify any access control,
3685 * the calling code is responsible for all validation (usually it is the form definition).
3687 * @param array $editoroptions course description editor options
3688 * @param object $data - all the data needed for an entry in the 'course' table
3689 * @return object new course instance
3691 function create_course($data, $editoroptions = NULL) {
3694 //check the categoryid - must be given for all new courses
3695 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3697 //check if the shortname already exist
3698 if (!empty($data->shortname
)) {
3699 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3700 throw new moodle_exception('shortnametaken');
3704 //check if the id number already exist
3705 if (!empty($data->idnumber
)) {
3706 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3707 throw new moodle_exception('idnumbertaken');
3711 $data->timecreated
= time();
3712 $data->timemodified
= $data->timecreated
;
3714 // place at beginning of any category
3715 $data->sortorder
= 0;
3717 if ($editoroptions) {
3718 // summary text is updated later, we need context to store the files first
3719 $data->summary
= '';
3720 $data->summary_format
= FORMAT_HTML
;
3723 if (!isset($data->visible
)) {
3724 // data not from form, add missing visibility info
3725 $data->visible
= $category->visible
;
3727 $data->visibleold
= $data->visible
;
3729 $newcourseid = $DB->insert_record('course', $data);
3730 $context = get_context_instance(CONTEXT_COURSE
, $newcourseid, MUST_EXIST
);
3732 if ($editoroptions) {
3733 // Save the files used in the summary editor and store
3734 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3735 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3736 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3739 $course = $DB->get_record('course', array('id'=>$newcourseid));
3742 blocks_add_default_course_blocks($course);
3744 $section = new stdClass();
3745 $section->course
= $course->id
; // Create a default section.
3746 $section->section
= 0;
3747 $section->summaryformat
= FORMAT_HTML
;
3748 $DB->insert_record('course_sections', $section);
3750 fix_course_sortorder();
3752 // update module restrictions
3753 if ($course->restrictmodules
) {
3754 if (isset($data->allowedmods
)) {
3755 update_restricted_mods($course, $data->allowedmods
);
3757 if (!empty($CFG->defaultallowedmodules
)) {
3758 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules
));
3763 // new context created - better mark it as dirty
3764 mark_context_dirty($context->path
);
3766 // Save any custom role names.
3767 save_local_role_names($course->id
, (array)$data);
3769 // set up enrolments
3770 enrol_course_updated(true, $course, $data);
3772 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3775 events_trigger('course_created', $course);
3783 * Please note this functions does not verify any access control,
3784 * the calling code is responsible for all validation (usually it is the form definition).
3786 * @param object $data - all the data needed for an entry in the 'course' table
3787 * @param array $editoroptions course description editor options
3790 function update_course($data, $editoroptions = NULL) {
3793 $data->timemodified
= time();
3795 $oldcourse = $DB->get_record('course', array('id'=>$data->id
), '*', MUST_EXIST
);
3796 $context = get_context_instance(CONTEXT_COURSE
, $oldcourse->id
);
3798 if ($editoroptions) {
3799 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3802 if (!isset($data->category
) or empty($data->category
)) {
3803 // prevent nulls and 0 in category field
3804 unset($data->category
);
3806 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3808 if (!isset($data->visible
)) {
3809 // data not from form, add missing visibility info
3810 $data->visible
= $oldcourse->visible
;
3813 if ($data->visible
!= $oldcourse->visible
) {
3814 // reset the visibleold flag when manually hiding/unhiding course
3815 $data->visibleold
= $data->visible
;
3818 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3819 if (empty($newcategory->visible
)) {
3820 // make sure when moving into hidden category the course is hidden automatically
3826 // Update with the new data
3827 $DB->update_record('course', $data);
3829 $course = $DB->get_record('course', array('id'=>$data->id
));
3832 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3833 context_moved($context, $newparent);
3836 fix_course_sortorder();
3838 // Test for and remove blocks which aren't appropriate anymore
3839 blocks_remove_inappropriate($course);
3841 // update module restrictions
3842 if (isset($data->allowedmods
)) {
3843 update_restricted_mods($course, $data->allowedmods
);
3846 // Save any custom role names.
3847 save_local_role_names($course->id
, $data);
3849 // update enrol settings
3850 enrol_course_updated(false, $course, $data);
3852 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3855 events_trigger('course_updated', $course);
3859 * Average number of participants
3862 function average_number_of_participants() {
3865 //count total of enrolments for visible course (except front page)
3866 $sql = 'SELECT COUNT(*) FROM (
3867 SELECT DISTINCT ue.userid, e.courseid
3868 FROM {user_enrolments} ue, {enrol} e, {course} c
3869 WHERE ue.enrolid = e.id
3870 AND e.courseid <> :siteid
3871 AND c.id = e.courseid
3872 AND c.visible = 1) as total';
3873 $params = array('siteid' => $SITE->id
);
3874 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3877 //count total of visible courses (minus front page)
3878 $coursetotal = $DB->count_records('course', array('visible' => 1));
3879 $coursetotal = $coursetotal - 1 ;
3881 //average of enrolment
3882 if (empty($coursetotal)) {
3883 $participantaverage = 0;
3885 $participantaverage = $enrolmenttotal / $coursetotal;
3888 return $participantaverage;
3892 * Average number of course modules
3895 function average_number_of_courses_modules() {
3898 //count total of visible course module (except front page)
3899 $sql = 'SELECT COUNT(*) FROM (
3900 SELECT cm.course, cm.module
3901 FROM {course} c, {course_modules} cm
3902 WHERE c.id = cm.course
3905 AND c.visible = 1) as total';
3906 $params = array('siteid' => $SITE->id
);
3907 $moduletotal = $DB->count_records_sql($sql, $params);
3910 //count total of visible courses (minus front page)
3911 $coursetotal = $DB->count_records('course', array('visible' => 1));
3912 $coursetotal = $coursetotal - 1 ;
3914 //average of course module
3915 if (empty($coursetotal)) {
3916 $coursemoduleaverage = 0;
3918 $coursemoduleaverage = $moduletotal / $coursetotal;
3921 return $coursemoduleaverage;
3925 * This class pertains to course requests and contains methods associated with
3926 * create, approving, and removing course requests.
3928 * Please note we do not allow embedded images here because there is no context
3929 * to store them with proper access control.
3931 * @copyright 2009 Sam Hemelryk
3932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3935 * @property-read int $id
3936 * @property-read string $fullname
3937 * @property-read string $shortname
3938 * @property-read string $summary
3939 * @property-read int $summaryformat
3940 * @property-read int $summarytrust
3941 * @property-read string $reason
3942 * @property-read int $requester
3944 class course_request
{
3947 * This is the stdClass that stores the properties for the course request
3948 * and is externally accessed through the __get magic method
3951 protected $properties;
3954 * An array of options for the summary editor used by course request forms.
3955 * This is initially set by {@link summary_editor_options()}
3959 protected static $summaryeditoroptions;
3962 * Static function to prepare the summary editor for working with a course
3966 * @param null|stdClass $data Optional, an object containing the default values
3967 * for the form, these may be modified when preparing the
3968 * editor so this should be called before creating the form
3969 * @return stdClass An object that can be used to set the default values for
3972 public static function prepare($data=null) {
3973 if ($data === null) {
3974 $data = new stdClass
;
3976 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
3981 * Static function to create a new course request when passed an array of properties
3984 * This function also handles saving any files that may have been used in the editor
3987 * @param stdClass $data
3988 * @return course_request The newly created course request
3990 public static function create($data) {
3991 global $USER, $DB, $CFG;
3992 $data->requester
= $USER->id
;
3994 // Summary is a required field so copy the text over
3995 $data->summary
= $data->summary_editor
['text'];
3996 $data->summaryformat
= $data->summary_editor
['format'];
3998 $data->id
= $DB->insert_record('course_request', $data);
4000 // Create a new course_request object and return it
4001 $request = new course_request($data);
4003 // Notify the admin if required.
4004 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
4007 $a->link
= "$CFG->wwwroot/course/pending.php";
4008 $a->user
= fullname($USER);
4009 $subject = get_string('courserequest');
4010 $message = get_string('courserequestnotifyemail', 'admin', $a);
4011 foreach ($users as $user) {
4012 $request->notify($user, $USER, 'courserequested', $subject, $message);
4020 * Returns an array of options to use with a summary editor
4022 * @uses course_request::$summaryeditoroptions
4023 * @return array An array of options to use with the editor
4025 public static function summary_editor_options() {
4027 if (self
::$summaryeditoroptions === null) {
4028 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4030 return self
::$summaryeditoroptions;
4034 * Loads the properties for this course request object. Id is required and if
4035 * only id is provided then we load the rest of the properties from the database
4037 * @param stdClass|int $properties Either an object containing properties
4038 * or the course_request id to load
4040 public function __construct($properties) {
4042 if (empty($properties->id
)) {
4043 if (empty($properties)) {
4044 throw new coding_exception('You must provide a course request id when creating a course_request object');
4047 $properties = new stdClass
;
4048 $properties->id
= (int)$id;
4051 if (empty($properties->requester
)) {
4052 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
4053 print_error('unknowncourserequest');
4056 $this->properties
= $properties;
4058 $this->properties
->collision
= null;
4062 * Returns the requested property
4064 * @param string $key
4067 public function __get($key) {
4068 return $this->properties
->$key;
4072 * Override this to ensure empty($request->blah) calls return a reliable answer...
4074 * This is required because we define the __get method
4077 * @return bool True is it not empty, false otherwise
4079 public function __isset($key) {
4080 return (!empty($this->properties
->$key));
4084 * Returns the user who requested this course
4086 * Uses a static var to cache the results and cut down the number of db queries
4088 * @staticvar array $requesters An array of cached users
4089 * @return stdClass The user who requested the course
4091 public function get_requester() {
4093 static $requesters= array();
4094 if (!array_key_exists($this->properties
->requester
, $requesters)) {
4095 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
4097 return $requesters[$this->properties
->requester
];
4101 * Checks that the shortname used by the course does not conflict with any other
4102 * courses that exist
4104 * @param string|null $shortnamemark The string to append to the requests shortname
4105 * should a conflict be found
4106 * @return bool true is there is a conflict, false otherwise
4108 public function check_shortname_collision($shortnamemark = '[*]') {
4111 if ($this->properties
->collision
!== null) {
4112 return $this->properties
->collision
;
4115 if (empty($this->properties
->shortname
)) {
4116 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
4117 $this->properties
->collision
= false;
4118 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
4119 if (!empty($shortnamemark)) {
4120 $this->properties
->shortname
.= ' '.$shortnamemark;
4122 $this->properties
->collision
= true;
4124 $this->properties
->collision
= false;
4126 return $this->properties
->collision
;
4130 * This function approves the request turning it into a course
4132 * This function converts the course request into a course, at the same time
4133 * transferring any files used in the summary to the new course and then removing
4134 * the course request and the files associated with it.
4136 * @return int The id of the course that was created from this request
4138 public function approve() {
4139 global $CFG, $DB, $USER;
4141 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
4143 $category = get_course_category($CFG->defaultrequestcategory
);
4144 $courseconfig = get_config('moodlecourse');
4146 // Transfer appropriate settings
4147 $data = clone($this->properties
);
4149 unset($data->reason
);
4150 unset($data->requester
);
4153 $data->category
= $category->id
;
4154 $data->sortorder
= $category->sortorder
; // place as the first in category
4156 // Set misc settings
4157 $data->requested
= 1;
4158 if (!empty($CFG->restrictmodulesfor
) && $CFG->restrictmodulesfor
!= 'none' && !empty($CFG->restrictbydefault
)) {
4159 $data->restrictmodules
= 1;
4162 // Apply course default settings
4163 $data->format
= $courseconfig->format
;
4164 $data->numsections
= $courseconfig->numsections
;
4165 $data->hiddensections
= $courseconfig->hiddensections
;
4166 $data->newsitems
= $courseconfig->newsitems
;
4167 $data->showgrades
= $courseconfig->showgrades
;
4168 $data->showreports
= $courseconfig->showreports
;
4169 $data->maxbytes
= $courseconfig->maxbytes
;
4170 $data->groupmode
= $courseconfig->groupmode
;
4171 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
4172 $data->visible
= $courseconfig->visible
;
4173 $data->visibleold
= $data->visible
;
4174 $data->lang
= $courseconfig->lang
;
4176 $course = create_course($data);
4177 $context = get_context_instance(CONTEXT_COURSE
, $course->id
, MUST_EXIST
);
4179 // add enrol instances
4180 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
4181 if ($manual = enrol_get_plugin('manual')) {
4182 $manual->add_default_instance($course);
4186 // enrol the requester as teacher if necessary
4187 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4188 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
4193 $a = new stdClass();
4194 $a->name
= format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
4195 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
4196 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4202 * Reject a course request
4204 * This function rejects a course request, emailing the requesting user the
4205 * provided notice and then removing the request from the database
4207 * @param string $notice The message to display to the user
4209 public function reject($notice) {
4211 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
4212 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4217 * Deletes the course request and any associated files
4219 public function delete() {
4221 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
4225 * Send a message from one user to another using events_trigger
4227 * @param object $touser
4228 * @param object $fromuser
4229 * @param string $name
4230 * @param string $subject
4231 * @param string $message
4233 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4234 $eventdata = new stdClass();
4235 $eventdata->component
= 'moodle';
4236 $eventdata->name
= $name;
4237 $eventdata->userfrom
= $fromuser;
4238 $eventdata->userto
= $touser;
4239 $eventdata->subject
= $subject;
4240 $eventdata->fullmessage
= $message;
4241 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
4242 $eventdata->fullmessagehtml
= '';
4243 $eventdata->smallmessage
= '';
4244 $eventdata->notification
= 1;
4245 message_send($eventdata);
4250 * Return a list of page types
4251 * @param string $pagetype current page type
4252 * @param stdClass $parentcontext Block's parent context
4253 * @param stdClass $currentcontext Current context of block
4255 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4256 // if above course context ,display all course fomats
4257 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
4258 if ($course->id
== SITEID
) {
4259 return array('*'=>get_string('page-x', 'pagetype'));
4261 return array('*'=>get_string('page-x', 'pagetype'),
4262 'course-*'=>get_string('page-course-x', 'pagetype'),
4263 'course-view-*'=>get_string('page-course-view-x', 'pagetype')