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');
31 require_once($CFG->dirroot
.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot
.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1'); // Not used. TODO MDL-38832 remove
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3'); // Not used. TODO MDL-38832 remove
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGEENROLLEDCOURSELIST', '5');
52 define('FRONTPAGEALLCOURSELIST', '6');
53 define('FRONTPAGECOURSESEARCH', '7');
54 define('FRONTPAGECOURSELIMIT', 200); // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage. TODO MDL-38832 remove
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 function make_log_url($module, $url) {
64 if (strpos($url, 'report/') === 0) {
65 // there is only one report type, course reports are deprecated
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
79 $url = "/course/$url";
84 $url = "/$module/$url";
97 $url = "/message/$url";
100 $url = "/notes/$url";
109 $url = "/grade/$url";
112 $url = "/mod/$module/$url";
116 //now let's sanitise urls - there might be some ugly nasties:-(
117 $parts = explode('?', $url);
118 $script = array_shift($parts);
119 if (strpos($script, 'http') === 0) {
120 $script = clean_param($script, PARAM_URL
);
122 $script = clean_param($script, PARAM_PATH
);
127 $query = implode('', $parts);
128 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
129 $parts = explode('&', $query);
130 $eq = urlencode('=');
131 foreach ($parts as $key=>$part) {
132 $part = urlencode(urldecode($part));
133 $part = str_replace($eq, '=', $part);
134 $parts[$key] = $part;
136 $query = '?'.implode('&', $parts);
139 return $script.$query;
143 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
144 $modname="", $modid=0, $modaction="", $groupid=0) {
147 // It is assumed that $date is the GMT time of midnight for that day,
148 // and so the next 86400 seconds worth of logs are printed.
150 /// Setup for group handling.
152 // TODO: I don't understand group/context/etc. enough to be able to do
153 // something interesting with it here
154 // What is the context of a remote course?
156 /// If the group mode is separate, and this user does not have editing privileges,
157 /// then only the user's group can be viewed.
158 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
159 // $groupid = get_current_group($course->id);
161 /// If this course doesn't have groups, no groupid can be specified.
162 //else if (!$course->groupmode) {
171 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
173 LEFT JOIN {user} u ON l.userid = u.id
177 $where .= "l.hostid = :hostid";
178 $params['hostid'] = $hostid;
180 // TODO: Is 1 really a magic number referring to the sitename?
181 if ($course != SITEID ||
$modid != 0) {
182 $where .= " AND l.course=:courseid";
183 $params['courseid'] = $course;
187 $where .= " AND l.module = :modname";
188 $params['modname'] = $modname;
191 if ('site_errors' === $modid) {
192 $where .= " AND ( l.action='error' OR l.action='infected' )";
194 //TODO: This assumes that modids are the same across sites... probably
196 $where .= " AND l.cmid = :modid";
197 $params['modid'] = $modid;
201 $firstletter = substr($modaction, 0, 1);
202 if ($firstletter == '-') {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
204 $params['modaction'] = '%'.substr($modaction, 1).'%';
206 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
207 $params['modaction'] = '%'.$modaction.'%';
212 $where .= " AND l.userid = :user";
213 $params['user'] = $user;
217 $enddate = $date +
86400;
218 $where .= " AND l.time > :date AND l.time < :enddate";
219 $params['date'] = $date;
220 $params['enddate'] = $enddate;
224 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
225 if(!empty($result['totalcount'])) {
226 $where .= " ORDER BY $order";
227 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
229 $result['logs'] = array();
234 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
235 $modname="", $modid=0, $modaction="", $groupid=0) {
236 global $DB, $SESSION, $USER;
237 // It is assumed that $date is the GMT time of midnight for that day,
238 // and so the next 86400 seconds worth of logs are printed.
240 /// Setup for group handling.
242 /// If the group mode is separate, and this user does not have editing privileges,
243 /// then only the user's group can be viewed.
244 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', context_course
::instance($course->id
))) {
245 if (isset($SESSION->currentgroup
[$course->id
])) {
246 $groupid = $SESSION->currentgroup
[$course->id
];
248 $groupid = groups_get_all_groups($course->id
, $USER->id
);
249 if (is_array($groupid)) {
250 $groupid = array_shift(array_keys($groupid));
251 $SESSION->currentgroup
[$course->id
] = $groupid;
257 /// If this course doesn't have groups, no groupid can be specified.
258 else if (!$course->groupmode
) {
265 if ($course->id
!= SITEID ||
$modid != 0) {
266 $joins[] = "l.course = :courseid";
267 $params['courseid'] = $course->id
;
271 $joins[] = "l.module = :modname";
272 $params['modname'] = $modname;
275 if ('site_errors' === $modid) {
276 $joins[] = "( l.action='error' OR l.action='infected' )";
278 $joins[] = "l.cmid = :modid";
279 $params['modid'] = $modid;
283 $firstletter = substr($modaction, 0, 1);
284 if ($firstletter == '-') {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
286 $params['modaction'] = '%'.substr($modaction, 1).'%';
288 $joins[] = $DB->sql_like('l.action', ':modaction', false);
289 $params['modaction'] = '%'.$modaction.'%';
294 /// Getting all members of a group.
295 if ($groupid and !$user) {
296 if ($gusers = groups_get_members($groupid)) {
297 $gusers = array_keys($gusers);
298 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
300 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
304 $joins[] = "l.userid = :userid";
305 $params['userid'] = $user;
309 $enddate = $date +
86400;
310 $joins[] = "l.time > :date AND l.time < :enddate";
311 $params['date'] = $date;
312 $params['enddate'] = $enddate;
315 $selector = implode(' AND ', $joins);
317 $totalcount = 0; // Initialise
319 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
320 $result['totalcount'] = $totalcount;
325 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
326 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
328 global $CFG, $DB, $OUTPUT;
330 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
331 $modname, $modid, $modaction, $groupid)) {
332 echo $OUTPUT->notification("No logs found!");
333 echo $OUTPUT->footer();
339 if ($course->id
== SITEID
) {
341 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
342 foreach ($ccc as $cc) {
343 $courses[$cc->id
] = $cc->shortname
;
347 $courses[$course->id
] = $course->shortname
;
350 $totalcount = $logs['totalcount'];
353 $tt = getdate(time());
354 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
356 $strftimedatetime = get_string("strftimedatetime");
358 echo "<div class=\"info\">\n";
359 print_string("displayingrecords", "", $totalcount);
362 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
364 $table = new html_table();
365 $table->classes
= array('logtable','generaltable');
366 $table->align
= array('right', 'left', 'left');
367 $table->head
= array(
369 get_string('ip_address'),
370 get_string('fullnameuser'),
371 get_string('action'),
374 $table->data
= array();
376 if ($course->id
== SITEID
) {
377 array_unshift($table->align
, 'left');
378 array_unshift($table->head
, get_string('course'));
381 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
382 if (empty($logs['logs'])) {
383 $logs['logs'] = array();
386 foreach ($logs['logs'] as $log) {
388 if (isset($ldcache[$log->module
][$log->action
])) {
389 $ld = $ldcache[$log->module
][$log->action
];
391 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
392 $ldcache[$log->module
][$log->action
] = $ld;
394 if ($ld && is_numeric($log->info
)) {
395 // ugly hack to make sure fullname is shown correctly
396 if ($ld->mtable
== 'user' && $ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname')) {
397 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
399 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
404 $log->info
= format_string($log->info
);
406 // If $log->url has been trimmed short by the db size restriction
407 // code in add_to_log, keep a note so we don't add a link to a broken url
408 $brokenurl=(textlib
::strlen($log->url
)==100 && textlib
::substr($log->url
,97)=='...');
411 if ($course->id
== SITEID
) {
412 if (empty($log->course
)) {
413 $row[] = get_string('site');
415 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>";
419 $row[] = userdate($log->time
, '%a').' '.userdate($log->time
, $strftimedatetime);
421 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
422 $row[] = $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
424 $row[] = html_writer
::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course
::instance($course->id
))));
426 $displayaction="$log->module $log->action";
428 $row[] = $displayaction;
430 $link = make_log_url($log->module
,$log->url
);
431 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
434 $table->data
[] = $row;
437 echo html_writer
::table($table);
438 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
442 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
443 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
445 global $CFG, $DB, $OUTPUT;
447 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
448 $modname, $modid, $modaction, $groupid)) {
449 echo $OUTPUT->notification("No logs found!");
450 echo $OUTPUT->footer();
454 if ($course->id
== SITEID
) {
456 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
457 foreach ($ccc as $cc) {
458 $courses[$cc->id
] = $cc->shortname
;
463 $totalcount = $logs['totalcount'];
466 $tt = getdate(time());
467 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
469 $strftimedatetime = get_string("strftimedatetime");
471 echo "<div class=\"info\">\n";
472 print_string("displayingrecords", "", $totalcount);
475 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
477 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
479 if ($course->id
== SITEID
) {
480 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
482 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
483 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
484 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
485 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
486 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
489 if (empty($logs['logs'])) {
495 foreach ($logs['logs'] as $log) {
497 $log->info
= $log->coursename
;
498 $row = ($row +
1) %
2;
500 if (isset($ldcache[$log->module
][$log->action
])) {
501 $ld = $ldcache[$log->module
][$log->action
];
503 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
504 $ldcache[$log->module
][$log->action
] = $ld;
506 if (0 && $ld && !empty($log->info
)) {
507 // ugly hack to make sure fullname is shown correctly
508 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
509 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
511 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
516 $log->info
= format_string($log->info
);
518 echo '<tr class="r'.$row.'">';
519 if ($course->id
== SITEID
) {
520 $courseshortname = format_string($courses[$log->course
], true, array('context' => context_course
::instance(SITEID
)));
521 echo "<td class=\"r$row c0\" >\n";
522 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
525 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
526 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
527 echo "<td class=\"r$row c2\" >\n";
528 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
529 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
531 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course
::instance($course->id
)));
532 echo "<td class=\"r$row c3\" >\n";
533 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
535 echo "<td class=\"r$row c4\">\n";
536 echo $log->action
.': '.$log->module
;
538 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
543 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
547 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
548 $modid, $modaction, $groupid) {
551 require_once($CFG->libdir
. '/csvlib.class.php');
553 $csvexporter = new csv_export_writer('tab');
556 $header[] = get_string('course');
557 $header[] = get_string('time');
558 $header[] = get_string('ip_address');
559 $header[] = get_string('fullnameuser');
560 $header[] = get_string('action');
561 $header[] = get_string('info');
563 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
564 $modname, $modid, $modaction, $groupid)) {
570 if ($course->id
== SITEID
) {
572 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
573 foreach ($ccc as $cc) {
574 $courses[$cc->id
] = $cc->shortname
;
578 $courses[$course->id
] = $course->shortname
;
583 $tt = getdate(time());
584 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
586 $strftimedatetime = get_string("strftimedatetime");
588 $csvexporter->set_filename('logs', '.txt');
589 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
590 $csvexporter->add_data($title);
591 $csvexporter->add_data($header);
593 if (empty($logs['logs'])) {
597 foreach ($logs['logs'] as $log) {
598 if (isset($ldcache[$log->module
][$log->action
])) {
599 $ld = $ldcache[$log->module
][$log->action
];
601 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
602 $ldcache[$log->module
][$log->action
] = $ld;
604 if ($ld && is_numeric($log->info
)) {
605 // ugly hack to make sure fullname is shown correctly
606 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
607 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
609 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
614 $log->info
= format_string($log->info
);
615 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
617 $coursecontext = context_course
::instance($course->id
);
618 $firstField = format_string($courses[$log->course
], true, array('context' => $coursecontext));
619 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
620 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
621 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
.' ('.$actionurl.')', $log->info
);
622 $csvexporter->add_data($row);
624 $csvexporter->download_file();
629 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
630 $modid, $modaction, $groupid) {
634 require_once("$CFG->libdir/excellib.class.php");
636 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
637 $modname, $modid, $modaction, $groupid)) {
643 if ($course->id
== SITEID
) {
645 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
646 foreach ($ccc as $cc) {
647 $courses[$cc->id
] = $cc->shortname
;
651 $courses[$course->id
] = $course->shortname
;
656 $tt = getdate(time());
657 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
659 $strftimedatetime = get_string("strftimedatetime");
661 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
662 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
665 $workbook = new MoodleExcelWorkbook('-');
666 $workbook->send($filename);
668 $worksheet = array();
669 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
670 get_string('fullnameuser'), get_string('action'), get_string('info'));
672 // Creating worksheets
673 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
674 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
675 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
676 $worksheet[$wsnumber]->set_column(1, 1, 30);
677 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
678 userdate(time(), $strftimedatetime));
680 foreach ($headers as $item) {
681 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
686 if (empty($logs['logs'])) {
691 $formatDate =& $workbook->add_format();
692 $formatDate->set_num_format(get_string('log_excel_date_format'));
694 $row = FIRSTUSEDEXCELROW
;
696 $myxls =& $worksheet[$wsnumber];
697 foreach ($logs['logs'] as $log) {
698 if (isset($ldcache[$log->module
][$log->action
])) {
699 $ld = $ldcache[$log->module
][$log->action
];
701 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
702 $ldcache[$log->module
][$log->action
] = $ld;
704 if ($ld && is_numeric($log->info
)) {
705 // ugly hack to make sure fullname is shown correctly
706 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
707 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
709 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
714 $log->info
= format_string($log->info
);
715 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
718 if ($row > EXCELROWS
) {
720 $myxls =& $worksheet[$wsnumber];
721 $row = FIRSTUSEDEXCELROW
;
725 $coursecontext = context_course
::instance($course->id
);
727 $myxls->write($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)), '');
728 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
729 $myxls->write($row, 2, $log->ip
, '');
730 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
731 $myxls->write($row, 3, $fullname, '');
732 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
733 $myxls->write($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')', '');
734 $myxls->write($row, 5, $log->info
, '');
743 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
744 $modid, $modaction, $groupid) {
748 require_once("$CFG->libdir/odslib.class.php");
750 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
751 $modname, $modid, $modaction, $groupid)) {
757 if ($course->id
== SITEID
) {
759 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
760 foreach ($ccc as $cc) {
761 $courses[$cc->id
] = $cc->shortname
;
765 $courses[$course->id
] = $course->shortname
;
770 $tt = getdate(time());
771 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
773 $strftimedatetime = get_string("strftimedatetime");
775 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
776 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
779 $workbook = new MoodleODSWorkbook('-');
780 $workbook->send($filename);
782 $worksheet = array();
783 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
784 get_string('fullnameuser'), get_string('action'), get_string('info'));
786 // Creating worksheets
787 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
788 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
789 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
790 $worksheet[$wsnumber]->set_column(1, 1, 30);
791 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
792 userdate(time(), $strftimedatetime));
794 foreach ($headers as $item) {
795 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
800 if (empty($logs['logs'])) {
805 $formatDate =& $workbook->add_format();
806 $formatDate->set_num_format(get_string('log_excel_date_format'));
808 $row = FIRSTUSEDEXCELROW
;
810 $myxls =& $worksheet[$wsnumber];
811 foreach ($logs['logs'] as $log) {
812 if (isset($ldcache[$log->module
][$log->action
])) {
813 $ld = $ldcache[$log->module
][$log->action
];
815 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
816 $ldcache[$log->module
][$log->action
] = $ld;
818 if ($ld && is_numeric($log->info
)) {
819 // ugly hack to make sure fullname is shown correctly
820 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
821 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
823 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
828 $log->info
= format_string($log->info
);
829 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
832 if ($row > EXCELROWS
) {
834 $myxls =& $worksheet[$wsnumber];
835 $row = FIRSTUSEDEXCELROW
;
839 $coursecontext = context_course
::instance($course->id
);
841 $myxls->write_string($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)));
842 $myxls->write_date($row, 1, $log->time
);
843 $myxls->write_string($row, 2, $log->ip
);
844 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
845 $myxls->write_string($row, 3, $fullname);
846 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
847 $myxls->write_string($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')');
848 $myxls->write_string($row, 5, $log->info
);
858 * For a given course, returns an array of course activity objects
859 * Each item in the array contains he following properties:
861 function get_array_of_activities($courseid) {
862 // cm - course module id
863 // mod - name of the module (eg forum)
864 // section - the number of the section (eg week or topic)
865 // name - the name of the instance
866 // visible - is the instance visible or not
867 // groupingid - grouping id
868 // groupmembersonly - is this instance visible to group members only
869 // extra - contains extra string to include in any link
871 if(!empty($CFG->enableavailability
)) {
872 require_once($CFG->libdir
.'/conditionlib.php');
875 $course = $DB->get_record('course', array('id'=>$courseid));
877 if (empty($course)) {
878 throw new moodle_exception('courseidnotfound');
883 $rawmods = get_course_mods($courseid);
884 if (empty($rawmods)) {
885 return $mod; // always return array
888 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
889 foreach ($sections as $section) {
890 if (!empty($section->sequence
)) {
891 $sequence = explode(",", $section->sequence
);
892 foreach ($sequence as $seq) {
893 if (empty($rawmods[$seq])) {
896 $mod[$seq] = new stdClass();
897 $mod[$seq]->id
= $rawmods[$seq]->instance
;
898 $mod[$seq]->cm
= $rawmods[$seq]->id
;
899 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
901 // Oh dear. Inconsistent names left here for backward compatibility.
902 $mod[$seq]->section
= $section->section
;
903 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
905 $mod[$seq]->module
= $rawmods[$seq]->module
;
906 $mod[$seq]->added
= $rawmods[$seq]->added
;
907 $mod[$seq]->score
= $rawmods[$seq]->score
;
908 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
909 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
910 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
911 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
912 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
913 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
914 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
915 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
916 $mod[$seq]->extra
= "";
917 $mod[$seq]->completiongradeitemnumber
=
918 $rawmods[$seq]->completiongradeitemnumber
;
919 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
920 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
921 $mod[$seq]->availablefrom
= $rawmods[$seq]->availablefrom
;
922 $mod[$seq]->availableuntil
= $rawmods[$seq]->availableuntil
;
923 $mod[$seq]->showavailability
= $rawmods[$seq]->showavailability
;
924 $mod[$seq]->showdescription
= $rawmods[$seq]->showdescription
;
925 if (!empty($CFG->enableavailability
)) {
926 condition_info
::fill_availability_conditions($rawmods[$seq]);
927 $mod[$seq]->conditionscompletion
= $rawmods[$seq]->conditionscompletion
;
928 $mod[$seq]->conditionsgrade
= $rawmods[$seq]->conditionsgrade
;
929 $mod[$seq]->conditionsfield
= $rawmods[$seq]->conditionsfield
;
932 $modname = $mod[$seq]->mod
;
933 $functionname = $modname."_get_coursemodule_info";
935 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
939 include_once("$CFG->dirroot/mod/$modname/lib.php");
941 if ($hasfunction = function_exists($functionname)) {
942 if ($info = $functionname($rawmods[$seq])) {
943 if (!empty($info->icon
)) {
944 $mod[$seq]->icon
= $info->icon
;
946 if (!empty($info->iconcomponent
)) {
947 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
949 if (!empty($info->name
)) {
950 $mod[$seq]->name
= $info->name
;
952 if ($info instanceof cached_cm_info
) {
953 // When using cached_cm_info you can include three new fields
954 // that aren't available for legacy code
955 if (!empty($info->content
)) {
956 $mod[$seq]->content
= $info->content
;
958 if (!empty($info->extraclasses
)) {
959 $mod[$seq]->extraclasses
= $info->extraclasses
;
961 if (!empty($info->iconurl
)) {
962 $mod[$seq]->iconurl
= $info->iconurl
;
964 if (!empty($info->onclick
)) {
965 $mod[$seq]->onclick
= $info->onclick
;
967 if (!empty($info->customdata
)) {
968 $mod[$seq]->customdata
= $info->customdata
;
971 // When using a stdclass, the (horrible) deprecated ->extra field
972 // is available for BC
973 if (!empty($info->extra
)) {
974 $mod[$seq]->extra
= $info->extra
;
979 // When there is no modname_get_coursemodule_info function,
980 // but showdescriptions is enabled, then we use the 'intro'
981 // and 'introformat' fields in the module table
982 if (!$hasfunction && $rawmods[$seq]->showdescription
) {
983 if ($modvalues = $DB->get_record($rawmods[$seq]->modname
,
984 array('id' => $rawmods[$seq]->instance
), 'name, intro, introformat')) {
985 // Set content from intro and introformat. Filters are disabled
986 // because we filter it with format_text at display time
987 $mod[$seq]->content
= format_module_intro($rawmods[$seq]->modname
,
988 $modvalues, $rawmods[$seq]->id
, false);
990 // To save making another query just below, put name in here
991 $mod[$seq]->name
= $modvalues->name
;
994 if (!isset($mod[$seq]->name
)) {
995 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
998 // Minimise the database size by unsetting default options when they are
999 // 'empty'. This list corresponds to code in the cm_info constructor.
1000 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1001 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1002 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1003 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1004 'completionview', 'completionexpected', 'score', 'showdescription')
1006 if (property_exists($mod[$seq], $property) &&
1007 empty($mod[$seq]->{$property})) {
1008 unset($mod[$seq]->{$property});
1011 // Special case: this value is usually set to null, but may be 0
1012 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1013 is_null($mod[$seq]->completiongradeitemnumber
)) {
1014 unset($mod[$seq]->completiongradeitemnumber
);
1024 * Returns the localised human-readable names of all used modules
1026 * @param bool $plural if true returns the plural forms of the names
1027 * @return array where key is the module name (component name without 'mod_') and
1028 * the value is the human-readable string. Array sorted alphabetically by value
1030 function get_module_types_names($plural = false) {
1031 static $modnames = null;
1033 if ($modnames === null) {
1034 $modnames = array(0 => array(), 1 => array());
1035 if ($allmods = $DB->get_records("modules")) {
1036 foreach ($allmods as $mod) {
1037 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible
) {
1038 $modnames[0][$mod->name
] = get_string("modulename", "$mod->name");
1039 $modnames[1][$mod->name
] = get_string("modulenameplural", "$mod->name");
1042 collatorlib
::asort($modnames[0]);
1043 collatorlib
::asort($modnames[1]);
1046 return $modnames[(int)$plural];
1050 * Set highlighted section. Only one section can be highlighted at the time.
1052 * @param int $courseid course id
1053 * @param int $marker highlight section with this number, 0 means remove higlightin
1056 function course_set_marker($courseid, $marker) {
1058 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1059 format_base
::reset_course_cache($courseid);
1063 * For a given course section, marks it visible or hidden,
1064 * and does the same for every activity in that section
1066 * @param int $courseid course id
1067 * @param int $sectionnumber The section number to adjust
1068 * @param int $visibility The new visibility
1069 * @return array A list of resources which were hidden in the section
1071 function set_section_visible($courseid, $sectionnumber, $visibility) {
1074 $resourcestotoggle = array();
1075 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1076 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1077 if (!empty($section->sequence
)) {
1078 $modules = explode(",", $section->sequence
);
1079 foreach ($modules as $moduleid) {
1080 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1082 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1083 set_coursemodule_visible($moduleid, $cm->visibleold
);
1085 // We hide the section, so we hide the module but we store the original state in visibleold.
1086 set_coursemodule_visible($moduleid, 0);
1087 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id' => $moduleid));
1092 rebuild_course_cache($courseid, true);
1094 // Determine which modules are visible for AJAX update
1095 if (!empty($modules)) {
1096 list($insql, $params) = $DB->get_in_or_equal($modules);
1097 $select = 'id ' . $insql . ' AND visible = ?';
1098 array_push($params, $visibility);
1100 $select .= ' AND visibleold = 1';
1102 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1105 return $resourcestotoggle;
1109 * Retrieve all metadata for the requested modules
1111 * @param object $course The Course
1112 * @param array $modnames An array containing the list of modules and their
1114 * @param int $sectionreturn The section to return to
1115 * @return array A list of stdClass objects containing metadata about each
1118 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1119 global $CFG, $OUTPUT;
1121 // get_module_metadata will be called once per section on the page and courses may show
1122 // different modules to one another
1123 static $modlist = array();
1124 if (!isset($modlist[$course->id
])) {
1125 $modlist[$course->id
] = array();
1129 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id
, 'sesskey' => sesskey()));
1130 if ($sectionreturn !== null) {
1131 $urlbase->param('sr', $sectionreturn);
1133 foreach($modnames as $modname => $modnamestr) {
1134 if (!course_allowed_module($course, $modname)) {
1137 if (isset($modlist[$course->id
][$modname])) {
1138 // This module is already cached
1139 $return[$modname] = $modlist[$course->id
][$modname];
1143 // Include the module lib
1144 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1145 if (!file_exists($libfile)) {
1148 include_once($libfile);
1150 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1151 $gettypesfunc = $modname.'_get_types';
1152 if (function_exists($gettypesfunc)) {
1153 $types = $gettypesfunc();
1154 if (is_array($types) && count($types) > 0) {
1155 $group = new stdClass();
1156 $group->name
= $modname;
1157 $group->icon
= $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1158 foreach($types as $type) {
1159 if ($type->typestr
=== '--') {
1162 if (strpos($type->typestr
, '--') === 0) {
1163 $group->title
= str_replace('--', '', $type->typestr
);
1166 // Set the Sub Type metadata
1167 $subtype = new stdClass();
1168 $subtype->title
= $type->typestr
;
1169 $subtype->type
= str_replace('&', '&', $type->type
);
1170 $subtype->name
= preg_replace('/.*type=/', '', $subtype->type
);
1171 $subtype->archetype
= $type->modclass
;
1173 // The group archetype should match the subtype archetypes and all subtypes
1174 // should have the same archetype
1175 $group->archetype
= $subtype->archetype
;
1177 if (get_string_manager()->string_exists('help' . $subtype->name
, $modname)) {
1178 $subtype->help
= get_string('help' . $subtype->name
, $modname);
1180 $subtype->link
= new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name
));
1181 $group->types
[] = $subtype;
1183 $modlist[$course->id
][$modname] = $group;
1186 $module = new stdClass();
1187 $module->title
= $modnamestr;
1188 $module->name
= $modname;
1189 $module->link
= new moodle_url($urlbase, array('add' => $modname));
1190 $module->icon
= $OUTPUT->pix_icon('icon', '', $module->name
, array('class' => 'icon'));
1191 $sm = get_string_manager();
1192 if ($sm->string_exists('modulename_help', $modname)) {
1193 $module->help
= get_string('modulename_help', $modname);
1194 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1195 $link = get_string('modulename_link', $modname);
1196 $linktext = get_string('morehelp');
1197 $module->help
.= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1200 $module->archetype
= plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1201 $modlist[$course->id
][$modname] = $module;
1203 if (isset($modlist[$course->id
][$modname])) {
1204 $return[$modname] = $modlist[$course->id
][$modname];
1206 debugging("Invalid module metadata configuration for {$modname}");
1214 * Return the course category context for the category with id $categoryid, except
1215 * that if $categoryid is 0, return the system context.
1217 * @param integer $categoryid a category id or 0.
1218 * @return object the corresponding context
1220 function get_category_or_system_context($categoryid) {
1222 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
1224 return context_system
::instance();
1229 * Returns full course categories trees to be used in html_writer::select()
1231 * Calls {@link coursecat::make_categories_list()} to build the tree and
1232 * adds whitespace to denote nesting
1234 * @return array array mapping coursecat id to the display name
1236 function make_categories_options() {
1238 require_once($CFG->libdir
. '/coursecatlib.php');
1239 $cats = coursecat
::make_categories_list();
1240 foreach ($cats as $key => $value) {
1241 $cats[$key] = str_repeat(' ', coursecat
::get($key)->depth
- 1). $value;
1247 * Print the buttons relating to course requests.
1249 * @param object $context current page context.
1251 function print_course_request_buttons($context) {
1252 global $CFG, $DB, $OUTPUT;
1253 if (empty($CFG->enablecourserequests
)) {
1256 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1257 /// Print a button to request a new course
1258 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1260 /// Print a button to manage pending requests
1261 if ($context->contextlevel
== CONTEXT_SYSTEM
&& has_capability('moodle/site:approvecourse', $context)) {
1262 $disabled = !$DB->record_exists('course_request', array());
1263 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1268 * Does the user have permission to edit things in this category?
1270 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1271 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1273 function can_edit_in_category($categoryid = 0) {
1274 $context = get_category_or_system_context($categoryid);
1275 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1278 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1280 function add_course_module($mod) {
1283 $mod->added
= time();
1286 $cmid = $DB->insert_record("course_modules", $mod);
1287 rebuild_course_cache($mod->course
, true);
1292 * Creates missing course section(s) and rebuilds course cache
1294 * @param int|stdClass $courseorid course id or course object
1295 * @param int|array $sections list of relative section numbers to create
1296 * @return bool if there were any sections created
1298 function course_create_sections_if_missing($courseorid, $sections) {
1300 if (!is_array($sections)) {
1301 $sections = array($sections);
1303 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1304 if (is_object($courseorid)) {
1305 $courseorid = $courseorid->id
;
1307 $coursechanged = false;
1308 foreach ($sections as $sectionnum) {
1309 if (!in_array($sectionnum, $existing)) {
1310 $cw = new stdClass();
1311 $cw->course
= $courseorid;
1312 $cw->section
= $sectionnum;
1314 $cw->summaryformat
= FORMAT_HTML
;
1316 $id = $DB->insert_record("course_sections", $cw);
1317 $coursechanged = true;
1320 if ($coursechanged) {
1321 rebuild_course_cache($courseorid, true);
1323 return $coursechanged;
1327 * Adds an existing module to the section
1329 * Updates both tables {course_sections} and {course_modules}
1331 * @param int|stdClass $courseorid course id or course object
1332 * @param int $cmid id of the module already existing in course_modules table
1333 * @param int $sectionnum relative number of the section (field course_sections.section)
1334 * If section does not exist it will be created
1335 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1336 * before which the module needs to be included. Null for inserting in the
1337 * end of the section
1338 * @return int The course_sections ID where the module is inserted
1340 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1341 global $DB, $COURSE;
1342 if (is_object($beforemod)) {
1343 $beforemod = $beforemod->id
;
1345 if (is_object($courseorid)) {
1346 $courseid = $courseorid->id
;
1348 $courseid = $courseorid;
1350 course_create_sections_if_missing($courseorid, $sectionnum);
1351 // Do not try to use modinfo here, there is no guarantee it is valid!
1352 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST
);
1353 $modarray = explode(",", trim($section->sequence
));
1354 if (empty($section->sequence
)) {
1355 $newsequence = "$cmid";
1356 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1357 $insertarray = array($cmid, $beforemod);
1358 array_splice($modarray, $key[0], 1, $insertarray);
1359 $newsequence = implode(",", $modarray);
1361 $newsequence = "$section->sequence,$cmid";
1363 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
1364 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
1365 if (is_object($courseorid)) {
1366 rebuild_course_cache($courseorid->id
, true);
1368 rebuild_course_cache($courseorid, true);
1370 return $section->id
; // Return course_sections ID that was used.
1373 function set_coursemodule_groupmode($id, $groupmode) {
1375 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
1376 if ($cm->groupmode
!= $groupmode) {
1377 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
1378 rebuild_course_cache($cm->course
, true);
1380 return ($cm->groupmode
!= $groupmode);
1383 function set_coursemodule_idnumber($id, $idnumber) {
1385 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
1386 if ($cm->idnumber
!= $idnumber) {
1387 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
1388 rebuild_course_cache($cm->course
, true);
1390 return ($cm->idnumber
!= $idnumber);
1394 * Set the visibility of a module and inherent properties.
1396 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1397 * has been moved to {@link set_section_visible()} which was the only place from which
1398 * the parameter was used.
1400 * @param int $id of the module
1401 * @param int $visible state of the module
1402 * @return bool false when the module was not found, true otherwise
1404 function set_coursemodule_visible($id, $visible) {
1406 require_once($CFG->libdir
.'/gradelib.php');
1408 // Trigger developer's attention when using the previously removed argument.
1409 if (func_num_args() > 2) {
1410 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1411 has been removed.', DEBUG_DEVELOPER
);
1414 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1418 // Create events and propagate visibility to associated grade items if the value has changed.
1419 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1420 if ($cm->visible
== $visible) {
1424 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
1427 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
1428 foreach($events as $event) {
1437 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1438 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
1440 foreach ($grade_items as $grade_item) {
1441 $grade_item->set_hidden(!$visible);
1445 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1446 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1447 $cminfo = new stdClass();
1449 $cminfo->visible
= $visible;
1450 $cminfo->visibleold
= $visible;
1451 $DB->update_record('course_modules', $cminfo);
1453 rebuild_course_cache($cm->course
, true);
1458 * This function will handles the whole deletion process of a module. This includes calling
1459 * the modules delete_instance function, deleting files, events, grades, conditional data,
1460 * the data in the course_module and course_sections table and adding a module deletion
1463 * @param int $cmid the course module id
1466 function course_delete_module($cmid) {
1467 global $CFG, $DB, $USER;
1469 require_once($CFG->libdir
.'/gradelib.php');
1470 require_once($CFG->dirroot
.'/blog/lib.php');
1472 // Get the course module.
1473 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1477 // Get the module context.
1478 $modcontext = context_module
::instance($cm->id
);
1480 // Get the course module name.
1481 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
1483 // Get the file location of the delete_instance function for this module.
1484 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1486 // Include the file required to call the delete_instance function for this module.
1487 if (file_exists($modlib)) {
1488 require_once($modlib);
1490 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1491 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1494 $deleteinstancefunction = $modulename . '_delete_instance';
1496 // Ensure the delete_instance function exists for this module.
1497 if (!function_exists($deleteinstancefunction)) {
1498 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1499 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1502 // Call the delete_instance function, if it returns false throw an exception.
1503 if (!$deleteinstancefunction($cm->instance
)) {
1504 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1505 "Cannot delete the module $modulename (instance).");
1508 // Remove all module files in case modules forget to do that.
1509 $fs = get_file_storage();
1510 $fs->delete_area_files($modcontext->id
);
1512 // Delete events from calendar.
1513 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
1514 foreach($events as $event) {
1515 delete_event($event->id
);
1519 // Delete grade items, outcome items and grades attached to modules.
1520 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1521 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
1522 foreach ($grade_items as $grade_item) {
1523 $grade_item->delete('moddelete');
1527 // Delete completion and availability data; it is better to do this even if the
1528 // features are not turned on, in case they were turned on previously (these will be
1529 // very quick on an empty table).
1530 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
1531 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
1532 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id
));
1533 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
1534 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
1536 // Delete the context.
1537 delete_context(CONTEXT_MODULE
, $cm->id
);
1539 // Delete the module from the course_modules table.
1540 $DB->delete_records('course_modules', array('id' => $cm->id
));
1542 // Delete module from that section.
1543 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
1544 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1545 "Cannot delete the module $modulename (instance) from section.");
1548 // Trigger a mod_deleted event with information about this module.
1549 $eventdata = new stdClass();
1550 $eventdata->modulename
= $modulename;
1551 $eventdata->cmid
= $cm->id
;
1552 $eventdata->courseid
= $cm->course
;
1553 $eventdata->userid
= $USER->id
;
1554 events_trigger('mod_deleted', $eventdata);
1556 add_to_log($cm->course
, 'course', "delete mod",
1557 "view.php?id=$cm->course",
1558 "$modulename $cm->instance", $cm->id
);
1560 rebuild_course_cache($cm->course
, true);
1563 function delete_mod_from_section($modid, $sectionid) {
1566 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1568 $modarray = explode(",", $section->sequence
);
1570 if ($key = array_keys ($modarray, $modid)) {
1571 array_splice($modarray, $key[0], 1);
1572 $newsequence = implode(",", $modarray);
1573 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
1574 rebuild_course_cache($section->course
, true);
1585 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
1587 * @param object $course course object
1588 * @param int $section Section number (not id!!!)
1589 * @param int $move (-1 or 1)
1590 * @return boolean true if section moved successfully
1591 * @todo MDL-33379 remove this function in 2.5
1593 function move_section($course, $section, $move) {
1594 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER
);
1596 /// Moves a whole course section up and down within the course
1603 $sectiondest = $section +
$move;
1605 // compartibility with course formats using field 'numsections'
1606 $courseformatoptions = course_get_format($course)->get_format_options();
1607 if (array_key_exists('numsections', $courseformatoptions) &&
1608 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
1612 $retval = move_section_to($course, $section, $sectiondest);
1617 * Moves a section within a course, from a position to another.
1618 * Be very careful: $section and $destination refer to section number,
1621 * @param object $course
1622 * @param int $section Section number (not id!!!)
1623 * @param int $destination
1624 * @return boolean Result
1626 function move_section_to($course, $section, $destination) {
1627 /// Moves a whole course section up and down within the course
1630 if (!$destination && $destination != 0) {
1634 // compartibility with course formats using field 'numsections'
1635 $courseformatoptions = course_get_format($course)->get_format_options();
1636 if ((array_key_exists('numsections', $courseformatoptions) &&
1637 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
1641 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1642 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
1643 'section ASC, id ASC', 'id, section')) {
1647 $movedsections = reorder_sections($sections, $section, $destination);
1649 // Update all sections. Do this in 2 steps to avoid breaking database
1650 // uniqueness constraint
1651 $transaction = $DB->start_delegated_transaction();
1652 foreach ($movedsections as $id => $position) {
1653 if ($sections[$id] !== $position) {
1654 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1657 foreach ($movedsections as $id => $position) {
1658 if ($sections[$id] !== $position) {
1659 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1663 // If we move the highlighted section itself, then just highlight the destination.
1664 // Adjust the higlighted section location if we move something over it either direction.
1665 if ($section == $course->marker
) {
1666 course_set_marker($course->id
, $destination);
1667 } elseif ($section > $course->marker
&& $course->marker
>= $destination) {
1668 course_set_marker($course->id
, $course->marker+
1);
1669 } elseif ($section < $course->marker
&& $course->marker
<= $destination) {
1670 course_set_marker($course->id
, $course->marker
-1);
1673 $transaction->allow_commit();
1674 rebuild_course_cache($course->id
, true);
1679 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1680 * an original position number and a target position number, rebuilds the array so that the
1681 * move is made without any duplication of section positions.
1682 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1683 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1685 * @param array $sections
1686 * @param int $origin_position
1687 * @param int $target_position
1690 function reorder_sections($sections, $origin_position, $target_position) {
1691 if (!is_array($sections)) {
1695 // We can't move section position 0
1696 if ($origin_position < 1) {
1697 echo "We can't move section position 0";
1701 // Locate origin section in sections array
1702 if (!$origin_key = array_search($origin_position, $sections)) {
1703 echo "searched position not in sections array";
1704 return false; // searched position not in sections array
1707 // Extract origin section
1708 $origin_section = $sections[$origin_key];
1709 unset($sections[$origin_key]);
1711 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1713 $append_array = array();
1714 foreach ($sections as $id => $position) {
1716 $append_array[$id] = $position;
1717 unset($sections[$id]);
1719 if ($position == $target_position) {
1720 if ($target_position < $origin_position) {
1721 $append_array[$id] = $position;
1722 unset($sections[$id]);
1728 // Append moved section
1729 $sections[$origin_key] = $origin_section;
1731 // Append rest of array (if applicable)
1732 if (!empty($append_array)) {
1733 foreach ($append_array as $id => $position) {
1734 $sections[$id] = $position;
1738 // Renumber positions
1740 foreach ($sections as $id => $p) {
1741 $sections[$id] = $position;
1750 * Move the module object $mod to the specified $section
1751 * If $beforemod exists then that is the module
1752 * before which $modid should be inserted
1753 * All parameters are objects
1755 function moveto_module($mod, $section, $beforemod=NULL) {
1756 global $OUTPUT, $DB;
1758 /// Remove original module from original section
1759 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
1760 echo $OUTPUT->notification("Could not delete module from existing section");
1763 // if moving to a hidden section then hide module
1764 if ($mod->section
!= $section->id
) {
1765 if (!$section->visible
&& $mod->visible
) {
1766 // Set this in the object because it is sent as a response to ajax calls.
1768 set_coursemodule_visible($mod->id
, 0);
1769 // Set visibleold to 1 so module will be visible when section is made visible.
1770 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
1772 if ($section->visible
&& !$mod->visible
) {
1773 set_coursemodule_visible($mod->id
, $mod->visibleold
);
1774 // Set this in the object because it is sent as a response to ajax calls.
1775 $mod->visible
= $mod->visibleold
;
1779 /// Add the module into the new section
1780 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
1785 * Returns the list of all editing actions that current user can perform on the module
1787 * @param cm_info $mod The module to produce editing buttons for
1788 * @param int $indent The current indenting (default -1 means no move left-right actions)
1789 * @param int $sr The section to link back to (used for creating the links)
1790 * @return array array of action_link or pix_icon objects
1792 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
1793 global $COURSE, $SITE;
1797 $coursecontext = context_course
::instance($mod->course
);
1798 $modcontext = context_module
::instance($mod->id
);
1800 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1801 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1803 // no permission to edit anything
1804 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1808 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1811 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1812 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1813 $str->assign
= get_string('assignroles', 'role');
1814 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1815 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1816 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1817 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1818 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1819 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1822 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1825 $baseurl->param('sr', $sr);
1830 if ($mod->has_view() && $hasmanageactivities &&
1831 (($mod->course
== $COURSE->id
&& course_ajax_enabled($COURSE)) ||
1832 ($mod->course
== SITEID
&& course_ajax_enabled($SITE)))) {
1833 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1834 $actions['title'] = new action_link(
1835 new moodle_url($baseurl, array('update' => $mod->id
)),
1836 new pix_icon('t/editstring', $str->edittitle
, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
1838 array('class' => 'editing_title', 'title' => $str->edittitle
)
1843 if ($hasmanageactivities) {
1844 if (right_to_left()) { // Exchange arrows on RTL
1845 $rightarrow = 't/left';
1846 $leftarrow = 't/right';
1848 $rightarrow = 't/right';
1849 $leftarrow = 't/left';
1853 $actions['moveleft'] = new action_link(
1854 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '-1')),
1855 new pix_icon($leftarrow, $str->moveleft
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1857 array('class' => 'editing_moveleft', 'title' => $str->moveleft
)
1861 $actions['moveright'] = new action_link(
1862 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '1')),
1863 new pix_icon($rightarrow, $str->moveright
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1865 array('class' => 'editing_moveright', 'title' => $str->moveright
)
1871 if ($hasmanageactivities) {
1872 $actions['move'] = new action_link(
1873 new moodle_url($baseurl, array('copy' => $mod->id
)),
1874 new pix_icon('t/move', $str->move
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1876 array('class' => 'editing_move', 'title' => $str->move
)
1881 if ($hasmanageactivities) {
1882 $actions['update'] = new action_link(
1883 new moodle_url($baseurl, array('update' => $mod->id
)),
1884 new pix_icon('t/edit', $str->update
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1886 array('class' => 'editing_update', 'title' => $str->update
)
1890 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1891 // note that restoring on front page is never allowed
1892 if ($mod->course
!= SITEID
&& has_all_capabilities($dupecaps, $coursecontext) &&
1893 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
)) {
1894 $actions['duplicate'] = new action_link(
1895 new moodle_url($baseurl, array('duplicate' => $mod->id
)),
1896 new pix_icon('t/copy', $str->duplicate
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1898 array('class' => 'editing_duplicate', 'title' => $str->duplicate
)
1903 if ($hasmanageactivities) {
1904 $actions['delete'] = new action_link(
1905 new moodle_url($baseurl, array('delete' => $mod->id
)),
1906 new pix_icon('t/delete', $str->delete
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1908 array('class' => 'editing_delete', 'title' => $str->delete
)
1913 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1914 if ($mod->visible
) {
1915 $actions['hide'] = new action_link(
1916 new moodle_url($baseurl, array('hide' => $mod->id
)),
1917 new pix_icon('t/hide', $str->hide
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1919 array('class' => 'editing_hide', 'title' => $str->hide
)
1922 $actions['show'] = new action_link(
1923 new moodle_url($baseurl, array('show' => $mod->id
)),
1924 new pix_icon('t/show', $str->show
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1926 array('class' => 'editing_show', 'title' => $str->show
)
1932 if ($hasmanageactivities and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
1933 if ($mod->coursegroupmodeforce
) {
1934 $modgroupmode = $mod->coursegroupmode
;
1936 $modgroupmode = $mod->groupmode
;
1938 if ($modgroupmode == SEPARATEGROUPS
) {
1939 $groupmode = NOGROUPS
;
1940 $grouptitle = $str->groupsseparate
;
1941 $forcedgrouptitle = $str->forcedgroupsseparate
;
1942 $actionname = 'groupsseparate';
1943 $groupimage = 't/groups';
1944 } else if ($modgroupmode == VISIBLEGROUPS
) {
1945 $groupmode = SEPARATEGROUPS
;
1946 $grouptitle = $str->groupsvisible
;
1947 $forcedgrouptitle = $str->forcedgroupsvisible
;
1948 $actionname = 'groupsvisible';
1949 $groupimage = 't/groupv';
1951 $groupmode = VISIBLEGROUPS
;
1952 $grouptitle = $str->groupsnone
;
1953 $forcedgrouptitle = $str->forcedgroupsnone
;
1954 $actionname = 'groupsnone';
1955 $groupimage = 't/groupn';
1957 if (!$mod->coursegroupmodeforce
) {
1958 $actions[$actionname] = new action_link(
1959 new moodle_url($baseurl, array('id' => $mod->id
, 'groupmode' => $groupmode)),
1960 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1962 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
1965 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
1970 if (has_capability('moodle/role:assign', $modcontext)){
1971 $actions['assign'] = new action_link(
1972 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
1973 new pix_icon('t/assignroles', $str->assign
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1975 array('class' => 'editing_assign', 'title' => $str->assign
)
1983 * given a course object with shortname & fullname, this function will
1984 * truncate the the number of chars allowed and add ... if it was too long
1986 function course_format_name ($course,$max=100) {
1988 $context = context_course
::instance($course->id
);
1989 $shortname = format_string($course->shortname
, true, array('context' => $context));
1990 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
1991 $str = $shortname.': '. $fullname;
1992 if (textlib
::strlen($str) <= $max) {
1996 return textlib
::substr($str,0,$max-3).'...';
2001 * Is the user allowed to add this type of module to this course?
2002 * @param object $course the course settings. Only $course->id is used.
2003 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2004 * @return bool whether the current user is allowed to add this type of module to this course.
2006 function course_allowed_module($course, $modname) {
2007 if (is_numeric($modname)) {
2008 throw new coding_exception('Function course_allowed_module no longer
2009 supports numeric module ids. Please update your code to pass the module name.');
2012 $capability = 'mod/' . $modname . ':addinstance';
2013 if (!get_capability_info($capability)) {
2014 // Debug warning that the capability does not exist, but no more than once per page.
2015 static $warned = array();
2016 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
2017 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
2018 debugging('The module ' . $modname . ' does not define the standard capability ' .
2019 $capability , DEBUG_DEVELOPER
);
2020 $warned[$modname] = 1;
2023 // If the capability does not exist, the module can always be added.
2027 $coursecontext = context_course
::instance($course->id
);
2028 return has_capability($capability, $coursecontext);
2032 * Efficiently moves many courses around while maintaining
2033 * sortorder in order.
2035 * @param array $courseids is an array of course ids
2036 * @param int $categoryid
2037 * @return bool success
2039 function move_courses($courseids, $categoryid) {
2040 global $CFG, $DB, $OUTPUT;
2042 if (empty($courseids)) {
2047 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2051 $courseids = array_reverse($courseids);
2052 $newparent = context_coursecat
::instance($category->id
);
2055 foreach ($courseids as $courseid) {
2056 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2057 $course = new stdClass();
2058 $course->id
= $courseid;
2059 $course->category
= $category->id
;
2060 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
2061 if ($category->visible
== 0) {
2062 // hide the course when moving into hidden category,
2063 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2064 $course->visible
= 0;
2067 $DB->update_record('course', $course);
2068 add_to_log($course->id
, "course", "move", "edit.php?id=$course->id", $course->id
);
2070 $context = context_course
::instance($course->id
);
2071 context_moved($context, $newparent);
2074 fix_course_sortorder();
2075 cache_helper
::purge_by_event('changesincourse');
2081 * Returns the display name of the given section that the course prefers
2083 * Implementation of this function is provided by course format
2084 * @see format_base::get_section_name()
2086 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2087 * @param int|stdClass $section Section object from database or just field course_sections.section
2088 * @return string Display name that the course format prefers, e.g. "Week 2"
2090 function get_section_name($courseorid, $section) {
2091 return course_get_format($courseorid)->get_section_name($section);
2095 * Tells if current course format uses sections
2097 * @param string $format Course format ID e.g. 'weeks' $course->format
2100 function course_format_uses_sections($format) {
2101 $course = new stdClass();
2102 $course->format
= $format;
2103 return course_get_format($course)->uses_sections();
2107 * Returns the information about the ajax support in the given source format
2109 * The returned object's property (boolean)capable indicates that
2110 * the course format supports Moodle course ajax features.
2111 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2113 * @param string $format
2116 function course_format_ajax_support($format) {
2117 $course = new stdClass();
2118 $course->format
= $format;
2119 return course_get_format($course)->supports_ajax();
2123 * Can the current user delete this course?
2124 * Course creators have exception,
2125 * 1 day after the creation they can sill delete the course.
2126 * @param int $courseid
2129 function can_delete_course($courseid) {
2132 $context = context_course
::instance($courseid);
2134 if (has_capability('moodle/course:delete', $context)) {
2138 // hack: now try to find out if creator created this course recently (1 day)
2139 if (!has_capability('moodle/course:create', $context)) {
2143 $since = time() - 60*60*24;
2145 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2146 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2148 return $DB->record_exists_select('log', $select, $params);
2152 * Save the Your name for 'Some role' strings.
2154 * @param integer $courseid the id of this course.
2155 * @param array $data the data that came from the course settings form.
2157 function save_local_role_names($courseid, $data) {
2159 $context = context_course
::instance($courseid);
2161 foreach ($data as $fieldname => $value) {
2162 if (strpos($fieldname, 'role_') !== 0) {
2165 list($ignored, $roleid) = explode('_', $fieldname);
2167 // make up our mind whether we want to delete, update or insert
2169 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
2171 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
2172 $rolename->name
= $value;
2173 $DB->update_record('role_names', $rolename);
2176 $rolename = new stdClass
;
2177 $rolename->contextid
= $context->id
;
2178 $rolename->roleid
= $roleid;
2179 $rolename->name
= $value;
2180 $DB->insert_record('role_names', $rolename);
2186 * Returns options to use in course overviewfiles filemanager
2188 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2189 * may be empty if course does not exist yet (course create form)
2190 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2191 * or null if overviewfiles are disabled
2193 function course_overviewfiles_options($course) {
2195 if (empty($CFG->courseoverviewfileslimit
)) {
2198 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext
), -1, PREG_SPLIT_NO_EMPTY
);
2199 if (in_array('*', $accepted_types) ||
empty($accepted_types)) {
2200 $accepted_types = '*';
2202 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2203 // Make sure extensions are prefixed with dot unless they are valid typegroups
2204 foreach ($accepted_types as $i => $type) {
2205 if (substr($type, 0, 1) !== '.') {
2206 require_once($CFG->libdir
. '/filelib.php');
2207 if (!count(file_get_typegroup('extension', $type))) {
2208 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2209 $accepted_types[$i] = '.'. $type;
2214 if (!empty($corrected)) {
2215 set_config('courseoverviewfilesext', join(',', $accepted_types));
2219 'maxfiles' => $CFG->courseoverviewfileslimit
,
2220 'maxbytes' => $CFG->maxbytes
,
2222 'accepted_types' => $accepted_types
2224 if (!empty($course->id
)) {
2225 $options['context'] = context_course
::instance($course->id
);
2226 } else if (is_int($course) && $course > 0) {
2227 $options['context'] = context_course
::instance($course);
2233 * Create a course and either return a $course object
2235 * Please note this functions does not verify any access control,
2236 * the calling code is responsible for all validation (usually it is the form definition).
2238 * @param array $editoroptions course description editor options
2239 * @param object $data - all the data needed for an entry in the 'course' table
2240 * @return object new course instance
2242 function create_course($data, $editoroptions = NULL) {
2245 //check the categoryid - must be given for all new courses
2246 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
2248 //check if the shortname already exist
2249 if (!empty($data->shortname
)) {
2250 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
2251 throw new moodle_exception('shortnametaken');
2255 //check if the id number already exist
2256 if (!empty($data->idnumber
)) {
2257 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
2258 throw new moodle_exception('idnumbertaken');
2262 $data->timecreated
= time();
2263 $data->timemodified
= $data->timecreated
;
2265 // place at beginning of any category
2266 $data->sortorder
= 0;
2268 if ($editoroptions) {
2269 // summary text is updated later, we need context to store the files first
2270 $data->summary
= '';
2271 $data->summary_format
= FORMAT_HTML
;
2274 if (!isset($data->visible
)) {
2275 // data not from form, add missing visibility info
2276 $data->visible
= $category->visible
;
2278 $data->visibleold
= $data->visible
;
2280 $newcourseid = $DB->insert_record('course', $data);
2281 $context = context_course
::instance($newcourseid, MUST_EXIST
);
2283 if ($editoroptions) {
2284 // Save the files used in the summary editor and store
2285 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2286 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
2287 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
2289 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2290 // Save the course overviewfiles
2291 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2294 // update course format options
2295 course_get_format($newcourseid)->update_course_format_options($data);
2297 $course = course_get_format($newcourseid)->get_course();
2300 blocks_add_default_course_blocks($course);
2302 // Create a default section.
2303 course_create_sections_if_missing($course, 0);
2305 fix_course_sortorder();
2306 // purge appropriate caches in case fix_course_sortorder() did not change anything
2307 cache_helper
::purge_by_event('changesincourse');
2309 // new context created - better mark it as dirty
2310 mark_context_dirty($context->path
);
2312 // Save any custom role names.
2313 save_local_role_names($course->id
, (array)$data);
2315 // set up enrolments
2316 enrol_course_updated(true, $course, $data);
2318 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
2321 events_trigger('course_created', $course);
2329 * Please note this functions does not verify any access control,
2330 * the calling code is responsible for all validation (usually it is the form definition).
2332 * @param object $data - all the data needed for an entry in the 'course' table
2333 * @param array $editoroptions course description editor options
2336 function update_course($data, $editoroptions = NULL) {
2339 $data->timemodified
= time();
2341 $oldcourse = course_get_format($data->id
)->get_course();
2342 $context = context_course
::instance($oldcourse->id
);
2344 if ($editoroptions) {
2345 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2347 if ($overviewfilesoptions = course_overviewfiles_options($data->id
)) {
2348 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2351 if (!isset($data->category
) or empty($data->category
)) {
2352 // prevent nulls and 0 in category field
2353 unset($data->category
);
2355 $changesincoursecat = $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
2357 if (!isset($data->visible
)) {
2358 // data not from form, add missing visibility info
2359 $data->visible
= $oldcourse->visible
;
2362 if ($data->visible
!= $oldcourse->visible
) {
2363 // reset the visibleold flag when manually hiding/unhiding course
2364 $data->visibleold
= $data->visible
;
2365 $changesincoursecat = true;
2368 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
2369 if (empty($newcategory->visible
)) {
2370 // make sure when moving into hidden category the course is hidden automatically
2376 // Update with the new data
2377 $DB->update_record('course', $data);
2378 // make sure the modinfo cache is reset
2379 rebuild_course_cache($data->id
);
2381 // update course format options with full course data
2382 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
2384 $course = $DB->get_record('course', array('id'=>$data->id
));
2387 $newparent = context_coursecat
::instance($course->category
);
2388 context_moved($context, $newparent);
2391 fix_course_sortorder();
2392 // purge appropriate caches in case fix_course_sortorder() did not change anything
2393 cache_helper
::purge_by_event('changesincourse');
2394 if ($changesincoursecat) {
2395 cache_helper
::purge_by_event('changesincoursecat');
2398 // Test for and remove blocks which aren't appropriate anymore
2399 blocks_remove_inappropriate($course);
2401 // Save any custom role names.
2402 save_local_role_names($course->id
, $data);
2404 // update enrol settings
2405 enrol_course_updated(false, $course, $data);
2407 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
2410 events_trigger('course_updated', $course);
2412 if ($oldcourse->format
!== $course->format
) {
2413 // Remove all options stored for the previous format
2414 // We assume that new course format migrated everything it needed watching trigger
2415 // 'course_updated' and in method format_XXX::update_course_format_options()
2416 $DB->delete_records('course_format_options',
2417 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
2422 * Average number of participants
2425 function average_number_of_participants() {
2428 //count total of enrolments for visible course (except front page)
2429 $sql = 'SELECT COUNT(*) FROM (
2430 SELECT DISTINCT ue.userid, e.courseid
2431 FROM {user_enrolments} ue, {enrol} e, {course} c
2432 WHERE ue.enrolid = e.id
2433 AND e.courseid <> :siteid
2434 AND c.id = e.courseid
2435 AND c.visible = 1) total';
2436 $params = array('siteid' => $SITE->id
);
2437 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2440 //count total of visible courses (minus front page)
2441 $coursetotal = $DB->count_records('course', array('visible' => 1));
2442 $coursetotal = $coursetotal - 1 ;
2444 //average of enrolment
2445 if (empty($coursetotal)) {
2446 $participantaverage = 0;
2448 $participantaverage = $enrolmenttotal / $coursetotal;
2451 return $participantaverage;
2455 * Average number of course modules
2458 function average_number_of_courses_modules() {
2461 //count total of visible course module (except front page)
2462 $sql = 'SELECT COUNT(*) FROM (
2463 SELECT cm.course, cm.module
2464 FROM {course} c, {course_modules} cm
2465 WHERE c.id = cm.course
2468 AND c.visible = 1) total';
2469 $params = array('siteid' => $SITE->id
);
2470 $moduletotal = $DB->count_records_sql($sql, $params);
2473 //count total of visible courses (minus front page)
2474 $coursetotal = $DB->count_records('course', array('visible' => 1));
2475 $coursetotal = $coursetotal - 1 ;
2477 //average of course module
2478 if (empty($coursetotal)) {
2479 $coursemoduleaverage = 0;
2481 $coursemoduleaverage = $moduletotal / $coursetotal;
2484 return $coursemoduleaverage;
2488 * This class pertains to course requests and contains methods associated with
2489 * create, approving, and removing course requests.
2491 * Please note we do not allow embedded images here because there is no context
2492 * to store them with proper access control.
2494 * @copyright 2009 Sam Hemelryk
2495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2498 * @property-read int $id
2499 * @property-read string $fullname
2500 * @property-read string $shortname
2501 * @property-read string $summary
2502 * @property-read int $summaryformat
2503 * @property-read int $summarytrust
2504 * @property-read string $reason
2505 * @property-read int $requester
2507 class course_request
{
2510 * This is the stdClass that stores the properties for the course request
2511 * and is externally accessed through the __get magic method
2514 protected $properties;
2517 * An array of options for the summary editor used by course request forms.
2518 * This is initially set by {@link summary_editor_options()}
2522 protected static $summaryeditoroptions;
2525 * Static function to prepare the summary editor for working with a course
2529 * @param null|stdClass $data Optional, an object containing the default values
2530 * for the form, these may be modified when preparing the
2531 * editor so this should be called before creating the form
2532 * @return stdClass An object that can be used to set the default values for
2535 public static function prepare($data=null) {
2536 if ($data === null) {
2537 $data = new stdClass
;
2539 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
2544 * Static function to create a new course request when passed an array of properties
2547 * This function also handles saving any files that may have been used in the editor
2550 * @param stdClass $data
2551 * @return course_request The newly created course request
2553 public static function create($data) {
2554 global $USER, $DB, $CFG;
2555 $data->requester
= $USER->id
;
2557 // Setting the default category if none set.
2558 if (empty($data->category
) ||
empty($CFG->requestcategoryselection
)) {
2559 $data->category
= $CFG->defaultrequestcategory
;
2562 // Summary is a required field so copy the text over
2563 $data->summary
= $data->summary_editor
['text'];
2564 $data->summaryformat
= $data->summary_editor
['format'];
2566 $data->id
= $DB->insert_record('course_request', $data);
2568 // Create a new course_request object and return it
2569 $request = new course_request($data);
2571 // Notify the admin if required.
2572 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
2575 $a->link
= "$CFG->wwwroot/course/pending.php";
2576 $a->user
= fullname($USER);
2577 $subject = get_string('courserequest');
2578 $message = get_string('courserequestnotifyemail', 'admin', $a);
2579 foreach ($users as $user) {
2580 $request->notify($user, $USER, 'courserequested', $subject, $message);
2588 * Returns an array of options to use with a summary editor
2590 * @uses course_request::$summaryeditoroptions
2591 * @return array An array of options to use with the editor
2593 public static function summary_editor_options() {
2595 if (self
::$summaryeditoroptions === null) {
2596 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2598 return self
::$summaryeditoroptions;
2602 * Loads the properties for this course request object. Id is required and if
2603 * only id is provided then we load the rest of the properties from the database
2605 * @param stdClass|int $properties Either an object containing properties
2606 * or the course_request id to load
2608 public function __construct($properties) {
2610 if (empty($properties->id
)) {
2611 if (empty($properties)) {
2612 throw new coding_exception('You must provide a course request id when creating a course_request object');
2615 $properties = new stdClass
;
2616 $properties->id
= (int)$id;
2619 if (empty($properties->requester
)) {
2620 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
2621 print_error('unknowncourserequest');
2624 $this->properties
= $properties;
2626 $this->properties
->collision
= null;
2630 * Returns the requested property
2632 * @param string $key
2635 public function __get($key) {
2636 return $this->properties
->$key;
2640 * Override this to ensure empty($request->blah) calls return a reliable answer...
2642 * This is required because we define the __get method
2645 * @return bool True is it not empty, false otherwise
2647 public function __isset($key) {
2648 return (!empty($this->properties
->$key));
2652 * Returns the user who requested this course
2654 * Uses a static var to cache the results and cut down the number of db queries
2656 * @staticvar array $requesters An array of cached users
2657 * @return stdClass The user who requested the course
2659 public function get_requester() {
2661 static $requesters= array();
2662 if (!array_key_exists($this->properties
->requester
, $requesters)) {
2663 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
2665 return $requesters[$this->properties
->requester
];
2669 * Checks that the shortname used by the course does not conflict with any other
2670 * courses that exist
2672 * @param string|null $shortnamemark The string to append to the requests shortname
2673 * should a conflict be found
2674 * @return bool true is there is a conflict, false otherwise
2676 public function check_shortname_collision($shortnamemark = '[*]') {
2679 if ($this->properties
->collision
!== null) {
2680 return $this->properties
->collision
;
2683 if (empty($this->properties
->shortname
)) {
2684 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
2685 $this->properties
->collision
= false;
2686 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
2687 if (!empty($shortnamemark)) {
2688 $this->properties
->shortname
.= ' '.$shortnamemark;
2690 $this->properties
->collision
= true;
2692 $this->properties
->collision
= false;
2694 return $this->properties
->collision
;
2698 * Returns the category where this course request should be created
2700 * Note that we don't check here that user has a capability to view
2701 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2702 * 'moodle/course:changecategory'
2706 public function get_category() {
2708 require_once($CFG->libdir
.'/coursecatlib.php');
2709 // If the category is not set, if the current user does not have the rights to change the category, or if the
2710 // category does not exist, we set the default category to the course to be approved.
2711 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2712 if (empty($this->properties
->category
) ||
!has_capability('moodle/course:changecategory', context_system
::instance()) ||
2713 (!$category = coursecat
::get($this->properties
->category
, IGNORE_MISSING
, true))) {
2714 $category = coursecat
::get($CFG->defaultrequestcategory
, IGNORE_MISSING
, true);
2717 $category = coursecat
::get_default();
2723 * This function approves the request turning it into a course
2725 * This function converts the course request into a course, at the same time
2726 * transferring any files used in the summary to the new course and then removing
2727 * the course request and the files associated with it.
2729 * @return int The id of the course that was created from this request
2731 public function approve() {
2732 global $CFG, $DB, $USER;
2734 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
2736 $courseconfig = get_config('moodlecourse');
2738 // Transfer appropriate settings
2739 $data = clone($this->properties
);
2741 unset($data->reason
);
2742 unset($data->requester
);
2745 $category = $this->get_category();
2746 $data->category
= $category->id
;
2747 // Set misc settings
2748 $data->requested
= 1;
2750 // Apply course default settings
2751 $data->format
= $courseconfig->format
;
2752 $data->newsitems
= $courseconfig->newsitems
;
2753 $data->showgrades
= $courseconfig->showgrades
;
2754 $data->showreports
= $courseconfig->showreports
;
2755 $data->maxbytes
= $courseconfig->maxbytes
;
2756 $data->groupmode
= $courseconfig->groupmode
;
2757 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
2758 $data->visible
= $courseconfig->visible
;
2759 $data->visibleold
= $data->visible
;
2760 $data->lang
= $courseconfig->lang
;
2762 $course = create_course($data);
2763 $context = context_course
::instance($course->id
, MUST_EXIST
);
2765 // add enrol instances
2766 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
2767 if ($manual = enrol_get_plugin('manual')) {
2768 $manual->add_default_instance($course);
2772 // enrol the requester as teacher if necessary
2773 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2774 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
2779 $a = new stdClass();
2780 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2781 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
2782 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2788 * Reject a course request
2790 * This function rejects a course request, emailing the requesting user the
2791 * provided notice and then removing the request from the database
2793 * @param string $notice The message to display to the user
2795 public function reject($notice) {
2797 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
2798 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2803 * Deletes the course request and any associated files
2805 public function delete() {
2807 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
2811 * Send a message from one user to another using events_trigger
2813 * @param object $touser
2814 * @param object $fromuser
2815 * @param string $name
2816 * @param string $subject
2817 * @param string $message
2819 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
2820 $eventdata = new stdClass();
2821 $eventdata->component
= 'moodle';
2822 $eventdata->name
= $name;
2823 $eventdata->userfrom
= $fromuser;
2824 $eventdata->userto
= $touser;
2825 $eventdata->subject
= $subject;
2826 $eventdata->fullmessage
= $message;
2827 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
2828 $eventdata->fullmessagehtml
= '';
2829 $eventdata->smallmessage
= '';
2830 $eventdata->notification
= 1;
2831 message_send($eventdata);
2836 * Return a list of page types
2837 * @param string $pagetype current page type
2838 * @param context $parentcontext Block's parent context
2839 * @param context $currentcontext Current context of block
2840 * @return array array of page types
2842 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2843 if ($pagetype === 'course-index' ||
$pagetype === 'course-index-category') {
2844 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2845 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2846 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2848 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) ||
$coursecontext->instanceid
== SITEID
)) {
2849 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2850 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2852 // Otherwise consider it a page inside a course even if $currentcontext is null
2853 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2854 'course-*' => get_string('page-course-x', 'pagetype'),
2855 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2862 * Determine whether course ajax should be enabled for the specified course
2864 * @param stdClass $course The course to test against
2865 * @return boolean Whether course ajax is enabled or note
2867 function course_ajax_enabled($course) {
2868 global $CFG, $PAGE, $SITE;
2870 // Ajax must be enabled globally
2871 if (!$CFG->enableajax
) {
2875 // The user must be editing for AJAX to be included
2876 if (!$PAGE->user_is_editing()) {
2880 // Check that the theme suports
2881 if (!$PAGE->theme
->enablecourseajax
) {
2885 // Check that the course format supports ajax functionality
2886 // The site 'format' doesn't have information on course format support
2887 if ($SITE->id
!== $course->id
) {
2888 $courseformatajaxsupport = course_format_ajax_support($course->format
);
2889 if (!$courseformatajaxsupport->capable
) {
2894 // All conditions have been met so course ajax should be enabled
2899 * Include the relevant javascript and language strings for the resource
2900 * toolbox YUI module
2902 * @param integer $id The ID of the course being applied to
2903 * @param array $usedmodules An array containing the names of the modules in use on the page
2904 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2905 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2906 * * resourceurl The URL to post changes to for resource changes
2907 * * sectionurl The URL to post changes to for section changes
2908 * * pageparams Additional parameters to pass through in the post
2911 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2912 global $PAGE, $SITE;
2914 // Ensure that ajax should be included
2915 if (!course_ajax_enabled($course)) {
2920 $config = new stdClass();
2923 // The URL to use for resource changes
2924 if (!isset($config->resourceurl
)) {
2925 $config->resourceurl
= '/course/rest.php';
2928 // The URL to use for section changes
2929 if (!isset($config->sectionurl
)) {
2930 $config->sectionurl
= '/course/rest.php';
2933 // Any additional parameters which need to be included on page submission
2934 if (!isset($config->pageparams
)) {
2935 $config->pageparams
= array();
2938 // Include toolboxes
2939 $PAGE->requires
->yui_module('moodle-course-toolboxes',
2940 'M.course.init_resource_toolbox',
2942 'courseid' => $course->id
,
2943 'ajaxurl' => $config->resourceurl
,
2944 'config' => $config,
2947 $PAGE->requires
->yui_module('moodle-course-toolboxes',
2948 'M.course.init_section_toolbox',
2950 'courseid' => $course->id
,
2951 'format' => $course->format
,
2952 'ajaxurl' => $config->sectionurl
,
2953 'config' => $config,
2957 // Include course dragdrop
2958 if ($course->id
!= $SITE->id
) {
2959 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
2961 'courseid' => $course->id
,
2962 'ajaxurl' => $config->sectionurl
,
2963 'config' => $config,
2966 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
2968 'courseid' => $course->id
,
2969 'ajaxurl' => $config->resourceurl
,
2970 'config' => $config,
2974 // Require various strings for the command toolbox
2975 $PAGE->requires
->strings_for_js(array(
2978 'deletechecktypename',
2980 'edittitleinstructions',
2986 'clicktochangeinbrackets',
2993 // Include format-specific strings
2994 if ($course->id
!= $SITE->id
) {
2995 $PAGE->requires
->strings_for_js(array(
2998 ), 'format_' . $course->format
);
3001 // For confirming resource deletion we need the name of the module in question
3002 foreach ($usedmodules as $module => $modname) {
3003 $PAGE->requires
->string_for_js('pluginname', $module);
3006 // Load drag and drop upload AJAX.
3007 dndupload_add_to_course($course, $enabledmodules);
3013 * Returns the sorted list of available course formats, filtered by enabled if necessary
3015 * @param bool $enabledonly return only formats that are enabled
3016 * @return array array of sorted format names
3018 function get_sorted_course_formats($enabledonly = false) {
3020 $formats = get_plugin_list('format');
3022 if (!empty($CFG->format_plugins_sortorder
)) {
3023 $order = explode(',', $CFG->format_plugins_sortorder
);
3024 $order = array_merge(array_intersect($order, array_keys($formats)),
3025 array_diff(array_keys($formats), $order));
3027 $order = array_keys($formats);
3029 if (!$enabledonly) {
3032 $sortedformats = array();
3033 foreach ($order as $formatname) {
3034 if (!get_config('format_'.$formatname, 'disabled')) {
3035 $sortedformats[] = $formatname;
3038 return $sortedformats;
3042 * The URL to use for the specified course (with section)
3044 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3045 * @param int|stdClass $section Section object from database or just field course_sections.section
3046 * if omitted the course view page is returned
3047 * @param array $options options for view URL. At the moment core uses:
3048 * 'navigation' (bool) if true and section has no separate page, the function returns null
3049 * 'sr' (int) used by multipage formats to specify to which section to return
3050 * @return moodle_url The url of course
3052 function course_get_url($courseorid, $section = null, $options = array()) {
3053 return course_get_format($courseorid)->get_view_url($section, $options);
3060 * - capability checks and other checks
3061 * - create the module from the module info
3063 * @param object $module
3064 * @return object the created module info
3066 function create_module($moduleinfo) {
3069 require_once($CFG->dirroot
. '/course/modlib.php');
3071 // Check manadatory attributs.
3072 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3073 if (plugin_supports('mod', $moduleinfo->modulename
, FEATURE_MOD_INTRO
, true)) {
3074 $mandatoryfields[] = 'introeditor';
3076 foreach($mandatoryfields as $mandatoryfield) {
3077 if (!isset($moduleinfo->{$mandatoryfield})) {
3078 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3082 // Some additional checks (capability / existing instances).
3083 $course = $DB->get_record('course', array('id'=>$moduleinfo->course
), '*', MUST_EXIST
);
3084 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename
, $moduleinfo->section
);
3086 // Load module library.
3087 include_modulelib($module->name
);
3090 $moduleinfo->module
= $module->id
;
3091 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3100 * - capability and other checks
3101 * - update the module
3103 * @param object $module
3104 * @return object the updated module info
3106 function update_module($moduleinfo) {
3109 require_once($CFG->dirroot
. '/course/modlib.php');
3111 // Check the course module exists.
3112 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule
, 0, false, MUST_EXIST
);
3114 // Check the course exists.
3115 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
3117 // Some checks (capaibility / existing instances).
3118 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3120 // Load module library.
3121 include_modulelib($module->name
);
3123 // Retrieve few information needed by update_moduleinfo.
3124 $moduleinfo->modulename
= $cm->modname
;
3125 if (!isset($moduleinfo->scale
)) {
3126 $moduleinfo->scale
= 0;
3128 $moduleinfo->type
= 'mod';
3130 // Update the module.
3131 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3137 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3138 * Sorts by descending order of time.
3140 * @param stdClass $a First object
3141 * @param stdClass $b Second object
3142 * @return int 0,1,-1 representing the order
3144 function compare_activities_by_time_desc($a, $b) {
3145 // Make sure the activities actually have a timestamp property.
3146 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3149 // We treat instances without timestamp as if they have a timestamp of 0.
3150 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3153 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3156 if ($a->timestamp
== $b->timestamp
) {
3159 return ($a->timestamp
> $b->timestamp
) ?
-1 : 1;
3163 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3164 * Sorts by ascending order of time.
3166 * @param stdClass $a First object
3167 * @param stdClass $b Second object
3168 * @return int 0,1,-1 representing the order
3170 function compare_activities_by_time_asc($a, $b) {
3171 // Make sure the activities actually have a timestamp property.
3172 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3175 // We treat instances without timestamp as if they have a timestamp of 0.
3176 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3179 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3182 if ($a->timestamp
== $b->timestamp
) {
3185 return ($a->timestamp
< $b->timestamp
) ?
-1 : 1;