MDL-31011 course: Fixed typo in comment
[moodle.git] / course / lib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Library of useful functions
20  *
21  * @copyright 1999 Martin Dougiamas  http://dougiamas.com
22  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  * @package core
24  * @subpackage course
25  */
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
32 define('COURSE_MAX_LOGS_PER_PAGE', 1000);       // records
33 define('COURSE_MAX_RECENT_PERIOD', 172800);     // Two days, in seconds
34 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);    // courses
35 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); //  max courses in log dropdown before switching to optional
36 define('COURSE_MAX_USERS_PER_DROPDOWN',1000);   //  max users in log dropdown before switching to optional
37 define('FRONTPAGENEWS',           '0');
38 define('FRONTPAGECOURSELIST',     '1');
39 define('FRONTPAGECATEGORYNAMES',  '2');
40 define('FRONTPAGETOPICONLY',      '3');
41 define('FRONTPAGECATEGORYCOMBO',  '4');
42 define('FRONTPAGECOURSELIMIT',    200);         // maximum number of courses displayed on the frontpage
43 define('EXCELROWS', 65535);
44 define('FIRSTUSEDEXCELROW', 3);
46 define('MOD_CLASS_ACTIVITY', 0);
47 define('MOD_CLASS_RESOURCE', 1);
49 function make_log_url($module, $url) {
50     switch ($module) {
51         case 'course':
52             if (strpos($url, 'report/') === 0) {
53                 // there is only one report type, course reports are deprecated
54                 $url = "/$url";
55                 break;
56             }
57         case 'file':
58         case 'login':
59         case 'lib':
60         case 'admin':
61         case 'calendar':
62         case 'mnet course':
63             if (strpos($url, '../') === 0) {
64                 $url = ltrim($url, '.');
65             } else {
66                 $url = "/course/$url";
67             }
68             break;
69         case 'user':
70         case 'blog':
71             $url = "/$module/$url";
72             break;
73         case 'upload':
74             $url = $url;
75             break;
76         case 'coursetags':
77             $url = '/'.$url;
78             break;
79         case 'library':
80         case '':
81             $url = '/';
82             break;
83         case 'message':
84             $url = "/message/$url";
85             break;
86         case 'notes':
87             $url = "/notes/$url";
88             break;
89         case 'tag':
90             $url = "/tag/$url";
91             break;
92         case 'role':
93             $url = '/'.$url;
94             break;
95         default:
96             $url = "/mod/$module/$url";
97             break;
98     }
100     //now let's sanitise urls - there might be some ugly nasties:-(
101     $parts = explode('?', $url);
102     $script = array_shift($parts);
103     if (strpos($script, 'http') === 0) {
104         $script = clean_param($script, PARAM_URL);
105     } else {
106         $script = clean_param($script, PARAM_PATH);
107     }
109     $query = '';
110     if ($parts) {
111         $query = implode('', $parts);
112         $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
113         $parts = explode('&', $query);
114         $eq = urlencode('=');
115         foreach ($parts as $key=>$part) {
116             $part = urlencode(urldecode($part));
117             $part = str_replace($eq, '=', $part);
118             $parts[$key] = $part;
119         }
120         $query = '?'.implode('&amp;', $parts);
121     }
123     return $script.$query;
127 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
128                    $modname="", $modid=0, $modaction="", $groupid=0) {
129     global $CFG, $DB;
131     // It is assumed that $date is the GMT time of midnight for that day,
132     // and so the next 86400 seconds worth of logs are printed.
134     /// Setup for group handling.
136     // TODO: I don't understand group/context/etc. enough to be able to do
137     // something interesting with it here
138     // What is the context of a remote course?
140     /// If the group mode is separate, and this user does not have editing privileges,
141     /// then only the user's group can be viewed.
142     //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
143     //    $groupid = get_current_group($course->id);
144     //}
145     /// If this course doesn't have groups, no groupid can be specified.
146     //else if (!$course->groupmode) {
147     //    $groupid = 0;
148     //}
150     $groupid = 0;
152     $joins = array();
154     $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
155               FROM {mnet_log} l
156                LEFT JOIN {user} u ON l.userid = u.id
157               WHERE ";
158     $params = array();
160     $where .= "l.hostid = :hostid";
161     $params['hostid'] = $hostid;
163     // TODO: Is 1 really a magic number referring to the sitename?
164     if ($course != SITEID || $modid != 0) {
165         $where .= " AND l.course=:courseid";
166         $params['courseid'] = $course;
167     }
169     if ($modname) {
170         $where .= " AND l.module = :modname";
171         $params['modname'] = $modname;
172     }
174     if ('site_errors' === $modid) {
175         $where .= " AND ( l.action='error' OR l.action='infected' )";
176     } else if ($modid) {
177         //TODO: This assumes that modids are the same across sites... probably
178         //not true
179         $where .= " AND l.cmid = :modid";
180         $params['modid'] = $modid;
181     }
183     if ($modaction) {
184         $firstletter = substr($modaction, 0, 1);
185         if ($firstletter == '-') {
186             $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
187             $params['modaction'] = '%'.substr($modaction, 1).'%';
188         } else {
189             $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
190             $params['modaction'] = '%'.$modaction.'%';
191         }
192     }
194     if ($user) {
195         $where .= " AND l.userid = :user";
196         $params['user'] = $user;
197     }
199     if ($date) {
200         $enddate = $date + 86400;
201         $where .= " AND l.time > :date AND l.time < :enddate";
202         $params['date'] = $date;
203         $params['enddate'] = $enddate;
204     }
206     $result = array();
207     $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
208     if(!empty($result['totalcount'])) {
209         $where .= " ORDER BY $order";
210         $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
211     } else {
212         $result['logs'] = array();
213     }
214     return $result;
217 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
218                    $modname="", $modid=0, $modaction="", $groupid=0) {
219     global $DB, $SESSION, $USER;
220     // It is assumed that $date is the GMT time of midnight for that day,
221     // and so the next 86400 seconds worth of logs are printed.
223     /// Setup for group handling.
225     /// If the group mode is separate, and this user does not have editing privileges,
226     /// then only the user's group can be viewed.
227     if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
228         if (isset($SESSION->currentgroup[$course->id])) {
229             $groupid =  $SESSION->currentgroup[$course->id];
230         } else {
231             $groupid = groups_get_all_groups($course->id, $USER->id);
232             if (is_array($groupid)) {
233                 $groupid = array_shift(array_keys($groupid));
234                 $SESSION->currentgroup[$course->id] = $groupid;
235             } else {
236                 $groupid = 0;
237             }
238         }
239     }
240     /// If this course doesn't have groups, no groupid can be specified.
241     else if (!$course->groupmode) {
242         $groupid = 0;
243     }
245     $joins = array();
246     $params = array();
248     if ($course->id != SITEID || $modid != 0) {
249         $joins[] = "l.course = :courseid";
250         $params['courseid'] = $course->id;
251     }
253     if ($modname) {
254         $joins[] = "l.module = :modname";
255         $params['modname'] = $modname;
256     }
258     if ('site_errors' === $modid) {
259         $joins[] = "( l.action='error' OR l.action='infected' )";
260     } else if ($modid) {
261         $joins[] = "l.cmid = :modid";
262         $params['modid'] = $modid;
263     }
265     if ($modaction) {
266         $firstletter = substr($modaction, 0, 1);
267         if ($firstletter == '-') {
268             $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
269             $params['modaction'] = '%'.substr($modaction, 1).'%';
270         } else {
271             $joins[] = $DB->sql_like('l.action', ':modaction', false);
272             $params['modaction'] = '%'.$modaction.'%';
273         }
274     }
277     /// Getting all members of a group.
278     if ($groupid and !$user) {
279         if ($gusers = groups_get_members($groupid)) {
280             $gusers = array_keys($gusers);
281             $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
282         } else {
283             $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
284         }
285     }
286     else if ($user) {
287         $joins[] = "l.userid = :userid";
288         $params['userid'] = $user;
289     }
291     if ($date) {
292         $enddate = $date + 86400;
293         $joins[] = "l.time > :date AND l.time < :enddate";
294         $params['date'] = $date;
295         $params['enddate'] = $enddate;
296     }
298     $selector = implode(' AND ', $joins);
300     $totalcount = 0;  // Initialise
301     $result = array();
302     $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
303     $result['totalcount'] = $totalcount;
304     return $result;
308 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
309                    $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
311     global $CFG, $DB, $OUTPUT;
313     if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
314                        $modname, $modid, $modaction, $groupid)) {
315         echo $OUTPUT->notification("No logs found!");
316         echo $OUTPUT->footer();
317         exit;
318     }
320     $courses = array();
322     if ($course->id == SITEID) {
323         $courses[0] = '';
324         if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
325             foreach ($ccc as $cc) {
326                 $courses[$cc->id] = $cc->shortname;
327             }
328         }
329     } else {
330         $courses[$course->id] = $course->shortname;
331     }
333     $totalcount = $logs['totalcount'];
334     $count=0;
335     $ldcache = array();
336     $tt = getdate(time());
337     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
339     $strftimedatetime = get_string("strftimedatetime");
341     echo "<div class=\"info\">\n";
342     print_string("displayingrecords", "", $totalcount);
343     echo "</div>\n";
345     echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
347     $table = new html_table();
348     $table->classes = array('logtable','generalbox');
349     $table->align = array('right', 'left', 'left');
350     $table->head = array(
351         get_string('time'),
352         get_string('ip_address'),
353         get_string('fullnameuser'),
354         get_string('action'),
355         get_string('info')
356     );
357     $table->data = array();
359     if ($course->id == SITEID) {
360         array_unshift($table->align, 'left');
361         array_unshift($table->head, get_string('course'));
362     }
364     // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
365     if (empty($logs['logs'])) {
366         $logs['logs'] = array();
367     }
369     foreach ($logs['logs'] as $log) {
371         if (isset($ldcache[$log->module][$log->action])) {
372             $ld = $ldcache[$log->module][$log->action];
373         } else {
374             $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
375             $ldcache[$log->module][$log->action] = $ld;
376         }
377         if ($ld && is_numeric($log->info)) {
378             // ugly hack to make sure fullname is shown correctly
379             if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
380                 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
381             } else {
382                 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
383             }
384         }
386         //Filter log->info
387         $log->info = format_string($log->info);
389         // If $log->url has been trimmed short by the db size restriction
390         // code in add_to_log, keep a note so we don't add a link to a broken url
391         $tl=textlib_get_instance();
392         $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
394         $row = array();
395         if ($course->id == SITEID) {
396             if (empty($log->course)) {
397                 $row[] = get_string('site');
398             } else {
399                 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
400             }
401         }
403         $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
405         $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
406         $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
408         $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))));
410         $displayaction="$log->module $log->action";
411         if ($brokenurl) {
412             $row[] = $displayaction;
413         } else {
414             $link = make_log_url($log->module,$log->url);
415             $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
416         }
417         $row[] = $log->info;
418         $table->data[] = $row;
419     }
421     echo html_writer::table($table);
422     echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
426 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
427                    $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
429     global $CFG, $DB, $OUTPUT;
431     if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
432                        $modname, $modid, $modaction, $groupid)) {
433         echo $OUTPUT->notification("No logs found!");
434         echo $OUTPUT->footer();
435         exit;
436     }
438     if ($course->id == SITEID) {
439         $courses[0] = '';
440         if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
441             foreach ($ccc as $cc) {
442                 $courses[$cc->id] = $cc->shortname;
443             }
444         }
445     }
447     $totalcount = $logs['totalcount'];
448     $count=0;
449     $ldcache = array();
450     $tt = getdate(time());
451     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
453     $strftimedatetime = get_string("strftimedatetime");
455     echo "<div class=\"info\">\n";
456     print_string("displayingrecords", "", $totalcount);
457     echo "</div>\n";
459     echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
461     echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
462     echo "<tr>";
463     if ($course->id == SITEID) {
464         echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
465     }
466     echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
467     echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
468     echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
469     echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
470     echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
471     echo "</tr>\n";
473     if (empty($logs['logs'])) {
474         echo "</table>\n";
475         return;
476     }
478     $row = 1;
479     foreach ($logs['logs'] as $log) {
481         $log->info = $log->coursename;
482         $row = ($row + 1) % 2;
484         if (isset($ldcache[$log->module][$log->action])) {
485             $ld = $ldcache[$log->module][$log->action];
486         } else {
487             $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
488             $ldcache[$log->module][$log->action] = $ld;
489         }
490         if (0 && $ld && !empty($log->info)) {
491             // ugly hack to make sure fullname is shown correctly
492             if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
493                 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
494             } else {
495                 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
496             }
497         }
499         //Filter log->info
500         $log->info = format_string($log->info);
502         echo '<tr class="r'.$row.'">';
503         if ($course->id == SITEID) {
504             $courseshortname = format_string($courses[$log->course], true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
505             echo "<td class=\"r$row c0\" >\n";
506             echo "    <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
507             echo "</td>\n";
508         }
509         echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
510              ' '.userdate($log->time, $strftimedatetime)."</td>\n";
511         echo "<td class=\"r$row c2\" >\n";
512         $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
513         echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
514         echo "</td>\n";
515         $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
516         echo "<td class=\"r$row c3\" >\n";
517         echo "    <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
518         echo "</td>\n";
519         echo "<td class=\"r$row c4\">\n";
520         echo $log->action .': '.$log->module;
521         echo "</td>\n";;
522         echo "<td class=\"r$row c5\">{$log->info}</td>\n";
523         echo "</tr>\n";
524     }
525     echo "</table>\n";
527     echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
531 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
532                         $modid, $modaction, $groupid) {
533     global $DB;
535     $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
536             get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
538     if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
539                        $modname, $modid, $modaction, $groupid)) {
540         return false;
541     }
543     $courses = array();
545     if ($course->id == SITEID) {
546         $courses[0] = '';
547         if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
548             foreach ($ccc as $cc) {
549                 $courses[$cc->id] = $cc->shortname;
550             }
551         }
552     } else {
553         $courses[$course->id] = $course->shortname;
554     }
556     $count=0;
557     $ldcache = array();
558     $tt = getdate(time());
559     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
561     $strftimedatetime = get_string("strftimedatetime");
563     $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
564     $filename .= '.txt';
565     header("Content-Type: application/download\n");
566     header("Content-Disposition: attachment; filename=$filename");
567     header("Expires: 0");
568     header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
569     header("Pragma: public");
571     echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
572     echo $text."\n";
574     if (empty($logs['logs'])) {
575         return true;
576     }
578     foreach ($logs['logs'] as $log) {
579         if (isset($ldcache[$log->module][$log->action])) {
580             $ld = $ldcache[$log->module][$log->action];
581         } else {
582             $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
583             $ldcache[$log->module][$log->action] = $ld;
584         }
585         if ($ld && !empty($log->info)) {
586             // ugly hack to make sure fullname is shown correctly
587             if (($ld->mtable == 'user') and ($ld->field ==  $DB->sql_concat('firstname', "' '" , 'lastname'))) {
588                 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
589             } else {
590                 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
591             }
592         }
594         //Filter log->info
595         $log->info = format_string($log->info);
596         $log->info = strip_tags(urldecode($log->info));    // Some XSS protection
598         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
599         $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
600         $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
601         $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
602         $text = implode("\t", $row);
603         echo $text." \n";
604     }
605     return true;
609 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
610                         $modid, $modaction, $groupid) {
612     global $CFG, $DB;
614     require_once("$CFG->libdir/excellib.class.php");
616     if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
617                        $modname, $modid, $modaction, $groupid)) {
618         return false;
619     }
621     $courses = array();
623     if ($course->id == SITEID) {
624         $courses[0] = '';
625         if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
626             foreach ($ccc as $cc) {
627                 $courses[$cc->id] = $cc->shortname;
628             }
629         }
630     } else {
631         $courses[$course->id] = $course->shortname;
632     }
634     $count=0;
635     $ldcache = array();
636     $tt = getdate(time());
637     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
639     $strftimedatetime = get_string("strftimedatetime");
641     $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
642     $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
643     $filename .= '.xls';
645     $workbook = new MoodleExcelWorkbook('-');
646     $workbook->send($filename);
648     $worksheet = array();
649     $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
650                         get_string('fullnameuser'),    get_string('action'), get_string('info'));
652     // Creating worksheets
653     for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
654         $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
655         $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
656         $worksheet[$wsnumber]->set_column(1, 1, 30);
657         $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
658                                     userdate(time(), $strftimedatetime));
659         $col = 0;
660         foreach ($headers as $item) {
661             $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
662             $col++;
663         }
664     }
666     if (empty($logs['logs'])) {
667         $workbook->close();
668         return true;
669     }
671     $formatDate =& $workbook->add_format();
672     $formatDate->set_num_format(get_string('log_excel_date_format'));
674     $row = FIRSTUSEDEXCELROW;
675     $wsnumber = 1;
676     $myxls =& $worksheet[$wsnumber];
677     foreach ($logs['logs'] as $log) {
678         if (isset($ldcache[$log->module][$log->action])) {
679             $ld = $ldcache[$log->module][$log->action];
680         } else {
681             $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
682             $ldcache[$log->module][$log->action] = $ld;
683         }
684         if ($ld && !empty($log->info)) {
685             // ugly hack to make sure fullname is shown correctly
686             if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
687                 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
688             } else {
689                 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
690             }
691         }
693         // Filter log->info
694         $log->info = format_string($log->info);
695         $log->info = strip_tags(urldecode($log->info));  // Some XSS protection
697         if ($nroPages>1) {
698             if ($row > EXCELROWS) {
699                 $wsnumber++;
700                 $myxls =& $worksheet[$wsnumber];
701                 $row = FIRSTUSEDEXCELROW;
702             }
703         }
705         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
707         $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
708         $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
709         $myxls->write($row, 2, $log->ip, '');
710         $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
711         $myxls->write($row, 3, $fullname, '');
712         $myxls->write($row, 4, $log->module.' '.$log->action, '');
713         $myxls->write($row, 5, $log->info, '');
715         $row++;
716     }
718     $workbook->close();
719     return true;
722 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
723                         $modid, $modaction, $groupid) {
725     global $CFG, $DB;
727     require_once("$CFG->libdir/odslib.class.php");
729     if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
730                        $modname, $modid, $modaction, $groupid)) {
731         return false;
732     }
734     $courses = array();
736     if ($course->id == SITEID) {
737         $courses[0] = '';
738         if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
739             foreach ($ccc as $cc) {
740                 $courses[$cc->id] = $cc->shortname;
741             }
742         }
743     } else {
744         $courses[$course->id] = $course->shortname;
745     }
747     $count=0;
748     $ldcache = array();
749     $tt = getdate(time());
750     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
752     $strftimedatetime = get_string("strftimedatetime");
754     $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
755     $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
756     $filename .= '.ods';
758     $workbook = new MoodleODSWorkbook('-');
759     $workbook->send($filename);
761     $worksheet = array();
762     $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
763                         get_string('fullnameuser'),    get_string('action'), get_string('info'));
765     // Creating worksheets
766     for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
767         $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
768         $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
769         $worksheet[$wsnumber]->set_column(1, 1, 30);
770         $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
771                                     userdate(time(), $strftimedatetime));
772         $col = 0;
773         foreach ($headers as $item) {
774             $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
775             $col++;
776         }
777     }
779     if (empty($logs['logs'])) {
780         $workbook->close();
781         return true;
782     }
784     $formatDate =& $workbook->add_format();
785     $formatDate->set_num_format(get_string('log_excel_date_format'));
787     $row = FIRSTUSEDEXCELROW;
788     $wsnumber = 1;
789     $myxls =& $worksheet[$wsnumber];
790     foreach ($logs['logs'] as $log) {
791         if (isset($ldcache[$log->module][$log->action])) {
792             $ld = $ldcache[$log->module][$log->action];
793         } else {
794             $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
795             $ldcache[$log->module][$log->action] = $ld;
796         }
797         if ($ld && !empty($log->info)) {
798             // ugly hack to make sure fullname is shown correctly
799             if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
800                 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
801             } else {
802                 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
803             }
804         }
806         // Filter log->info
807         $log->info = format_string($log->info);
808         $log->info = strip_tags(urldecode($log->info));  // Some XSS protection
810         if ($nroPages>1) {
811             if ($row > EXCELROWS) {
812                 $wsnumber++;
813                 $myxls =& $worksheet[$wsnumber];
814                 $row = FIRSTUSEDEXCELROW;
815             }
816         }
818         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
820         $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $context)));
821         $myxls->write_date($row, 1, $log->time);
822         $myxls->write_string($row, 2, $log->ip);
823         $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
824         $myxls->write_string($row, 3, $fullname);
825         $myxls->write_string($row, 4, $log->module.' '.$log->action);
826         $myxls->write_string($row, 5, $log->info);
828         $row++;
829     }
831     $workbook->close();
832     return true;
836 function print_overview($courses, array $remote_courses=array()) {
837     global $CFG, $USER, $DB, $OUTPUT;
839     $htmlarray = array();
840     if ($modules = $DB->get_records('modules')) {
841         foreach ($modules as $mod) {
842             if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
843                 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
844                 $fname = $mod->name.'_print_overview';
845                 if (function_exists($fname)) {
846                     $fname($courses,$htmlarray);
847                 }
848             }
849         }
850     }
851     foreach ($courses as $course) {
852         $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
853         echo $OUTPUT->box_start('coursebox');
854         $attributes = array('title' => s($fullname));
855         if (empty($course->visible)) {
856             $attributes['class'] = 'dimmed';
857         }
858         echo $OUTPUT->heading(html_writer::link(
859             new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
860         if (array_key_exists($course->id,$htmlarray)) {
861             foreach ($htmlarray[$course->id] as $modname => $html) {
862                 echo $html;
863             }
864         }
865         echo $OUTPUT->box_end();
866     }
868     if (!empty($remote_courses)) {
869         echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
870     }
871     foreach ($remote_courses as $course) {
872         echo $OUTPUT->box_start('coursebox');
873         $attributes = array('title' => s($course->fullname));
874         echo $OUTPUT->heading(html_writer::link(
875             new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
876             format_string($course->shortname),
877             $attributes) . ' (' . format_string($course->hostname) . ')', 3);
878         echo $OUTPUT->box_end();
879     }
883 /**
884  * This function trawls through the logs looking for
885  * anything new since the user's last login
886  */
887 function print_recent_activity($course) {
888     // $course is an object
889     global $CFG, $USER, $SESSION, $DB, $OUTPUT;
891     $context = get_context_instance(CONTEXT_COURSE, $course->id);
893     $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
895     $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
897     if (!isguestuser()) {
898         if (!empty($USER->lastcourseaccess[$course->id])) {
899             if ($USER->lastcourseaccess[$course->id] > $timestart) {
900                 $timestart = $USER->lastcourseaccess[$course->id];
901             }
902         }
903     }
905     echo '<div class="activitydate">';
906     echo get_string('activitysince', '', userdate($timestart));
907     echo '</div>';
908     echo '<div class="activityhead">';
910     echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
912     echo "</div>\n";
914     $content = false;
916 /// Firstly, have there been any new enrolments?
918     $users = get_recent_enrolments($course->id, $timestart);
920     //Accessibility: new users now appear in an <OL> list.
921     if ($users) {
922         echo '<div class="newusers">';
923         echo $OUTPUT->heading(get_string("newusers").':', 3);
924         $content = true;
925         echo "<ol class=\"list\">\n";
926         foreach ($users as $user) {
927             $fullname = fullname($user, $viewfullnames);
928             echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
929         }
930         echo "</ol>\n</div>\n";
931     }
933 /// Next, have there been any modifications to the course structure?
935     $modinfo =& get_fast_modinfo($course);
937     $changelist = array();
939     $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
940                                             module = 'course' AND
941                                             (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
942                                     array($timestart, $course->id), "id ASC");
944     if ($logs) {
945         $actions  = array('add mod', 'update mod', 'delete mod');
946         $newgones = array(); // added and later deleted items
947         foreach ($logs as $key => $log) {
948             if (!in_array($log->action, $actions)) {
949                 continue;
950             }
951             $info = explode(' ', $log->info);
953             // note: in most cases I replaced hardcoding of label with use of
954             // $cm->has_view() but it was not possible to do this here because
955             // we don't necessarily have the $cm for it
956             if ($info[0] == 'label') {     // Labels are ignored in recent activity
957                 continue;
958             }
960             if (count($info) != 2) {
961                 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
962                 continue;
963             }
965             $modname    = $info[0];
966             $instanceid = $info[1];
968             if ($log->action == 'delete mod') {
969                 // unfortunately we do not know if the mod was visible
970                 if (!array_key_exists($log->info, $newgones)) {
971                     $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
972                     $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
973                 }
974             } else {
975                 if (!isset($modinfo->instances[$modname][$instanceid])) {
976                     if ($log->action == 'add mod') {
977                         // do not display added and later deleted activities
978                         $newgones[$log->info] = true;
979                     }
980                     continue;
981                 }
982                 $cm = $modinfo->instances[$modname][$instanceid];
983                 if (!$cm->uservisible) {
984                     continue;
985                 }
987                 if ($log->action == 'add mod') {
988                     $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
989                     $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
991                 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
992                     $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
993                     $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
994                 }
995             }
996         }
997     }
999     if (!empty($changelist)) {
1000         echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1001         $content = true;
1002         foreach ($changelist as $changeinfo => $change) {
1003             echo '<p class="activity">'.$change['text'].'</p>';
1004         }
1005     }
1007 /// Now display new things from each module
1009     $usedmodules = array();
1010     foreach($modinfo->cms as $cm) {
1011         if (isset($usedmodules[$cm->modname])) {
1012             continue;
1013         }
1014         if (!$cm->uservisible) {
1015             continue;
1016         }
1017         $usedmodules[$cm->modname] = $cm->modname;
1018     }
1020     foreach ($usedmodules as $modname) {      // Each module gets it's own logs and prints them
1021         if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1022             include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1023             $print_recent_activity = $modname.'_print_recent_activity';
1024             if (function_exists($print_recent_activity)) {
1025                 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1026                 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1027             }
1028         } else {
1029             debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1030         }
1031     }
1033     if (! $content) {
1034         echo '<p class="message">'.get_string('nothingnew').'</p>';
1035     }
1038 /**
1039  * For a given course, returns an array of course activity objects
1040  * Each item in the array contains he following properties:
1041  */
1042 function get_array_of_activities($courseid) {
1043 //  cm - course module id
1044 //  mod - name of the module (eg forum)
1045 //  section - the number of the section (eg week or topic)
1046 //  name - the name of the instance
1047 //  visible - is the instance visible or not
1048 //  groupingid - grouping id
1049 //  groupmembersonly - is this instance visible to group members only
1050 //  extra - contains extra string to include in any link
1051     global $CFG, $DB;
1052     if(!empty($CFG->enableavailability)) {
1053         require_once($CFG->libdir.'/conditionlib.php');
1054     }
1056     $course = $DB->get_record('course', array('id'=>$courseid));
1058     if (empty($course)) {
1059         throw new moodle_exception('courseidnotfound');
1060     }
1062     $mod = array();
1064     $rawmods = get_course_mods($courseid);
1065     if (empty($rawmods)) {
1066         return $mod; // always return array
1067     }
1069     if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1070        foreach ($sections as $section) {
1071            if (!empty($section->sequence)) {
1072                $sequence = explode(",", $section->sequence);
1073                foreach ($sequence as $seq) {
1074                    if (empty($rawmods[$seq])) {
1075                        continue;
1076                    }
1077                    $mod[$seq]->id               = $rawmods[$seq]->instance;
1078                    $mod[$seq]->cm               = $rawmods[$seq]->id;
1079                    $mod[$seq]->mod              = $rawmods[$seq]->modname;
1081                     // Oh dear. Inconsistent names left here for backward compatibility.
1082                    $mod[$seq]->section          = $section->section;
1083                    $mod[$seq]->sectionid        = $rawmods[$seq]->section;
1085                    $mod[$seq]->module           = $rawmods[$seq]->module;
1086                    $mod[$seq]->added            = $rawmods[$seq]->added;
1087                    $mod[$seq]->score            = $rawmods[$seq]->score;
1088                    $mod[$seq]->idnumber         = $rawmods[$seq]->idnumber;
1089                    $mod[$seq]->visible          = $rawmods[$seq]->visible;
1090                    $mod[$seq]->visibleold       = $rawmods[$seq]->visibleold;
1091                    $mod[$seq]->groupmode        = $rawmods[$seq]->groupmode;
1092                    $mod[$seq]->groupingid       = $rawmods[$seq]->groupingid;
1093                    $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1094                    $mod[$seq]->indent           = $rawmods[$seq]->indent;
1095                    $mod[$seq]->completion       = $rawmods[$seq]->completion;
1096                    $mod[$seq]->extra            = "";
1097                    $mod[$seq]->completiongradeitemnumber =
1098                            $rawmods[$seq]->completiongradeitemnumber;
1099                    $mod[$seq]->completionview   = $rawmods[$seq]->completionview;
1100                    $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1101                    $mod[$seq]->availablefrom    = $rawmods[$seq]->availablefrom;
1102                    $mod[$seq]->availableuntil   = $rawmods[$seq]->availableuntil;
1103                    $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1104                    $mod[$seq]->showdescription  = $rawmods[$seq]->showdescription;
1105                    if (!empty($CFG->enableavailability)) {
1106                        condition_info::fill_availability_conditions($rawmods[$seq]);
1107                        $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1108                        $mod[$seq]->conditionsgrade  = $rawmods[$seq]->conditionsgrade;
1109                    }
1111                    $modname = $mod[$seq]->mod;
1112                    $functionname = $modname."_get_coursemodule_info";
1114                    if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1115                        continue;
1116                    }
1118                    include_once("$CFG->dirroot/mod/$modname/lib.php");
1120                    if ($hasfunction = function_exists($functionname)) {
1121                        if ($info = $functionname($rawmods[$seq])) {
1122                            if (!empty($info->icon)) {
1123                                $mod[$seq]->icon = $info->icon;
1124                            }
1125                            if (!empty($info->iconcomponent)) {
1126                                $mod[$seq]->iconcomponent = $info->iconcomponent;
1127                            }
1128                            if (!empty($info->name)) {
1129                                $mod[$seq]->name = $info->name;
1130                            }
1131                            if ($info instanceof cached_cm_info) {
1132                                // When using cached_cm_info you can include three new fields
1133                                // that aren't available for legacy code
1134                                if (!empty($info->content)) {
1135                                    $mod[$seq]->content = $info->content;
1136                                }
1137                                if (!empty($info->extraclasses)) {
1138                                    $mod[$seq]->extraclasses = $info->extraclasses;
1139                                }
1140                                if (!empty($info->iconurl)) {
1141                                    $mod[$seq]->iconurl = $info->iconurl;
1142                                }
1143                                if (!empty($info->onclick)) {
1144                                    $mod[$seq]->onclick = $info->onclick;
1145                                }
1146                                if (!empty($info->customdata)) {
1147                                    $mod[$seq]->customdata = $info->customdata;
1148                                }
1149                            } else {
1150                                // When using a stdclass, the (horrible) deprecated ->extra field
1151                                // is available for BC
1152                                if (!empty($info->extra)) {
1153                                    $mod[$seq]->extra = $info->extra;
1154                                }
1155                            }
1156                        }
1157                    }
1158                    // When there is no modname_get_coursemodule_info function,
1159                    // but showdescriptions is enabled, then we use the 'intro'
1160                    // and 'introformat' fields in the module table
1161                    if (!$hasfunction && $rawmods[$seq]->showdescription) {
1162                        if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1163                                array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1164                            // Set content from intro and introformat. Filters are disabled
1165                            // because we  filter it with format_text at display time
1166                            $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1167                                    $modvalues, $rawmods[$seq]->id, false);
1169                            // To save making another query just below, put name in here
1170                            $mod[$seq]->name = $modvalues->name;
1171                        }
1172                    }
1173                    if (!isset($mod[$seq]->name)) {
1174                        $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1175                    }
1177                    // Minimise the database size by unsetting default options when they are
1178                    // 'empty'. This list corresponds to code in the cm_info constructor.
1179                    foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1180                            'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1181                            'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1182                            'availableuntil', 'conditionscompletion', 'conditionsgrade',
1183                            'completionview', 'completionexpected', 'score', 'showdescription')
1184                            as $property) {
1185                        if (property_exists($mod[$seq], $property) &&
1186                                empty($mod[$seq]->{$property})) {
1187                            unset($mod[$seq]->{$property});
1188                        }
1189                    }
1190                    // Special case: this value is usually set to null, but may be 0
1191                    if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1192                            is_null($mod[$seq]->completiongradeitemnumber)) {
1193                        unset($mod[$seq]->completiongradeitemnumber);
1194                    }
1195                }
1196             }
1197         }
1198     }
1199     return $mod;
1203 /**
1204  * Returns a number of useful structures for course displays
1205  */
1206 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1207     global $CFG, $DB, $COURSE;
1209     $mods          = array();    // course modules indexed by id
1210     $modnames      = array();    // all course module names (except resource!)
1211     $modnamesplural= array();    // all course module names (plural form)
1212     $modnamesused  = array();    // course module names used
1214     if ($allmods = $DB->get_records("modules")) {
1215         foreach ($allmods as $mod) {
1216             if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1217                 continue;
1218             }
1219             if ($mod->visible) {
1220                 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1221                 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1222             }
1223         }
1224         collatorlib::asort($modnames);
1225     } else {
1226         print_error("nomodules", 'debug');
1227     }
1229     $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1230     $modinfo = get_fast_modinfo($course);
1232     if ($rawmods=$modinfo->cms) {
1233         foreach($rawmods as $mod) {    // Index the mods
1234             if (empty($modnames[$mod->modname])) {
1235                 continue;
1236             }
1237             $mods[$mod->id] = $mod;
1238             $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1239             if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1240                 continue;
1241             }
1242             // Check groupings
1243             if (!groups_course_module_visible($mod)) {
1244                 continue;
1245             }
1246             $modnamesused[$mod->modname] = $modnames[$mod->modname];
1247         }
1248         if ($modnamesused) {
1249             collatorlib::asort($modnamesused);
1250         }
1251     }
1254 /**
1255  * Returns an array of sections for the requested course id
1256  *
1257  * This function stores the sections against the course id within a staticvar encase
1258  * of subsequent requests. This is used all over + in some standard libs and course
1259  * format callbacks so subsequent requests are a reality.
1260  *
1261  * @staticvar array $coursesections
1262  * @param int $courseid
1263  * @return array Array of sections
1264  */
1265 function get_all_sections($courseid) {
1266     global $DB;
1267     static $coursesections = array();
1268     if (!array_key_exists($courseid, $coursesections)) {
1269         $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1270                            "section, id, course, name, summary, summaryformat, sequence, visible");
1271     }
1272     return $coursesections[$courseid];
1275 /**
1276  * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1277  * It also sets the $USER->display cache to array($courseid=>return value)
1278  *
1279  * @param int $courseid The course id
1280  * @return int Course section to display, 0 means all
1281  */
1282 function course_get_display($courseid) {
1283     global $USER, $DB;
1285     if (!isloggedin() or isguestuser()) {
1286         //do not get settings in db for guests
1287         return 0; //return the implicit setting
1288     }
1290     if (!isset($USER->display[$courseid])) {
1291         if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id, 'course'=>$courseid))) {
1292             $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1293         }
1294         //use display cache for one course only - we need to keep session small
1295         $USER->display = array($courseid => $display);
1296     }
1298     return $USER->display[$courseid];
1301 /**
1302  * Show one section only or all sections.
1303  *
1304  * @param int $courseid The course id
1305  * @param mixed $display show only this section, 0 or 'all' means show all sections
1306  * @return int Course section to display, 0 means all
1307  */
1308 function course_set_display($courseid, $display) {
1309     global $USER, $DB;
1311     if ($display === 'all' or empty($display)) {
1312         $display = 0;
1313     }
1315     if (!isloggedin() or isguestuser()) {
1316         //do not store settings in db for guests
1317         return 0;
1318     }
1320     if ($display == 0) {
1321         //show all, do not store anything in database
1322         $DB->delete_records('course_display', array('userid' => $USER->id, 'course' => $courseid));
1324     } else {
1325         if ($DB->record_exists('course_display', array('userid' => $USER->id, 'course' => $courseid))) {
1326             $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id, 'course' => $courseid));
1327         } else {
1328             $record = new stdClass();
1329             $record->userid = $USER->id;
1330             $record->course = $courseid;
1331             $record->display = $display;
1332             $DB->insert_record('course_display', $record);
1333         }
1334     }
1336     //use display cache for one course only - we need to keep session small
1337     $USER->display = array($courseid => $display);
1339     return $display;
1342 /**
1343  * For a given course section, marks it visible or hidden,
1344  * and does the same for every activity in that section
1345  */
1346 function set_section_visible($courseid, $sectionnumber, $visibility) {
1347     global $DB;
1349     if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1350         $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1351         if (!empty($section->sequence)) {
1352             $modules = explode(",", $section->sequence);
1353             foreach ($modules as $moduleid) {
1354                 set_coursemodule_visible($moduleid, $visibility, true);
1355             }
1356         }
1357         rebuild_course_cache($courseid);
1358     }
1361 /**
1362  * Obtains shared data that is used in print_section when displaying a
1363  * course-module entry.
1364  *
1365  * Calls format_text or format_string as appropriate, and obtains the correct icon.
1366  *
1367  * This data is also used in other areas of the code.
1368  * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1369  * @param object $course Moodle course object
1370  * @return array An array with the following values in this order:
1371  *   $content (optional extra content for after link),
1372  *   $instancename (text of link)
1373  */
1374 function get_print_section_cm_text(cm_info $cm, $course) {
1375     global $OUTPUT;
1377     // Get content from modinfo if specified. Content displays either
1378     // in addition to the standard link (below), or replaces it if
1379     // the link is turned off by setting ->url to null.
1380     if (($content = $cm->get_content()) !== '') {
1381         // Improve filter performance by preloading filter setttings for all
1382         // activities on the course (this does nothing if called multiple
1383         // times)
1384         filter_preload_activities($cm->get_modinfo());
1386         // Get module context
1387         $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1388         $labelformatoptions = new stdClass();
1389         $labelformatoptions->noclean = true;
1390         $labelformatoptions->overflowdiv = true;
1391         $labelformatoptions->context = $modulecontext;
1392         $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1393     } else {
1394         $content = '';
1395     }
1397     // Get course context
1398     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1399     $stringoptions = new stdClass;
1400     $stringoptions->context = $coursecontext;
1401     $instancename = format_string($cm->name, true,  $stringoptions);
1402     return array($content, $instancename);
1405 /**
1406  * Prints a section full of activity modules
1407  */
1408 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1409     global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1411     static $initialised;
1413     static $groupbuttons;
1414     static $groupbuttonslink;
1415     static $isediting;
1416     static $ismoving;
1417     static $strmovehere;
1418     static $strmovefull;
1419     static $strunreadpostsone;
1420     static $groupings;
1421     static $modulenames;
1423     if (!isset($initialised)) {
1424         $groupbuttons     = ($course->groupmode or (!$course->groupmodeforce));
1425         $groupbuttonslink = (!$course->groupmodeforce);
1426         $isediting        = $PAGE->user_is_editing();
1427         $ismoving         = $isediting && ismoving($course->id);
1428         if ($ismoving) {
1429             $strmovehere  = get_string("movehere");
1430             $strmovefull  = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1431         }
1432         $modulenames      = array();
1433         $initialised = true;
1434     }
1436     $tl = textlib_get_instance();
1438     $modinfo = get_fast_modinfo($course);
1439     $completioninfo = new completion_info($course);
1441     //Accessibility: replace table with list <ul>, but don't output empty list.
1442     if (!empty($section->sequence)) {
1444         // Fix bug #5027, don't want style=\"width:$width\".
1445         echo "<ul class=\"section img-text\">\n";
1446         $sectionmods = explode(",", $section->sequence);
1448         foreach ($sectionmods as $modnumber) {
1449             if (empty($mods[$modnumber])) {
1450                 continue;
1451             }
1453             /**
1454              * @var cm_info
1455              */
1456             $mod = $mods[$modnumber];
1458             if ($ismoving and $mod->id == $USER->activitycopy) {
1459                 // do not display moving mod
1460                 continue;
1461             }
1463             if (isset($modinfo->cms[$modnumber])) {
1464                 // We can continue (because it will not be displayed at all)
1465                 // if:
1466                 // 1) The activity is not visible to users
1467                 // and
1468                 // 2a) The 'showavailability' option is not set (if that is set,
1469                 //     we need to display the activity so we can show
1470                 //     availability info)
1471                 // or
1472                 // 2b) The 'availableinfo' is empty, i.e. the activity was
1473                 //     hidden in a way that leaves no info, such as using the
1474                 //     eye icon.
1475                 if (!$modinfo->cms[$modnumber]->uservisible &&
1476                     (empty($modinfo->cms[$modnumber]->showavailability) ||
1477                       empty($modinfo->cms[$modnumber]->availableinfo))) {
1478                     // visibility shortcut
1479                     continue;
1480                 }
1481             } else {
1482                 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1483                     // module not installed
1484                     continue;
1485                 }
1486                 if (!coursemodule_visible_for_user($mod) &&
1487                     empty($mod->showavailability)) {
1488                     // full visibility check
1489                     continue;
1490                 }
1491             }
1493             if (!isset($modulenames[$mod->modname])) {
1494                 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1495             }
1496             $modulename = $modulenames[$mod->modname];
1498             // In some cases the activity is visible to user, but it is
1499             // dimmed. This is done if viewhiddenactivities is true and if:
1500             // 1. the activity is not visible, or
1501             // 2. the activity has dates set which do not include current, or
1502             // 3. the activity has any other conditions set (regardless of whether
1503             //    current user meets them)
1504             $canviewhidden = has_capability(
1505                 'moodle/course:viewhiddenactivities',
1506                 get_context_instance(CONTEXT_MODULE, $mod->id));
1507             $accessiblebutdim = false;
1508             if ($canviewhidden) {
1509                 $accessiblebutdim = !$mod->visible;
1510                 if (!empty($CFG->enableavailability)) {
1511                     $accessiblebutdim = $accessiblebutdim ||
1512                         $mod->availablefrom > time() ||
1513                         ($mod->availableuntil && $mod->availableuntil < time()) ||
1514                         count($mod->conditionsgrade) > 0 ||
1515                         count($mod->conditionscompletion) > 0;
1516                 }
1517             }
1519             $liclasses = array();
1520             $liclasses[] = 'activity';
1521             $liclasses[] = $mod->modname;
1522             $liclasses[] = 'modtype_'.$mod->modname;
1523             $extraclasses = $mod->get_extra_classes();
1524             if ($extraclasses) {
1525                 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1526             }
1527             echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1528             if ($ismoving) {
1529                 echo '<a title="'.$strmovefull.'"'.
1530                      ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1531                      '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1532                      ' alt="'.$strmovehere.'" /></a><br />
1533                      ';
1534             }
1536             $classes = array('mod-indent');
1537             if (!empty($mod->indent)) {
1538                 $classes[] = 'mod-indent-'.$mod->indent;
1539                 if ($mod->indent > 15) {
1540                     $classes[] = 'mod-indent-huge';
1541                 }
1542             }
1543             echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1545             // Get data about this course-module
1546             list($content, $instancename) =
1547                     get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1549             //Accessibility: for files get description via icon, this is very ugly hack!
1550             $altname = '';
1551             $altname = $mod->modfullname;
1552             if (!empty($customicon)) {
1553                 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1554                 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1555                     $mimetype = mimeinfo_from_icon('type', $customicon);
1556                     $altname = get_mimetype_description($mimetype);
1557                 }
1558             }
1559             // Avoid unnecessary duplication: if e.g. a forum name already
1560             // includes the word forum (or Forum, etc) then it is unhelpful
1561             // to include that in the accessible description that is added.
1562             if (false !== strpos($tl->strtolower($instancename),
1563                     $tl->strtolower($altname))) {
1564                 $altname = '';
1565             }
1566             // File type after name, for alphabetic lists (screen reader).
1567             if ($altname) {
1568                 $altname = get_accesshide(' '.$altname);
1569             }
1571             // We may be displaying this just in order to show information
1572             // about visibility, without the actual link
1573             $contentpart = '';
1574             if ($mod->uservisible) {
1575                 // Nope - in this case the link is fully working for user
1576                 $linkclasses = '';
1577                 $textclasses = '';
1578                 if ($accessiblebutdim) {
1579                     $linkclasses .= ' dimmed';
1580                     $textclasses .= ' dimmed_text';
1581                     $accesstext = '<span class="accesshide">'.
1582                         get_string('hiddenfromstudents').': </span>';
1583                 } else {
1584                     $accesstext = '';
1585                 }
1586                 if ($linkclasses) {
1587                     $linkcss = 'class="' . trim($linkclasses) . '" ';
1588                 } else {
1589                     $linkcss = '';
1590                 }
1591                 if ($textclasses) {
1592                     $textcss = 'class="' . trim($textclasses) . '" ';
1593                 } else {
1594                     $textcss = '';
1595                 }
1597                 // Get on-click attribute value if specified
1598                 $onclick = $mod->get_on_click();
1599                 if ($onclick) {
1600                     $onclick = ' onclick="' . $onclick . '"';
1601                 }
1603                 if ($url = $mod->get_url()) {
1604                     // Display link itself
1605                     echo '<a ' . $linkcss . $mod->extra . $onclick .
1606                             ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1607                             '" class="activityicon" alt="' .
1608                             $modulename . '" /> ' .
1609                             $accesstext . '<span class="instancename">' .
1610                             $instancename . $altname . '</span></a>';
1612                     // If specified, display extra content after link
1613                     if ($content) {
1614                         $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1615                                 '">' . $content . '</div>';
1616                     }
1617                 } else {
1618                     // No link, so display only content
1619                     $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1620                             $accesstext . $content . '</div>';
1621                 }
1623                 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1624                     if (!isset($groupings)) {
1625                         $groupings = groups_get_all_groupings($course->id);
1626                     }
1627                     echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1628                 }
1629             } else {
1630                 $textclasses = $extraclasses;
1631                 $textclasses .= ' dimmed_text';
1632                 if ($textclasses) {
1633                     $textcss = 'class="' . trim($textclasses) . '" ';
1634                 } else {
1635                     $textcss = '';
1636                 }
1637                 $accesstext = '<span class="accesshide">' .
1638                         get_string('notavailableyet', 'condition') .
1639                         ': </span>';
1641                 if ($url = $mod->get_url()) {
1642                     // Display greyed-out text of link
1643                     echo '<div ' . $textcss . $mod->extra .
1644                             ' >' . '<img src="' . $mod->get_icon_url() .
1645                             '" class="activityicon" alt="' .
1646                             $modulename .
1647                             '" /> <span>'. $instancename . $altname .
1648                             '</span></div>';
1650                     // Do not display content after link when it is greyed out like this.
1651                 } else {
1652                     // No link, so display only content (also greyed)
1653                     $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1654                             $accesstext . $content . '</div>';
1655                 }
1656             }
1658             // Module can put text after the link (e.g. forum unread)
1659             echo $mod->get_after_link();
1661             // If there is content but NO link (eg label), then display the
1662             // content here (BEFORE any icons). In this case cons must be
1663             // displayed after the content so that it makes more sense visually
1664             // and for accessibility reasons, e.g. if you have a one-line label
1665             // it should work similarly (at least in terms of ordering) to an
1666             // activity.
1667             if (empty($url)) {
1668                 echo $contentpart;
1669             }
1671             if ($isediting) {
1672                 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1673                     if (! $mod->groupmodelink = $groupbuttonslink) {
1674                         $mod->groupmode = $course->groupmode;
1675                     }
1677                 } else {
1678                     $mod->groupmode = false;
1679                 }
1680                 echo '&nbsp;&nbsp;';
1681                 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1682                 echo $mod->get_after_edit_icons();
1683             }
1685             // Completion
1686             $completion = $hidecompletion
1687                 ? COMPLETION_TRACKING_NONE
1688                 : $completioninfo->is_enabled($mod);
1689             if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1690                 !isguestuser() && $mod->uservisible) {
1691                 $completiondata = $completioninfo->get_data($mod,true);
1692                 $completionicon = '';
1693                 if ($isediting) {
1694                     switch ($completion) {
1695                         case COMPLETION_TRACKING_MANUAL :
1696                             $completionicon = 'manual-enabled'; break;
1697                         case COMPLETION_TRACKING_AUTOMATIC :
1698                             $completionicon = 'auto-enabled'; break;
1699                         default: // wtf
1700                     }
1701                 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1702                     switch($completiondata->completionstate) {
1703                         case COMPLETION_INCOMPLETE:
1704                             $completionicon = 'manual-n'; break;
1705                         case COMPLETION_COMPLETE:
1706                             $completionicon = 'manual-y'; break;
1707                     }
1708                 } else { // Automatic
1709                     switch($completiondata->completionstate) {
1710                         case COMPLETION_INCOMPLETE:
1711                             $completionicon = 'auto-n'; break;
1712                         case COMPLETION_COMPLETE:
1713                             $completionicon = 'auto-y'; break;
1714                         case COMPLETION_COMPLETE_PASS:
1715                             $completionicon = 'auto-pass'; break;
1716                         case COMPLETION_COMPLETE_FAIL:
1717                             $completionicon = 'auto-fail'; break;
1718                     }
1719                 }
1720                 if ($completionicon) {
1721                     $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1722                     $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1723                     if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1724                         $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1725                         $newstate =
1726                             $completiondata->completionstate==COMPLETION_COMPLETE
1727                             ? COMPLETION_INCOMPLETE
1728                             : COMPLETION_COMPLETE;
1729                         // In manual mode the icon is a toggle form...
1731                         // If this completion state is used by the
1732                         // conditional activities system, we need to turn
1733                         // off the JS.
1734                         if (!empty($CFG->enableavailability) &&
1735                             condition_info::completion_value_used_as_condition($course, $mod)) {
1736                             $extraclass = ' preventjs';
1737                         } else {
1738                             $extraclass = '';
1739                         }
1740                         echo "
1741 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1742 <input type='hidden' name='id' value='{$mod->id}' />
1743 <input type='hidden' name='sesskey' value='".sesskey()."' />
1744 <input type='hidden' name='completionstate' value='$newstate' />
1745 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1746 </div></form>";
1747                     } else {
1748                         // In auto mode, or when editing, the icon is just an image
1749                         echo "<span class='autocompletion'>";
1750                         echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1751                     }
1752                 }
1753             }
1755             // If there is content AND a link, then display the content here
1756             // (AFTER any icons). Otherwise it was displayed before
1757             if (!empty($url)) {
1758                 echo $contentpart;
1759             }
1761             // Show availability information (for someone who isn't allowed to
1762             // see the activity itself, or for staff)
1763             if (!$mod->uservisible) {
1764                 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1765             } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1766                 $ci = new condition_info($mod);
1767                 $fullinfo = $ci->get_full_information();
1768                 if($fullinfo) {
1769                     echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1770                         ? 'userrestriction_visible'
1771                         : 'userrestriction_hidden','condition',
1772                         $fullinfo).'</div>';
1773                 }
1774             }
1776             echo html_writer::end_tag('div');
1777             echo html_writer::end_tag('li')."\n";
1778         }
1780     } elseif ($ismoving) {
1781         echo "<ul class=\"section\">\n";
1782     }
1784     if ($ismoving) {
1785         echo '<li><a title="'.$strmovefull.'"'.
1786              ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1787              '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1788              ' alt="'.$strmovehere.'" /></a></li>
1789              ';
1790     }
1791     if (!empty($section->sequence) || $ismoving) {
1792         echo "</ul><!--class='section'-->\n\n";
1793     }
1796 /**
1797  * Prints the menus to add activities and resources.
1798  */
1799 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1800     global $CFG, $OUTPUT;
1802     // check to see if user can add menus
1803     if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1804         return false;
1805     }
1807     $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1809     $resources = array();
1810     $activities = array();
1812     foreach($modnames as $modname=>$modnamestr) {
1813         if (!course_allowed_module($course, $modname)) {
1814             continue;
1815         }
1817         $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1818         if (!file_exists($libfile)) {
1819             continue;
1820         }
1821         include_once($libfile);
1822         $gettypesfunc =  $modname.'_get_types';
1823         if (function_exists($gettypesfunc)) {
1824             // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1825             if ($types = $gettypesfunc()) {
1826                 $menu = array();
1827                 $atype = null;
1828                 $groupname = null;
1829                 foreach($types as $type) {
1830                     if ($type->typestr === '--') {
1831                         continue;
1832                     }
1833                     if (strpos($type->typestr, '--') === 0) {
1834                         $groupname = str_replace('--', '', $type->typestr);
1835                         continue;
1836                     }
1837                     $type->type = str_replace('&amp;', '&', $type->type);
1838                     if ($type->modclass == MOD_CLASS_RESOURCE) {
1839                         $atype = MOD_CLASS_RESOURCE;
1840                     }
1841                     $menu[$urlbase.$type->type] = $type->typestr;
1842                 }
1843                 if (!is_null($groupname)) {
1844                     if ($atype == MOD_CLASS_RESOURCE) {
1845                         $resources[] = array($groupname=>$menu);
1846                     } else {
1847                         $activities[] = array($groupname=>$menu);
1848                     }
1849                 } else {
1850                     if ($atype == MOD_CLASS_RESOURCE) {
1851                         $resources = array_merge($resources, $menu);
1852                     } else {
1853                         $activities = array_merge($activities, $menu);
1854                     }
1855                 }
1856             }
1857         } else {
1858             $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1859             if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1860                 $resources[$urlbase.$modname] = $modnamestr;
1861             } else if ($archetype === MOD_ARCHETYPE_SYSTEM) {
1862                 // System modules cannot be added by user, do not add to dropdown
1863             } else {
1864                 // all other archetypes are considered activity
1865                 $activities[$urlbase.$modname] = $modnamestr;
1866             }
1867         }
1868     }
1870     $straddactivity = get_string('addactivity');
1871     $straddresource = get_string('addresource');
1873     $output  = '<div class="section_add_menus">';
1875     if (!$vertical) {
1876         $output .= '<div class="horizontal">';
1877     }
1879     if (!empty($resources)) {
1880         $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1881         $select->set_help_icon('resources');
1882         $output .= $OUTPUT->render($select);
1883     }
1885     if (!empty($activities)) {
1886         $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1887         $select->set_help_icon('activities');
1888         $output .= $OUTPUT->render($select);
1889     }
1891     if (!$vertical) {
1892         $output .= '</div>';
1893     }
1895     $output .= '</div>';
1897     if ($return) {
1898         return $output;
1899     } else {
1900         echo $output;
1901     }
1904 /**
1905  * Return the course category context for the category with id $categoryid, except
1906  * that if $categoryid is 0, return the system context.
1907  *
1908  * @param integer $categoryid a category id or 0.
1909  * @return object the corresponding context
1910  */
1911 function get_category_or_system_context($categoryid) {
1912     if ($categoryid) {
1913         return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1914     } else {
1915         return get_context_instance(CONTEXT_SYSTEM);
1916     }
1919 /**
1920  * Gets the child categories of a given courses category. Uses a static cache
1921  * to make repeat calls efficient.
1922  *
1923  * @param int $parentid the id of a course category.
1924  * @return array all the child course categories.
1925  */
1926 function get_child_categories($parentid) {
1927     static $allcategories = null;
1929     // only fill in this variable the first time
1930     if (null == $allcategories) {
1931         $allcategories = array();
1933         $categories = get_categories();
1934         foreach ($categories as $category) {
1935             if (empty($allcategories[$category->parent])) {
1936                 $allcategories[$category->parent] = array();
1937             }
1938             $allcategories[$category->parent][] = $category;
1939         }
1940     }
1942     if (empty($allcategories[$parentid])) {
1943         return array();
1944     } else {
1945         return $allcategories[$parentid];
1946     }
1949 /**
1950  * This function recursively travels the categories, building up a nice list
1951  * for display. It also makes an array that list all the parents for each
1952  * category.
1953  *
1954  * For example, if you have a tree of categories like:
1955  *   Miscellaneous (id = 1)
1956  *      Subcategory (id = 2)
1957  *         Sub-subcategory (id = 4)
1958  *   Other category (id = 3)
1959  * Then after calling this function you will have
1960  * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1961  *      4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1962  *      3 => 'Other category');
1963  * $parents = array(2 => array(1), 4 => array(1, 2));
1964  *
1965  * If you specify $requiredcapability, then only categories where the current
1966  * user has that capability will be added to $list, although all categories
1967  * will still be added to $parents, and if you only have $requiredcapability
1968  * in a child category, not the parent, then the child catgegory will still be
1969  * included.
1970  *
1971  * If you specify the option $excluded, then that category, and all its children,
1972  * are omitted from the tree. This is useful when you are doing something like
1973  * moving categories, where you do not want to allow people to move a category
1974  * to be the child of itself.
1975  *
1976  * @param array $list For output, accumulates an array categoryid => full category path name
1977  * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1978  * @param string/array $requiredcapability if given, only categories where the current
1979  *      user has this capability will be added to $list. Can also be an array of capabilities,
1980  *      in which case they are all required.
1981  * @param integer $excludeid Omit this category and its children from the lists built.
1982  * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1983  * @param string $path For internal use, as part of recursive calls.
1984  */
1985 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1986         $excludeid = 0, $category = NULL, $path = "") {
1988     // initialize the arrays if needed
1989     if (!is_array($list)) {
1990         $list = array();
1991     }
1992     if (!is_array($parents)) {
1993         $parents = array();
1994     }
1996     if (empty($category)) {
1997         // Start at the top level.
1998         $category = new stdClass;
1999         $category->id = 0;
2000     } else {
2001         // This is the excluded category, don't include it.
2002         if ($excludeid > 0 && $excludeid == $category->id) {
2003             return;
2004         }
2006         $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2007         $categoryname = format_string($category->name, true, array('context' => $context));
2009         // Update $path.
2010         if ($path) {
2011             $path = $path.' / '.$categoryname;
2012         } else {
2013             $path = $categoryname;
2014         }
2016         // Add this category to $list, if the permissions check out.
2017         if (empty($requiredcapability)) {
2018             $list[$category->id] = $path;
2020         } else {
2021             $requiredcapability = (array)$requiredcapability;
2022             if (has_all_capabilities($requiredcapability, $context)) {
2023                 $list[$category->id] = $path;
2024             }
2025         }
2026     }
2028     // Add all the children recursively, while updating the parents array.
2029     if ($categories = get_child_categories($category->id)) {
2030         foreach ($categories as $cat) {
2031             if (!empty($category->id)) {
2032                 if (isset($parents[$category->id])) {
2033                     $parents[$cat->id]   = $parents[$category->id];
2034                 }
2035                 $parents[$cat->id][] = $category->id;
2036             }
2037             make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2038         }
2039     }
2042 /**
2043  * This function generates a structured array of courses and categories.
2044  *
2045  * The depth of categories is limited by $CFG->maxcategorydepth however there
2046  * is no limit on the number of courses!
2047  *
2048  * Suitable for use with the course renderers course_category_tree method:
2049  * $renderer = $PAGE->get_renderer('core','course');
2050  * echo $renderer->course_category_tree(get_course_category_tree());
2051  *
2052  * @global moodle_database $DB
2053  * @param int $id
2054  * @param int $depth
2055  */
2056 function get_course_category_tree($id = 0, $depth = 0) {
2057     global $DB, $CFG;
2058     $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2059     $categories = get_child_categories($id);
2060     $categoryids = array();
2061     foreach ($categories as $key => &$category) {
2062         if (!$category->visible && !$viewhiddencats) {
2063             unset($categories[$key]);
2064             continue;
2065         }
2066         $categoryids[$category->id] = $category;
2067         if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2068             list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2069             foreach ($subcategories as $subid=>$subcat) {
2070                 $categoryids[$subid] = $subcat;
2071             }
2072             $category->courses = array();
2073         }
2074     }
2076     if ($depth > 0) {
2077         // This is a recursive call so return the required array
2078         return array($categories, $categoryids);
2079     }
2081     // The depth is 0 this function has just been called so we can finish it off
2083     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2084     list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2085     $sql = "SELECT
2086             c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2087             $ccselect
2088             FROM {course} c
2089             $ccjoin
2090             WHERE c.category $catsql ORDER BY c.sortorder ASC";
2091     if ($courses = $DB->get_records_sql($sql, $catparams)) {
2092         // loop throught them
2093         foreach ($courses as $course) {
2094             if ($course->id == SITEID) {
2095                 continue;
2096             }
2097             context_instance_preload($course);
2098             if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2099                 $categoryids[$course->category]->courses[$course->id] = $course;
2100             }
2101         }
2102     }
2103     return $categories;
2106 /**
2107  * Recursive function to print out all the categories in a nice format
2108  * with or without courses included
2109  */
2110 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2111     global $CFG;
2113     // maxcategorydepth == 0 meant no limit
2114     if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2115         return;
2116     }
2118     if (!$displaylist) {
2119         make_categories_list($displaylist, $parentslist);
2120     }
2122     if ($category) {
2123         if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2124             print_category_info($category, $depth, $showcourses);
2125         } else {
2126             return;  // Don't bother printing children of invisible categories
2127         }
2129     } else {
2130         $category->id = "0";
2131     }
2133     if ($categories = get_child_categories($category->id)) {   // Print all the children recursively
2134         $countcats = count($categories);
2135         $count = 0;
2136         $first = true;
2137         $last = false;
2138         foreach ($categories as $cat) {
2139             $count++;
2140             if ($count == $countcats) {
2141                 $last = true;
2142             }
2143             $up = $first ? false : true;
2144             $down = $last ? false : true;
2145             $first = false;
2147             print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2148         }
2149     }
2152 /**
2153  * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2154  */
2155 function make_categories_options() {
2156     make_categories_list($cats,$parents);
2157     foreach ($cats as $key => $value) {
2158         if (array_key_exists($key,$parents)) {
2159             if ($indent = count($parents[$key])) {
2160                 for ($i = 0; $i < $indent; $i++) {
2161                     $cats[$key] = '&nbsp;'.$cats[$key];
2162                 }
2163             }
2164         }
2165     }
2166     return $cats;
2169 /**
2170  * Gets the name of a course to be displayed when showing a list of courses.
2171  * By default this is just $course->fullname but user can configure it. The
2172  * result of this function should be passed through print_string.
2173  * @param object $course Moodle course object
2174  * @return string Display name of course (either fullname or short + fullname)
2175  */
2176 function get_course_display_name_for_list($course) {
2177     global $CFG;
2178     if (!empty($CFG->courselistshortnames)) {
2179         return $course->shortname . ' ' .$course->fullname;
2180     } else {
2181         return $course->fullname;
2182     }
2185 /**
2186  * Prints the category info in indented fashion
2187  * This function is only used by print_whole_category_list() above
2188  */
2189 function print_category_info($category, $depth=0, $showcourses = false) {
2190     global $CFG, $DB, $OUTPUT;
2192     $strsummary = get_string('summary');
2194     $catlinkcss = null;
2195     if (!$category->visible) {
2196         $catlinkcss = array('class'=>'dimmed');
2197     }
2198     static $coursecount = null;
2199     if (null === $coursecount) {
2200         // only need to check this once
2201         $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2202     }
2204     if ($showcourses and $coursecount) {
2205         $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2206     } else {
2207         $catimage = "&nbsp;";
2208     }
2210     $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2211     $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2212     $fullname = format_string($category->name, true, array('context' => $context));
2214     if ($showcourses and $coursecount) {
2215         echo '<div class="categorylist clearfix">';
2216         $cat = '';
2217         $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2218         $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2219         $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2221         $html = '';
2222         if ($depth > 0) {
2223             for ($i=0; $i< $depth; $i++) {
2224                 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2225                 $cat = '';
2226             }
2227         } else {
2228             $html = $cat;
2229         }
2230         echo html_writer::tag('div', $html, array('class'=>'category'));
2231         echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2233         // does the depth exceed maxcategorydepth
2234         // maxcategorydepth == 0 or unset meant no limit
2235         $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2236         if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2237             foreach ($courses as $course) {
2238                 $linkcss = null;
2239                 if (!$course->visible) {
2240                     $linkcss = array('class'=>'dimmed');
2241                 }
2243                 $coursename = get_course_display_name_for_list($course);
2244                 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2246                 // print enrol info
2247                 $courseicon = '';
2248                 if ($icons = enrol_get_course_info_icons($course)) {
2249                     foreach ($icons as $pix_icon) {
2250                         $courseicon = $OUTPUT->render($pix_icon).' ';
2251                     }
2252                 }
2254                 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2256                 if ($course->summary) {
2257                     $link = new moodle_url('/course/info.php?id='.$course->id);
2258                     $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2259                         new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2260                         array('title'=>$strsummary));
2262                     $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2263                 }
2265                 $html = '';
2266                 for ($i=0; $i <= $depth; $i++) {
2267                     $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2268                     $coursecontent = '';
2269                 }
2270                 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2271             }
2272         }
2273         echo '</div>';
2274     } else {
2275         echo '<div class="categorylist">';
2276         $html = '';
2277         $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2278         if (count($courses) > 0) {
2279             $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2280         }
2282         if ($depth > 0) {
2283             for ($i=0; $i< $depth; $i++) {
2284                 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2285                 $cat = '';
2286             }
2287         } else {
2288             $html = $cat;
2289         }
2291         echo html_writer::tag('div', $html, array('class'=>'category'));
2292         echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2293         echo '</div>';
2294     }
2297 /**
2298  * Print the buttons relating to course requests.
2299  *
2300  * @param object $systemcontext the system context.
2301  */
2302 function print_course_request_buttons($systemcontext) {
2303     global $CFG, $DB, $OUTPUT;
2304     if (empty($CFG->enablecourserequests)) {
2305         return;
2306     }
2307     if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2308     /// Print a button to request a new course
2309         echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2310     }
2311     /// Print a button to manage pending requests
2312     if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2313         $disabled = !$DB->record_exists('course_request', array());
2314         echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2315     }
2318 /**
2319  * Does the user have permission to edit things in this category?
2320  *
2321  * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2322  * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2323  */
2324 function can_edit_in_category($categoryid = 0) {
2325     $context = get_category_or_system_context($categoryid);
2326     return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2329 /**
2330  * Prints the turn editing on/off button on course/index.php or course/category.php.
2331  *
2332  * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2333  * @return string HTML of the editing button, or empty string, if this user is not allowed
2334  *      to see it.
2335  */
2336 function update_category_button($categoryid = 0) {
2337     global $CFG, $PAGE, $OUTPUT;
2339     // Check permissions.
2340     if (!can_edit_in_category($categoryid)) {
2341         return '';
2342     }
2344     // Work out the appropriate action.
2345     if ($PAGE->user_is_editing()) {
2346         $label = get_string('turneditingoff');
2347         $edit = 'off';
2348     } else {
2349         $label = get_string('turneditingon');
2350         $edit = 'on';
2351     }
2353     // Generate the button HTML.
2354     $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2355     if ($categoryid) {
2356         $options['id'] = $categoryid;
2357         $page = 'category.php';
2358     } else {
2359         $page = 'index.php';
2360     }
2361     return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2364 /**
2365  * Category is 0 (for all courses) or an object
2366  */
2367 function print_courses($category) {
2368     global $CFG, $OUTPUT;
2370     if (!is_object($category) && $category==0) {
2371         $categories = get_child_categories(0);  // Parent = 0   ie top-level categories only
2372         if (is_array($categories) && count($categories) == 1) {
2373             $category   = array_shift($categories);
2374             $courses    = get_courses_wmanagers($category->id,
2375                                                 'c.sortorder ASC',
2376                                                 array('summary','summaryformat'));
2377         } else {
2378             $courses    = get_courses_wmanagers('all',
2379                                                 'c.sortorder ASC',
2380                                                 array('summary','summaryformat'));
2381         }
2382         unset($categories);
2383     } else {
2384         $courses    = get_courses_wmanagers($category->id,
2385                                             'c.sortorder ASC',
2386                                             array('summary','summaryformat'));
2387     }
2389     if ($courses) {
2390         echo html_writer::start_tag('ul', array('class'=>'unlist'));
2391         foreach ($courses as $course) {
2392             $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2393             if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2394                 echo html_writer::start_tag('li');
2395                 print_course($course);
2396                 echo html_writer::end_tag('li');
2397             }
2398         }
2399         echo html_writer::end_tag('ul');
2400     } else {
2401         echo $OUTPUT->heading(get_string("nocoursesyet"));
2402         $context = get_context_instance(CONTEXT_SYSTEM);
2403         if (has_capability('moodle/course:create', $context)) {
2404             $options = array();
2405             if (!empty($category->id)) {
2406                 $options['category'] = $category->id;
2407             } else {
2408                 $options['category'] = $CFG->defaultrequestcategory;
2409             }
2410             echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2411             echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2412             echo html_writer::end_tag('div');
2413         }
2414     }
2417 /**
2418  * Print a description of a course, suitable for browsing in a list.
2419  *
2420  * @param object $course the course object.
2421  * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2422  */
2423 function print_course($course, $highlightterms = '') {
2424     global $CFG, $USER, $DB, $OUTPUT;
2426     $context = get_context_instance(CONTEXT_COURSE, $course->id);
2428     // Rewrite file URLs so that they are correct
2429     $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2431     echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2432     echo html_writer::start_tag('div', array('class'=>'info'));
2433     echo html_writer::start_tag('h3', array('class'=>'name'));
2435     $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2437     $coursename = get_course_display_name_for_list($course);
2438     $linktext = highlight($highlightterms, format_string($coursename));
2439     $linkparams = array('title'=>get_string('entercourse'));
2440     if (empty($course->visible)) {
2441         $linkparams['class'] = 'dimmed';
2442     }
2443     echo html_writer::link($linkhref, $linktext, $linkparams);
2444     echo html_writer::end_tag('h3');
2446     /// first find all roles that are supposed to be displayed
2447     if (!empty($CFG->coursecontact)) {
2448         $managerroles = explode(',', $CFG->coursecontact);
2449         $namesarray = array();
2450         $rusers = array();
2452         if (!isset($course->managers)) {
2453             $rusers = get_role_users($managerroles, $context, true,
2454                 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2455                  r.name AS rolename, r.sortorder, r.id AS roleid',
2456                 'r.sortorder ASC, u.lastname ASC');
2457         } else {
2458             //  use the managers array if we have it for perf reasosn
2459             //  populate the datastructure like output of get_role_users();
2460             foreach ($course->managers as $manager) {
2461                 $u = new stdClass();
2462                 $u = $manager->user;
2463                 $u->roleid = $manager->roleid;
2464                 $u->rolename = $manager->rolename;
2466                 $rusers[] = $u;
2467             }
2468         }
2470         /// Rename some of the role names if needed
2471         if (isset($context)) {
2472             $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2473         }
2475         $namesarray = array();
2476         $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2477         foreach ($rusers as $ra) {
2478             if (isset($namesarray[$ra->id])) {
2479                 //  only display a user once with the higest sortorder role
2480                 continue;
2481             }
2483             if (isset($aliasnames[$ra->roleid])) {
2484                 $ra->rolename = $aliasnames[$ra->roleid]->name;
2485             }
2487             $fullname = fullname($ra, $canviewfullnames);
2488             $namesarray[$ra->id] = format_string($ra->rolename).': '.
2489                 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2490         }
2492         if (!empty($namesarray)) {
2493             echo html_writer::start_tag('ul', array('class'=>'teachers'));
2494             foreach ($namesarray as $name) {
2495                 echo html_writer::tag('li', $name);
2496             }
2497             echo html_writer::end_tag('ul');
2498         }
2499     }
2500     echo html_writer::end_tag('div'); // End of info div
2502     echo html_writer::start_tag('div', array('class'=>'summary'));
2503     $options = NULL;
2504     $options->noclean = true;
2505     $options->para = false;
2506     $options->overflowdiv = true;
2507     if (!isset($course->summaryformat)) {
2508         $course->summaryformat = FORMAT_MOODLE;
2509     }
2510     echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options,  $course->id));
2511     if ($icons = enrol_get_course_info_icons($course)) {
2512         echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2513         foreach ($icons as $icon) {
2514             echo $OUTPUT->render($icon);
2515         }
2516         echo html_writer::end_tag('div'); // End of enrolmenticons div
2517     }
2518     echo html_writer::end_tag('div'); // End of summary div
2519     echo html_writer::end_tag('div'); // End of coursebox div
2522 /**
2523  * Prints custom user information on the home page.
2524  * Over time this can include all sorts of information
2525  */
2526 function print_my_moodle() {
2527     global $USER, $CFG, $DB, $OUTPUT;
2529     if (!isloggedin() or isguestuser()) {
2530         print_error('nopermissions', '', '', 'See My Moodle');
2531     }
2533     $courses  = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2534     $rhosts   = array();
2535     $rcourses = array();
2536     if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2537         $rcourses = get_my_remotecourses($USER->id);
2538         $rhosts   = get_my_remotehosts();
2539     }
2541     if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2543         if (!empty($courses)) {
2544             echo '<ul class="unlist">';
2545             foreach ($courses as $course) {
2546                 if ($course->id == SITEID) {
2547                     continue;
2548                 }
2549                 echo '<li>';
2550                 print_course($course);
2551                 echo "</li>\n";
2552             }
2553             echo "</ul>\n";
2554         }
2556         // MNET
2557         if (!empty($rcourses)) {
2558             // at the IDP, we know of all the remote courses
2559             foreach ($rcourses as $course) {
2560                 print_remote_course($course, "100%");
2561             }
2562         } elseif (!empty($rhosts)) {
2563             // non-IDP, we know of all the remote servers, but not courses
2564             foreach ($rhosts as $host) {
2565                 print_remote_host($host, "100%");
2566             }
2567         }
2568         unset($course);
2569         unset($host);
2571         if ($DB->count_records("course") > (count($courses) + 1) ) {  // Some courses not being displayed
2572             echo "<table width=\"100%\"><tr><td align=\"center\">";
2573             print_course_search("", false, "short");
2574             echo "</td><td align=\"center\">";
2575             echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2576             echo "</td></tr></table>\n";
2577         }
2579     } else {
2580         if ($DB->count_records("course_categories") > 1) {
2581             echo $OUTPUT->box_start("categorybox");
2582             print_whole_category_list();
2583             echo $OUTPUT->box_end();
2584         } else {
2585             print_courses(0);
2586         }
2587     }
2591 function print_course_search($value="", $return=false, $format="plain") {
2592     global $CFG;
2593     static $count = 0;
2595     $count++;
2597     $id = 'coursesearch';
2599     if ($count > 1) {
2600         $id .= $count;
2601     }
2603     $strsearchcourses= get_string("searchcourses");
2605     if ($format == 'plain') {
2606         $output  = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2607         $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2608         $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2609         $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2610         $output .= '<input type="submit" value="'.get_string('go').'" />';
2611         $output .= '</fieldset></form>';
2612     } else if ($format == 'short') {
2613         $output  = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2614         $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2615         $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2616         $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2617         $output .= '<input type="submit" value="'.get_string('go').'" />';
2618         $output .= '</fieldset></form>';
2619     } else if ($format == 'navbar') {
2620         $output  = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2621         $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2622         $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2623         $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2624         $output .= '<input type="submit" value="'.get_string('go').'" />';
2625         $output .= '</fieldset></form>';
2626     }
2628     if ($return) {
2629         return $output;
2630     }
2631     echo $output;
2634 function print_remote_course($course, $width="100%") {
2635     global $CFG, $USER;
2637     $linkcss = '';
2639     $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2641     echo '<div class="coursebox remotecoursebox clearfix">';
2642     echo '<div class="info">';
2643     echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2644          $linkcss.' href="'.$url.'">'
2645         .  format_string($course->fullname) .'</a><br />'
2646         . format_string($course->hostname) . ' : '
2647         . format_string($course->cat_name) . ' : '
2648         . format_string($course->shortname). '</div>';
2649     echo '</div><div class="summary">';
2650     $options = NULL;
2651     $options->noclean = true;
2652     $options->para = false;
2653     $options->overflowdiv = true;
2654     echo format_text($course->summary, $course->summaryformat, $options);
2655     echo '</div>';
2656     echo '</div>';
2659 function print_remote_host($host, $width="100%") {
2660     global $OUTPUT;
2662     $linkcss = '';
2664     echo '<div class="coursebox clearfix">';
2665     echo '<div class="info">';
2666     echo '<div class="name">';
2667     echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2668     echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2669         . s($host['name']).'</a> - ';
2670     echo $host['count'] . ' ' . get_string('courses');
2671     echo '</div>';
2672     echo '</div>';
2673     echo '</div>';
2677 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2679 function add_course_module($mod) {
2680     global $DB;
2682     $mod->added = time();
2683     unset($mod->id);
2685     return $DB->insert_record("course_modules", $mod);
2688 /**
2689  * Returns course section - creates new if does not exist yet.
2690  * @param int $relative section number
2691  * @param int $courseid
2692  * @return object $course_section object
2693  */
2694 function get_course_section($section, $courseid) {
2695     global $DB;
2697     if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2698         return $cw;
2699     }
2700     $cw = new stdClass();
2701     $cw->course   = $courseid;
2702     $cw->section  = $section;
2703     $cw->summary  = "";
2704     $cw->summaryformat = FORMAT_HTML;
2705     $cw->sequence = "";
2706     $id = $DB->insert_record("course_sections", $cw);
2707     return $DB->get_record("course_sections", array("id"=>$id));
2709 /**
2710  * Given a full mod object with section and course already defined, adds this module to that section.
2711  *
2712  * @param object $mod
2713  * @param int $beforemod An existing ID which we will insert the new module before
2714  * @return int The course_sections ID where the mod is inserted
2715  */
2716 function add_mod_to_section($mod, $beforemod=NULL) {
2717     global $DB;
2719     if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2721         $section->sequence = trim($section->sequence);
2723         if (empty($section->sequence)) {
2724             $newsequence = "$mod->coursemodule";
2726         } else if ($beforemod) {
2727             $modarray = explode(",", $section->sequence);
2729             if ($key = array_keys($modarray, $beforemod->id)) {
2730                 $insertarray = array($mod->id, $beforemod->id);
2731                 array_splice($modarray, $key[0], 1, $insertarray);
2732                 $newsequence = implode(",", $modarray);
2734             } else {  // Just tack it on the end anyway
2735                 $newsequence = "$section->sequence,$mod->coursemodule";
2736             }
2738         } else {
2739             $newsequence = "$section->sequence,$mod->coursemodule";
2740         }
2742         $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2743         return $section->id;     // Return course_sections ID that was used.
2745     } else {  // Insert a new record
2746         $section->course   = $mod->course;
2747         $section->section  = $mod->section;
2748         $section->summary  = "";
2749         $section->summaryformat = FORMAT_HTML;
2750         $section->sequence = $mod->coursemodule;
2751         return $DB->insert_record("course_sections", $section);
2752     }
2755 function set_coursemodule_groupmode($id, $groupmode) {
2756     global $DB;
2757     return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2760 function set_coursemodule_idnumber($id, $idnumber) {
2761     global $DB;
2762     return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2765 /**
2766 * $prevstateoverrides = true will set the visibility of the course module
2767 * to what is defined in visibleold. This enables us to remember the current
2768 * visibility when making a whole section hidden, so that when we toggle
2769 * that section back to visible, we are able to return the visibility of
2770 * the course module back to what it was originally.
2771 */
2772 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2773     global $DB, $CFG;
2774     require_once($CFG->libdir.'/gradelib.php');
2776     if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2777         return false;
2778     }
2779     if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2780         return false;
2781     }
2782     if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2783         foreach($events as $event) {
2784             if ($visible) {
2785                 show_event($event);
2786             } else {
2787                 hide_event($event);
2788             }
2789         }
2790     }
2792     // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2793     $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2794     if ($grade_items) {
2795         foreach ($grade_items as $grade_item) {
2796             $grade_item->set_hidden(!$visible);
2797         }
2798     }
2800     if ($prevstateoverrides) {
2801         if ($visible == '0') {
2802             // Remember the current visible state so we can toggle this back.
2803             $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2804         } else {
2805             // Get the previous saved visible states.
2806             return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2807         }
2808     }
2809     return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2812 /**
2813  * Delete a course module and any associated data at the course level (events)
2814  * Until 1.5 this function simply marked a deleted flag ... now it
2815  * deletes it completely.
2816  *
2817  */
2818 function delete_course_module($id) {
2819     global $CFG, $DB;
2820     require_once($CFG->libdir.'/gradelib.php');
2821     require_once($CFG->dirroot.'/blog/lib.php');
2823     if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2824         return true;
2825     }
2826     $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2827     //delete events from calendar
2828     if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2829         foreach($events as $event) {
2830             delete_event($event->id);
2831         }
2832     }
2833     //delete grade items, outcome items and grades attached to modules
2834     if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2835                                                    'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2836         foreach ($grade_items as $grade_item) {
2837             $grade_item->delete('moddelete');
2838         }
2839     }
2840     // Delete completion and availability data; it is better to do this even if the
2841     // features are not turned on, in case they were turned on previously (these will be
2842     // very quick on an empty table)
2843     $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2844     $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2846     delete_context(CONTEXT_MODULE, $cm->id);
2847     return $DB->delete_records('course_modules', array('id'=>$cm->id));
2850 function delete_mod_from_section($mod, $section) {
2851     global $DB;
2853     if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2855         $modarray = explode(",", $section->sequence);
2857         if ($key = array_keys ($modarray, $mod)) {
2858             array_splice($modarray, $key[0], 1);
2859             $newsequence = implode(",", $modarray);
2860             return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2861         } else {
2862             return false;
2863         }
2865     }
2866     return false;
2869 /**
2870  * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2871  *
2872  * @param object $course
2873  * @param int $section
2874  * @param int $move (-1 or 1)
2875  */
2876 function move_section($course, $section, $move) {
2877 /// Moves a whole course section up and down within the course
2878     global $USER, $DB;
2880     if (!$move) {
2881         return true;
2882     }
2884     $sectiondest = $section + $move;
2886     if ($sectiondest > $course->numsections or $sectiondest < 1) {
2887         return false;
2888     }
2890     if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2891         return false;
2892     }
2894     if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2895         return false;
2896     }
2898     $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2899     $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2901     // if the focus is on the section that is being moved, then move the focus along
2902     if (course_get_display($course->id) == $section) {
2903         course_set_display($course->id, $sectiondest);
2904     }
2906     // Check for duplicates and fix order if needed.
2907     // There is a very rare case that some sections in the same course have the same section id.
2908     $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2909     $n = 0;
2910     foreach ($sections as $section) {
2911         if ($section->section != $n) {
2912             $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2913         }
2914         $n++;
2915     }
2916     return true;
2919 /**
2920  * Moves a section within a course, from a position to another.
2921  * Be very careful: $section and $destination refer to section number,
2922  * not id!.
2923  *
2924  * @param object $course
2925  * @param int $section Section number (not id!!!)
2926  * @param int $destination
2927  * @return boolean Result
2928  */
2929 function move_section_to($course, $section, $destination) {
2930 /// Moves a whole course section up and down within the course
2931     global $USER, $DB;
2933     if (!$destination && $destination != 0) {
2934         return true;
2935     }
2937     if ($destination > $course->numsections) {
2938         return false;
2939     }
2941     // Get all sections for this course and re-order them (2 of them should now share the same section number)
2942     if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2943             'section ASC, id ASC', 'id, section')) {
2944         return false;
2945     }
2947     $sections = reorder_sections($sections, $section, $destination);
2949     // Update all sections
2950     foreach ($sections as $id => $position) {
2951         $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2952     }
2954     // if the focus is on the section that is being moved, then move the focus along
2955     if (course_get_display($course->id) == $section) {
2956         course_set_display($course->id, $destination);
2957     }
2958     return true;
2961 /**
2962  * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2963  * an original position number and a target position number, rebuilds the array so that the
2964  * move is made without any duplication of section positions.
2965  * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2966  * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2967  *
2968  * @param array $sections
2969  * @param int $origin_position
2970  * @param int $target_position
2971  * @return array
2972  */
2973 function reorder_sections($sections, $origin_position, $target_position) {
2974     if (!is_array($sections)) {
2975         return false;
2976     }
2978     // We can't move section position 0
2979     if ($origin_position < 1) {
2980         echo "We can't move section position 0";
2981         return false;
2982     }
2984     // Locate origin section in sections array
2985     if (!$origin_key = array_search($origin_position, $sections)) {
2986         echo "searched position not in sections array";
2987         return false; // searched position not in sections array
2988     }
2990     // Extract origin section
2991     $origin_section = $sections[$origin_key];
2992     unset($sections[$origin_key]);
2994     // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2995     $found = false;
2996     $append_array = array();
2997     foreach ($sections as $id => $position) {
2998         if ($found) {
2999             $append_array[$id] = $position;
3000             unset($sections[$id]);
3001         }
3002         if ($position == $target_position) {
3003             $found = true;
3004         }
3005     }
3007     // Append moved section
3008     $sections[$origin_key] = $origin_section;
3010     // Append rest of array (if applicable)
3011     if (!empty($append_array)) {
3012         foreach ($append_array as $id => $position) {
3013             $sections[$id] = $position;
3014         }
3015     }
3017     // Renumber positions
3018     $position = 0;
3019     foreach ($sections as $id => $p) {
3020         $sections[$id] = $position;
3021         $position++;
3022     }
3024     return $sections;
3028 /**
3029  * Move the module object $mod to the specified $section
3030  * If $beforemod exists then that is the module
3031  * before which $modid should be inserted
3032  * All parameters are objects
3033  */
3034 function moveto_module($mod, $section, $beforemod=NULL) {
3035     global $DB, $OUTPUT;
3037 /// Remove original module from original section
3038     if (! delete_mod_from_section($mod->id, $mod->section)) {
3039         echo $OUTPUT->notification("Could not delete module from existing section");
3040     }
3042 /// Update module itself if necessary
3044     if ($mod->section != $section->id) {
3045         $mod->section = $section->id;
3046         $DB->update_record("course_modules", $mod);
3047         // if moving to a hidden section then hide module
3048         if (!$section->visible) {
3049             set_coursemodule_visible($mod->id, 0);
3050         }
3051     }
3053 /// Add the module into the new section
3055     $mod->course       = $section->course;
3056     $mod->section      = $section->section;  // need relative reference
3057     $mod->coursemodule = $mod->id;
3059     if (! add_mod_to_section($mod, $beforemod)) {
3060         return false;
3061     }
3063     return true;
3066 /**
3067  * Produces the editing buttons for a module
3068  *
3069  * @global core_renderer $OUTPUT
3070  * @staticvar type $str
3071  * @param stdClass $mod The module to produce editing buttons for
3072  * @param bool $absolute_ignored ignored - all links are absolute
3073  * @param bool $moveselect If true a move seleciton process is used (default true)
3074  * @param int $indent The current indenting
3075  * @param int $section The section to link back to
3076  * @return string XHTML for the editing buttons
3077  */
3078 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3079     global $CFG, $OUTPUT;
3081     static $str;
3083     $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3084     $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3086     $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3087     $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3089     // no permission to edit anything
3090     if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3091         return false;
3092     }
3094     $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3096     if (!isset($str)) {
3097         $str = new stdClass;
3098         $str->assign         = get_string("assignroles", 'role');
3099         $str->delete         = get_string("delete");
3100         $str->move           = get_string("move");
3101         $str->moveup         = get_string("moveup");
3102         $str->movedown       = get_string("movedown");
3103         $str->moveright      = get_string("moveright");
3104         $str->moveleft       = get_string("moveleft");
3105         $str->update         = get_string("update");
3106         $str->duplicate      = get_string("duplicate");
3107         $str->hide           = get_string("hide");
3108         $str->show           = get_string("show");
3109         $str->groupsnone     = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3110         $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3111         $str->groupsvisible  = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3112         $str->forcedgroupsnone     = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3113         $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3114         $str->forcedgroupsvisible  = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3115     }
3117     $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3119     if ($section >= 0) {
3120         $baseurl->param('sr', $section);
3121     }
3122     $actions = array();
3124     // leftright
3125     if ($hasmanageactivities) {
3126         if (right_to_left()) {   // Exchange arrows on RTL
3127             $rightarrow = 't/left';
3128             $leftarrow  = 't/right';
3129         } else {
3130             $rightarrow = 't/right';
3131             $leftarrow  = 't/left';
3132         }
3134         if ($indent > 0) {
3135             $actions[] = new action_link(
3136                 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3137                 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3138                 null,
3139                 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3140             );
3141         }
3142         if ($indent >= 0) {
3143             $actions[] = new action_link(
3144                 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3145                 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3146                 null,
3147                 array('class' => 'editing_moveright', 'title' => $str->moveright)
3148             );
3149         }
3150     }
3152     // move
3153     if ($hasmanageactivities) {
3154         if ($moveselect) {
3155             $actions[] = new action_link(
3156                 new moodle_url($baseurl, array('copy' => $mod->id)),
3157                 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3158                 null,
3159                 array('class' => 'editing_move', 'title' => $str->move)
3160             );
3161         } else {
3162             $actions[] = new action_link(
3163                 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3164                 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3165                 null,
3166                 array('class' => 'editing_moveup', 'title' => $str->moveup)
3167             );
3168             $actions[] = new action_link(
3169                 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3170                 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3171                 null,
3172                 array('class' => 'editing_movedown', 'title' => $str->movedown)
3173             );
3174         }
3175     }
3177     // Update
3178     if ($hasmanageactivities) {
3179         $actions[] = new action_link(
3180             new moodle_url($baseurl, array('update' => $mod->id)),
3181             new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3182             null,
3183             array('class' => 'editing_update', 'title' => $str->update)
3184         );
3185     }
3187     // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3188     if (has_all_capabilities($dupecaps, $coursecontext)) {
3189         $actions[] = new action_link(
3190             new moodle_url($baseurl, array('duplicate' => $mod->id)),
3191             new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3192             null,
3193             array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3194         );
3195     }
3197     // Delete
3198     if ($hasmanageactivities) {
3199         $actions[] = new action_link(
3200             new moodle_url($baseurl, array('delete' => $mod->id)),
3201             new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3202             null,
3203             array('class' => 'editing_delete', 'title' => $str->delete)
3204         );
3205     }
3207     // hideshow
3208     if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3209         if ($mod->visible) {
3210             $actions[] = new action_link(
3211                 new moodle_url($baseurl, array('hide' => $mod->id)),
3212                 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3213                 null,
3214                 array('class' => 'editing_hide', 'title' => $str->hide)
3215             );
3216         } else {
3217             $actions[] = new action_link(
3218                 new moodle_url($baseurl, array('show' => $mod->id)),
3219                 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3220                 null,
3221                 array('class' => 'editing_show', 'title' => $str->show)
3222             );
3223         }
3224     }
3226     // groupmode
3227     if ($hasmanageactivities and $mod->groupmode !== false) {
3228         if ($mod->groupmode == SEPARATEGROUPS) {
3229             $groupmode = 0;
3230             $grouptitle = $str->groupsseparate;
3231             $forcedgrouptitle = $str->forcedgroupsseparate;
3232             $groupclass = 'editing_groupsseparate';
3233             $groupimage = 't/groups';
3234         } else if ($mod->groupmode == VISIBLEGROUPS) {
3235             $groupmode = 1;
3236             $grouptitle = $str->groupsvisible;
3237             $forcedgrouptitle = $str->forcedgroupsvisible;
3238             $groupclass = 'editing_groupsvisible';
3239             $groupimage = 't/groupv';
3240         } else {
3241             $groupmode = 2;
3242             $grouptitle = $str->groupsnone;
3243             $forcedgrouptitle = $str->forcedgroupsnone;
3244             $groupclass = 'editing_groupsnone';
3245             $groupimage = 't/groupn';
3246         }
3247         if ($mod->groupmodelink) {
3248             $actions[] = new action_link(
3249                 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3250                 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3251                 null,
3252                 array('class' => $groupclass, 'title' => $grouptitle)
3253             );
3254         } else {
3255             $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3256         }
3257     }
3259     // Assign
3260     if (has_capability('moodle/role:assign', $modcontext)){
3261         $actions[] = new action_link(
3262             new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3263             new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3264             null,
3265             array('class' => 'editing_assign', 'title' => $str->assign)
3266         );
3267     }
3269     $output = html_writer::start_tag('span', array('class' => 'commands'));
3270     foreach ($actions as $action) {
3271         if ($action instanceof renderable) {
3272             $output .= $OUTPUT->render($action);
3273         } else {
3274             $output .= $action;
3275         }
3276     }
3277     $output .= html_writer::end_tag('span');
3278     return $output;
3281 /**
3282  * given a course object with shortname & fullname, this function will
3283  * truncate the the number of chars allowed and add ... if it was too long
3284  */
3285 function course_format_name ($course,$max=100) {
3287     $context = get_context_instance(CONTEXT_COURSE, $course->id);
3288     $shortname = format_string($course->shortname, true, array('context' => $context));
3289     $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3290     $str = $shortname.': '. $fullname;
3291     if (textlib::strlen($str) <= $max) {
3292         return $str;
3293     }
3294     else {
3295         return textlib::substr($str,0,$max-3).'...';
3296     }
3299 function update_restricted_mods($course, $mods) {
3300     global $DB;
3302 /// Delete all the current restricted list
3303     $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3305     if (empty($course->restrictmodules)) {
3306         return;   // We're done
3307     }
3309 /// Insert the new list of restricted mods
3310     foreach ($mods as $mod) {
3311         if ($mod == 0) {
3312             continue; // this is the 'allow none' option
3313         }
3314         $am = new stdClass();
3315         $am->course = $course->id;
3316         $am->module = $mod;
3317         $DB->insert_record('course_allowed_modules',$am);
3318     }
3321 /**
3322  * This function will take an int (module id) or a string (module name)
3323  * and return true or false, whether it's allowed in the given course (object)
3324  * $mod is not allowed to be an object, as the field for the module id is inconsistent
3325  * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3326  */
3328 function course_allowed_module($course,$mod) {
3329     global $DB;
3331     if (empty($course->restrictmodules)) {
3332         return true;
3333     }
3335     // Admins and admin-like people who can edit everything can also add anything.
3336     // Originally there was a course:update test only, but it did not match the test in course edit form
3337     if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3338         return true;
3339     }
3341     if (is_numeric($mod)) {
3342         $modid = $mod;
3343     } else if (is_string($mod)) {
3344         $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3345     }
3346     if (empty($modid)) {
3347         return false;
3348     }
3350     return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3353 /**
3354  * Recursively delete category including all subcategories and courses.
3355  * @param stdClass $category
3356  * @param boolean $showfeedback display some notices
3357  * @return array return deleted courses
3358  */
3359 function category_delete_full($category, $showfeedback=true) {
3360     global $CFG, $DB;
3361     require_once($CFG->libdir.'/gradelib.php');
3362     require_once($CFG->libdir.'/questionlib.php');
3363     require_once($CFG->dirroot.'/cohort/lib.php');
3365     if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3366         foreach ($children as $childcat) {
3367             category_delete_full($childcat, $showfeedback);
3368         }
3369     }
3371     $deletedcourses = array();
3372     if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3373         foreach ($courses as $course) {
3374             if (!delete_course($course, false)) {
3375                 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3376             }
3377             $deletedcourses[] = $course;
3378         }
3379     }
3381     // move or delete cohorts in this context
3382     cohort_delete_category($category);
3384     // now delete anything that may depend on course category context
3385     grade_course_category_delete($category->id, 0, $showfeedback);
3386     if (!question_delete_course_category($category, 0, $showfeedback)) {
3387         throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3388     }
3390     // finally delete the category and it's context
3391     $DB->delete_records('course_categories', array('id'=>$category->id));
3392     delete_context(CONTEXT_COURSECAT, $category->id);
3394     events_trigger('course_category_deleted', $category);
3396     return $deletedcourses;
3399 /**
3400  * Delete category, but move contents to another category.
3401  * @param object $ccategory
3402  * @param int $newparentid category id
3403  * @return bool status
3404  */
3405 function category_delete_move($category, $newparentid, $showfeedback=true) {
3406     global $CFG, $DB, $OUTPUT;
3407     require_once($CFG->libdir.'/gradelib.php');
3408     require_once($CFG->libdir.'/questionlib.php');
3409     require_once($CFG->dirroot.'/cohort/lib.php');
3411     if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3412         return false;
3413     }
3415     if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3416         foreach ($children as $childcat) {
3417             move_category($childcat, $newparentcat);
3418         }
3419     }
3421     if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3422         if (!move_courses(array_keys($courses), $newparentid)) {
3423             echo $OUTPUT->notification("Error moving courses");
3424             return false;
3425         }
3426         echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3427     }
3429     // move or delete cohorts in this context
3430     cohort_delete_category($category);
3432     // now delete anything that may depend on course category context
3433     grade_course_category_delete($category->id, $newparentid, $showfeedback);
3434     if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3435         echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3436         return false;
3437     }
3439     // finally delete the category and it's context
3440     $DB->delete_records('course_categories', array('id'=>$category->id));
3441     delete_context(CONTEXT_COURSECAT, $category->id);
3443     events_trigger('course_category_deleted', $category);
3445     echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3447     return true;
3450 /**
3451  * Efficiently moves many courses around while maintaining
3452  * sortorder in order.
3453  *
3454  * @param array $courseids is an array of course ids
3455  * @param int $categoryid
3456  * @return bool success
3457  */
3458 function move_courses($courseids, $categoryid) {
3459     global $CFG, $DB, $OUTPUT;
3461     if (empty($courseids)) {
3462         // nothing to do
3463         return;
3464     }
3466     if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3467         return false;
3468     }
3470     $courseids = array_reverse($courseids);
3471     $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3472     $i = 1;
3474     foreach ($courseids as $courseid) {
3475         if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3476             $course = new stdClass();
3477             $course->id = $courseid;
3478             $course->category  = $category->id;
3479             $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3480             if ($category->visible == 0) {
3481                 // hide the course when moving into hidden category,
3482                 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3483                 $course->visible = 0;
3484             }
3486             $DB->update_record('course', $course);
3488             $context   = get_context_instance(CONTEXT_COURSE, $course->id);
3489             context_moved($context, $newparent);
3490         }
3491     }
3492     fix_course_sortorder();
3494     return true;
3497 /**
3498  * Hide course category and child course and subcategories
3499  * @param stdClass $category
3500  * @return void
3501  */
3502 function course_category_hide($category) {
3503     global $DB;
3505     $category->visible = 0;
3506     $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3507     $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3508     $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
3509     $DB->set_field('course', 'visible', 0, array('category' => $category->id));