MDL-25249 Tidied up calendar variable passing and removed session abuse
authorSam Hemelryk <sam@moodle.com>
Wed, 29 Jun 2011 06:50:38 +0000 (14:50 +0800)
committerSam Hemelryk <sam@moodle.com>
Wed, 29 Jun 2011 06:50:38 +0000 (14:50 +0800)
12 files changed:
blocks/calendar_month/block_calendar_month.php
blocks/calendar_upcoming/block_calendar_upcoming.php
calendar/event.php
calendar/export.php
calendar/lib.php
calendar/preferences.php
calendar/renderer.php
calendar/set.php
calendar/view.php
lib/adminlib.php
lib/moodlelib.php
lib/navigationlib.php

index 9fa7ecb..b578d4d 100644 (file)
@@ -19,8 +19,6 @@ class block_calendar_month extends block_base {
         if ($this->content !== NULL) {
             return $this->content;
         }
-        // Reset the session variables
-        calendar_session_vars($this->page->course);
 
         $this->content = new stdClass;
         $this->content->text = '';
@@ -29,52 +27,30 @@ class block_calendar_month extends block_base {
         // [pj] To me it looks like this if would never be needed, but Penny added it
         // when committing the /my/ stuff. Reminder to discuss and learn what it's about.
         // It definitely needs SOME comment here!
-        $courseshown = $this->page->course->id;
+        $courseid = $this->page->course->id;
+        $issite = ($courseid == SITEID);
 
-        if ($courseshown == SITEID) {
+        if ($issite) {
             // Being displayed at site level. This will cause the filter to fall back to auto-detecting
             // the list of courses it will be grabbing events from.
-            $filtercourse    = NULL;
-            $groupeventsfrom = NULL;
-            $SESSION->cal_courses_shown = calendar_get_default_courses(true);
-            calendar_set_referring_course(0);
-
+            $filtercourse = calendar_get_default_courses();
         } else {
             // Forcibly filter events to include only those from the particular course we are in.
-            $filtercourse    = array($courseshown => $this->page->course);
-            $groupeventsfrom = array($courseshown => 1);
-        }
-
-        // We 'll need this later
-        calendar_set_referring_course($courseshown);
-
-        // MDL-9059, set to show this course when admins go into a course, then unset it.
-        if ($this->page->course->id != SITEID && !isset($SESSION->cal_courses_shown[$this->page->course->id]) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
-            $courseset = true;
-            $SESSION->cal_courses_shown[$this->page->course->id] = $this->page->course;
+            $filtercourse = array($courseid => $this->page->course);
         }
 
-        // Be VERY careful with the format for default courses arguments!
-        // Correct formatting is [courseid] => 1 to be concise with moodlelib.php functions.
-        calendar_set_filters($courses, $group, $user, $filtercourse, $groupeventsfrom, false);
-        if ($courseshown == SITEID) {
+        list($courses, $group, $user) = calendar_set_filters($filtercourse);
+        if ($issite) {
             // For the front page
-            $this->content->text .= calendar_top_controls('frontpage', array('id' => $courseshown, 'm' => $cal_m, 'y' => $cal_y));
+            $this->content->text .= calendar_top_controls('frontpage', array('id' => $courseid, 'm' => $cal_m, 'y' => $cal_y));
             $this->content->text .= calendar_get_mini($courses, $group, $user, $cal_m, $cal_y);
             // No filters for now
-
         } else {
             // For any other course
-            $this->content->text .= calendar_top_controls('course', array('id' => $courseshown, 'm' => $cal_m, 'y' => $cal_y));
+            $this->content->text .= calendar_top_controls('course', array('id' => $courseid, 'm' => $cal_m, 'y' => $cal_y));
             $this->content->text .= calendar_get_mini($courses, $group, $user, $cal_m, $cal_y);
             $this->content->text .= '<h3 class="eventskey">'.get_string('eventskey', 'calendar').'</h3>';
-            $this->content->text .= '<div class="filters">'.calendar_filter_controls('course', '', $this->page->course).'</div>';
-
-        }
-
-        // MDL-9059, unset this so that it doesn't stay in session
-        if (!empty($courseset)) {
-            unset($SESSION->cal_courses_shown[$this->page->course->id]);
+            $this->content->text .= '<div class="filters">'.calendar_filter_controls($this->page->url).'</div>';
         }
 
         return $this->content;
index 21d63b4..3b35210 100644 (file)
@@ -15,14 +15,12 @@ class block_calendar_upcoming extends block_base {
         if ($this->content !== NULL) {
             return $this->content;
         }
-        // Reset the session variables
-        calendar_session_vars($this->page->course);
         $this->content = new stdClass;
         $this->content->text = '';
 
+        $filtercourse    = array();
         if (empty($this->instance)) { // Overrides: use no course at all
             $courseshown = false;
-            $filtercourse = array();
             $this->content->footer = '';
 
         } else {
@@ -31,8 +29,7 @@ class block_calendar_upcoming extends block_base {
                                      '/calendar/view.php?view=upcoming&amp;course='.$courseshown.'">'.
                                       get_string('gotocalendar', 'calendar').'</a>...</div>';
             $context = get_context_instance(CONTEXT_COURSE, $courseshown);
-            if (has_capability('moodle/calendar:manageentries', $context) ||
-                has_capability('moodle/calendar:manageownentries', $context)) {
+            if (has_any_capability(array('moodle/calendar:manageentries', 'moodle/calendar:manageownentries'), $context)) {
                 $this->content->footer .= '<div class="newevent"><a href="'.$CFG->wwwroot.
                                           '/calendar/event.php?action=new&amp;course='.$courseshown.'">'.
                                            get_string('newevent', 'calendar').'</a>...</div>';
@@ -40,36 +37,34 @@ class block_calendar_upcoming extends block_base {
             if ($courseshown == SITEID) {
                 // Being displayed at site level. This will cause the filter to fall back to auto-detecting
                 // the list of courses it will be grabbing events from.
-                $filtercourse    = NULL;
-                $groupeventsfrom = NULL;
-                $SESSION->cal_courses_shown = calendar_get_default_courses(true);
-                calendar_set_referring_course(0);
+                $filtercourse = calendar_get_default_courses();
             } else {
                 // Forcibly filter events to include only those from the particular course we are in.
-                $filtercourse    = array($courseshown => $this->page->course);
-                $groupeventsfrom = array($courseshown => 1);
+                $filtercourse = array($courseshown => $this->page->course);
             }
         }
 
-        // We 'll need this later
-        calendar_set_referring_course($courseshown);
+        list($courses, $group, $user) = calendar_set_filters($filtercourse);
 
-        // Be VERY careful with the format for default courses arguments!
-        // Correct formatting is [courseid] => 1 to be concise with moodlelib.php functions.
+        $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
+        if (isset($CFG->calendar_lookahead)) {
+            $defaultlookahead = intval($CFG->calendar_lookahead);
+        }
+        $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
 
-        calendar_set_filters($courses, $group, $user, $filtercourse, $groupeventsfrom, false);
-        $events = calendar_get_upcoming($courses, $group, $user,
-                                        get_user_preferences('calendar_lookahead', CALENDAR_UPCOMING_DAYS),
-                                        get_user_preferences('calendar_maxevents', CALENDAR_UPCOMING_MAXEVENTS));
+        $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
+        if (isset($CFG->calendar_maxevents)) {
+            $defaultmaxevents = intval($CFG->calendar_maxevents);
+        }
+        $maxevents = get_user_preferences('calendar_maxevents', $defaultmaxevents);
+        $events = calendar_get_upcoming($courses, $group, $user, $lookahead, $maxevents);
 
         if (!empty($this->instance)) {
-            $this->content->text = calendar_get_block_upcoming($events,
-                                   'view.php?view=day&amp;course='.$courseshown.'&amp;');
+            $this->content->text = calendar_get_block_upcoming($events, 'view.php?view=day&amp;course='.$courseshown.'&amp;');
         }
 
         if (empty($this->content->text)) {
-            $this->content->text = '<div class="post">'.
-                                   get_string('noupcomingevents', 'calendar').'</div>';
+            $this->content->text = '<div class="post">'. get_string('noupcomingevents', 'calendar').'</div>';
         }
 
         return $this->content;
index 2e6fa67..dd98be3 100644 (file)
@@ -55,26 +55,43 @@ require_login();
 
 $action = optional_param('action', 'new', PARAM_ALPHA);
 $eventid = optional_param('id', 0, PARAM_INT);
-$courseid = optional_param('courseid', 0, PARAM_INT);
+$courseid = optional_param('courseid', SITEID, PARAM_INT);
+$courseid = optional_param('course', $courseid, PARAM_INT);
 $cal_y = optional_param('cal_y', 0, PARAM_INT);
 $cal_m = optional_param('cal_m', 0, PARAM_INT);
 $cal_d = optional_param('cal_d', 0, PARAM_INT);
 
-if ($courseid === 0) {
-    $courseid = optional_param('course', 0, PARAM_INT);
+$url = new moodle_url('/calendar/event.php', array('action' => $action));
+if ($eventid != 0) {
+    $url->param('id', $eventid);
+}
+if ($courseid != SITEID) {
+    $url->param('course', $courseid);
+}
+if ($cal_y !== 0) {
+    $url->param('cal_y', $cal_y);
+}
+if ($cal_m !== 0) {
+    $url->param('cal_m', $cal_m);
+}
+if ($cal_d !== 0) {
+    $url->param('cal_d', $cal_d);
 }
-
-$url = new moodle_url('/calendar/event.php', array('action'=>$action));
-if ($eventid !== 0) $url->param('id', $eventid);
-if ($courseid !== 0) $url->param('course', $courseid);
-if ($cal_y !== 0) $url->param('cal_y', $cal_y);
-if ($cal_m !== 0) $url->param('cal_m', $cal_m);
-if ($cal_d !== 0) $url->param('cal_d', $cal_d);
 $PAGE->set_url($url);
-$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
 $PAGE->set_pagelayout('standard');
 
-if ($action === 'delete' && $eventid>0) {
+if ($courseid != SITEID && !empty($courseid)) {
+    $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
+    $courses = array($course->id => $course);
+    $issite = false;
+} else {
+    $course = get_site();
+    $courses = calendar_get_default_courses();
+    $issite = true;
+}
+require_login($course, false);
+
+if ($action === 'delete' && $eventid > 0) {
     $deleteurl = new moodle_url('/calendar/delete.php', array('id'=>$eventid));
     if ($courseid > 0) {
         $deleteurl->param('course', $courseid);
@@ -82,56 +99,10 @@ if ($action === 'delete' && $eventid>0) {
     redirect($deleteurl);
 }
 
-$viewcalendarurl = new moodle_url(CALENDAR_URL.'view.php');
-$viewcalendarurl->params($PAGE->url->params());
-$viewcalendarurl->remove_params(array('id','action'));
-
-$now = usergetdate(time());
-
-if (isguestuser()) {
-    // Guests cannot do anything with events
-    redirect(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming', 'course'=>$courseid)));
-}
-
-$focus = '';
-
-$site = get_site();
-
-calendar_session_vars();
-
-// If a course has been supplied in the URL, change the filters to show that one
-$courseexists = false;
-if ($courseid > 0) {
-    if ($courseid == SITEID) {
-        // If coming from the site page, show all courses
-        $SESSION->cal_courses_shown = calendar_get_default_courses(true);
-        calendar_set_referring_course(0);
-    } else if ($DB->record_exists('course', array('id'=>$courseid))) {
-        $courseexists = true;
-        // Otherwise show just this one
-        $SESSION->cal_courses_shown = $courseid;
-        calendar_set_referring_course($SESSION->cal_courses_shown);
-    }
-}
-
-if (!empty($SESSION->cal_course_referer)) {
-    // TODO: This is part of the Great $course Hack in Moodle. Replace it at some point.
-    $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
-} else {
-    $course = $site;
-}
-
-require_login($course, false);
-
 $calendar = new calendar_information($cal_d, $cal_m, $cal_y);
-$calendar->courseid = $courseid;
-
-$strcalendar = get_string('calendar', 'calendar');
-$link = clone($viewcalendarurl);
-$link->param('view', 'upcoming');
+$calendar->prepare_for_view($course, $courses);
 
 $formoptions = new stdClass;
-
 if ($eventid !== 0) {
     $title = get_string('editevent', 'calendar');
     $event = calendar_event::load($eventid);
@@ -148,13 +119,13 @@ if ($eventid !== 0) {
     }
 } else {
     $title = get_string('newevent', 'calendar');
-    calendar_get_allowed_types($formoptions->eventtypes, $USER->id);
+    calendar_get_allowed_types($formoptions->eventtypes, $course);
     $event = new stdClass();
     $event->action = $action;
     $event->course = $courseid;
     $event->timeduration = 0;
     if ($formoptions->eventtypes->courses) {
-        if ($courseexists) {
+        if (!$issite) {
             $event->courseid = $courseid;
             $event->eventtype = 'course';
         } else {
@@ -165,6 +136,7 @@ if ($eventid !== 0) {
     if($cal_y && $cal_m && $cal_d && checkdate($cal_m, $cal_d, $cal_y)) {
         $event->timestart = make_timestamp($cal_y, $cal_m, $cal_d, 0, 0, 0);
     } else if($cal_y && $cal_m && checkdate($cal_m, 1, $cal_y)) {
+        $now = usergetdate(time());
         if($cal_y == $now['year'] && $cal_m == $now['mon']) {
             $event->timestart = make_timestamp($cal_y, $cal_m, $now['mday'], 0, 0, 0);
         } else {
@@ -193,23 +165,31 @@ if ($data) {
     }
 
     $event->update($data);
-    $eventurl = new moodle_url(CALENDAR_URL.'view.php', array('view'=>'day'));
-    if (!empty($event->courseid)) {
+
+    $params = array(
+        'view' => 'day',
+        'cal_d' => date('j', $event->timestart),
+        'cal_m' => date('n', $event->timestart),
+        'cal_y' => date('y', $event->timestart),
+    );
+    $eventurl = new moodle_url('/calendar/view.php', $params);
+    if (!empty($event->courseid) && $event->courseid != SITEID) {
         $eventurl->param('course', $event->courseid);
     }
-    $eventurl->param('cal_d', date('j', $event->timestart));
-    $eventurl->param('cal_m', date('n', $event->timestart));
-    $eventurl->param('cal_y', date('Y', $event->timestart));
     $eventurl->set_anchor('event_'.$event->id);
     redirect($eventurl);
 }
 
-$PAGE->navbar->add($strcalendar, $link);
+$viewcalendarurl = new moodle_url(CALENDAR_URL.'view.php', $PAGE->url->params());
+$viewcalendarurl->remove_params(array('id', 'action'));
+$viewcalendarurl->param('view', 'upcoming');
+$strcalendar = get_string('calendar', 'calendar');
+
+$PAGE->navbar->add($strcalendar, $viewcalendarurl);
 $PAGE->navbar->add($title);
-$PAGE->set_title($site->shortname.': '.$strcalendar.': '.$title);
-$PAGE->set_heading($COURSE->fullname);
+$PAGE->set_title($course->shortname.': '.$strcalendar.': '.$title);
+$PAGE->set_heading($course->fullname);
 
-calendar_set_filters($calendar->courses, $calendar->groups, $calendar->users);
 $renderer = $PAGE->get_renderer('core_calendar');
 $calendar->add_sidecalendar_blocks($renderer);
 
index 46b3436..d43f665 100644 (file)
 require_once('../config.php');
 require_once($CFG->dirroot.'/course/lib.php');
 require_once($CFG->dirroot.'/calendar/lib.php');
-//require_once($CFG->libdir.'/bennu/bennu.inc.php');
 
+if (empty($CFG->enablecalendarexport)) {
+    die('no export');
+}
+
+$courseid = optional_param('course', SITEID, PARAM_INT);
 $action = optional_param('action', '', PARAM_ALPHA);
 $day  = optional_param('cal_d', 0, PARAM_INT);
 $mon  = optional_param('cal_m', 0, PARAM_INT);
 $yr   = optional_param('cal_y', 0, PARAM_INT);
-if ($courseid = optional_param('course', 0, PARAM_INT)) {
-    $course = $DB->get_record('course', array('id'=>$courseid));
+
+if ($courseid != SITEID && !empty($courseid)) {
+    $course = $DB->get_record('course', array('id' => $courseid));
+    $courses = array($course->id => $course);
+    $issite = false;
 } else {
-    $course = NULL;
+    $course = get_site();
+    $courses = calendar_get_default_courses();
+    $issite = true;
 }
+require_course_login($course);
 
 $url = new moodle_url('/calendar/export.php');
 if ($action !== '') {
@@ -79,57 +89,22 @@ if ($course !== NULL) {
 }
 $PAGE->set_url($url);
 
-require_login($course);
-if (!$course) {
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); //TODO: wrong
-}
-
-if (empty($CFG->enablecalendarexport)) {
-    die('no export');
-}
-
-$site = get_site();
-
-// Initialize the session variables
-calendar_session_vars();
+$calendar = new calendar_information($day, $mon, $yr);
+$calendar->prepare_for_view($course, $courses);
 
 $pagetitle = get_string('export', 'calendar');
-$navlinks = array();
-$now = usergetdate(time());
 
-if (!empty($courseid) && $course->id != SITEID) {
+// Print title and header
+if ($issite) {
     $PAGE->navbar->add($course->shortname, new moodle_url('/course/view.php', array('id'=>$course->id)));
 }
-
-$calendar = new calendar_information($day, $mon, $yr);
-$calendar->courseid = $courseid;
-
-
-if(!checkdate($mon, $day, $yr)) {
-    $day = intval($now['mday']);
-    $mon = intval($now['mon']);
-    $yr = intval($now['year']);
-}
-$time = make_timestamp($yr, $mon, $day);
-
-if (!isloggedin() or isguestuser()) {
-    $defaultcourses = calendar_get_default_courses();
-    calendar_set_filters($calendar->courses, $calendar->groups, $calendar->users, $defaultcourses, $defaultcourses);
-} else {
-    calendar_set_filters($calendar->courses, $calendar->groups, $calendar->users);
-}
-
-$strcalendar = get_string('calendar', 'calendar');
-$prefsbutton = calendar_preferences_button();
-
-// Print title and header
 $link = new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming', 'course'=>$calendar->courseid));
 $PAGE->navbar->add(get_string('calendar', 'calendar'), calendar_get_link_href($link, $now['mday'], $now['mon'], $now['year']));
 $PAGE->navbar->add($pagetitle);
 
-$PAGE->set_title($site->shortname.': '.$strcalendar.': '.$pagetitle);
-$PAGE->set_heading($COURSE->fullname);
-$PAGE->set_button($prefsbutton);
+$PAGE->set_title($course->shortname.': '.get_string('calendar', 'calendar').': '.$pagetitle);
+$PAGE->set_heading($course->fullname);
+$PAGE->set_button(calendar_preferences_button($course));
 $PAGE->set_pagelayout('standard');
 
 $renderer = $PAGE->get_renderer('core_calendar');
@@ -139,19 +114,26 @@ echo $OUTPUT->header();
 echo $renderer->start_layout();
 switch($action) {
     case 'advanced':
-    break;
+        // Why nothing?
+        break;
     case '':
     default:
+        $weekend = CALENDAR_DEFAULT_WEEKEND;
+        if (isset($CFG->calendar_weekend)) {
+            $weekend = intval($CFG->calendar_weekend);
+        }
         $username = $USER->username;
         $authtoken = sha1($USER->username . $USER->password . $CFG->calendar_exportsalt);
         // Let's populate some vars to let "common tasks" be somewhat smart...
         // If today it's weekend, give the "next week" option
-        $allownextweek  = CALENDAR_WEEKEND & (1 << $now['wday']);
+        $allownextweek  = $weekend & (1 << $now['wday']);
         // If it's the last week of the month, give the "next month" option
         $allownextmonth = calendar_days_in_month($now['mon'], $now['year']) - $now['mday'] < 7;
         // If today it's weekend but tomorrow it isn't, do NOT give the "this week" option
-        $allowthisweek  = !((CALENDAR_WEEKEND & (1 << $now['wday'])) && !(CALENDAR_WEEKEND & (1 << (($now['wday'] + 1) % 7))));
+        $allowthisweek  = !(($weekend & (1 << $now['wday'])) && !($weekend & (1 << (($now['wday'] + 1) % 7))));
         echo $renderer->basic_export_form($allowthisweek, $allownextweek, $allownextmonth, $username, $authtoken);
+        break;
 }
+
 echo $renderer->complete_layout();
 echo $OUTPUT->footer();
index 926a551..9c963bc 100644 (file)
@@ -45,20 +45,29 @@ define('CALENDAR_DEFAULT_STARTING_WEEKDAY',   1);
 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
 define('CALENDAR_DEFAULT_WEEKEND',            65);
-define('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
-define('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
-define('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
 define('CALENDAR_TF_24', '%H:%M');
 define('CALENDAR_TF_12', '%I:%M %p');
 
+define('CALENDAR_EVENT_GLOBAL', 1);
+define('CALENDAR_EVENT_COURSE', 2);
+define('CALENDAR_EVENT_GROUP', 4);
+define('CALENDAR_EVENT_USER', 8);
+
 /**
  * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
  * @deprecated
  */
 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
 
-$CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
+/**
+ * Return the days of the week
+ *
+ * @return array
+ */
+function calendar_get_days() {
+    return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
+}
 
 /**
  * Gets the first day of the week
@@ -197,8 +206,7 @@ function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_y
     calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
 
     //Accessibility: added summary and <abbr> elements.
-    ///global $CALENDARDAYS; appears to be broken.
-    $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
+    $days_title = calendar_get_days();
 
     $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
     $summary = get_string('tabledata', 'access', $summary);
@@ -224,6 +232,11 @@ function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_y
         $content .= '<td class="dayblank">&nbsp;</td>'."\n";
     }
 
+    $weekend = CALENDAR_DEFAULT_WEEKEND;
+    if (isset($CFG->calendar_weekend)) {
+        $weekend = intval($CFG->calendar_weekend);
+    }
+
     // Now display all the calendar
     for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
         if($dayweek > $display->maxwday) {
@@ -234,7 +247,7 @@ function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_y
 
         // Reset vars
         $cell = '';
-        if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
+        if ($weekend & (1 << ($dayweek % 7))) {
             // Weekend. This is true no matter what the exact range is.
             $class = 'weekend day';
         } else {
@@ -665,7 +678,7 @@ function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withdur
 }
 
 function calendar_top_controls($type, $data) {
-    global $CFG, $CALENDARDAYS;
+    global $CFG;
     $content = '';
     if(!isset($data['d'])) {
         $data['d'] = 1;
@@ -786,11 +799,12 @@ function calendar_top_controls($type, $data) {
             $content .= html_writer::end_tag('div')."\n";
             break;
         case 'day':
+            $days = calendar_get_days();
             $data['d'] = $date['mday']; // Just for convenience
             $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
             $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
-            $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
-            $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
+            $prevname = calendar_wday_name($days[$prevdate['wday']]);
+            $nextname = calendar_wday_name($days[$nextdate['wday']]);
             $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
             $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
 
@@ -814,79 +828,61 @@ function calendar_top_controls($type, $data) {
     return $content;
 }
 
-function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
-    global $CFG, $SESSION, $USER, $OUTPUT;
+function calendar_filter_controls(moodle_url $returnurl) {
+    global $CFG, $USER, $OUTPUT;
 
     $groupevents = true;
-    $getvars = '';
 
     $id = optional_param( 'id',0,PARAM_INT );
 
-    switch($type) {
-        case 'event':
-        case 'upcoming':
-        case 'day':
-        case 'month':
-            $getvars = '&amp;from='.$type;
-        break;
-        case 'course':
-            if ($id > 0) {
-                $getvars = '&amp;from=course&amp;id='.$id;
-            } else {
-                $getvars = '&amp;from=course';
-            }
-            if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
-                $groupevents = false;
-            }
-        break;
-    }
-
-    if (!empty($vars)) {
-        $getvars .= '&amp;'.$vars;
-    }
+    $seturl = new moodle_url('/calendar/set.php', array('return' => $returnurl));
 
     $content = '<table>';
-
     $content .= '<tr>';
-    if($SESSION->cal_show_global) {
-        $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
-        $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
+
+    $seturl->param('var', 'showglobal');
+    if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
+        $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
     } else {
-        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
-        $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
+        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
     }
-    if($SESSION->cal_show_course) {
-        $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
-        $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
-    } else {
-        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
-        $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
 
+    $seturl->param('var', 'showcourses');
+    if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
+        $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
+    } else {
+        $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+        $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
     }
 
-
     if (isloggedin() && !isguestuser()) {
         $content .= "</tr>\n<tr>";
 
-        if($groupevents) {
+        if ($groupevents) {
             // This course MIGHT have group events defined, so show the filter
-            if($SESSION->cal_show_groups) {
-                $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
-                $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
+            $seturl->param('var', 'showgroups');
+            if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
+                $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+                $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
             } else {
-                $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
-                $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
+                $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+                $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
             }
         } else {
             // This course CANNOT have group events, so lose the filter
             $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
         }
-        if($SESSION->cal_show_user) {
-            $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
-            $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
+
+        $seturl->param('var', 'showuser');
+        if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
+            $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+            $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
         } else {
-            $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
-            $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
+            $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
+            $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
         }
     }
     $content .= "</tr>\n</table>\n";
@@ -1204,212 +1200,89 @@ function calendar_get_course_cached(&$coursecache, $courseid) {
     return $coursecache[$courseid];
 }
 
-function calendar_session_vars($course=null) {
-    global $SESSION, $USER;
+/**
+ * Returns the courses to load events for, the
+ *
+ * @global moodle_database $DB
+ * @param array $courseeventsfrom An array of courses to load calendar events for
+ * @param bool $ignorefilters
+ * @return array An array of courses, groups, and user to load calendar events for based upon filters
+ */
+function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
+    global $USER, $CFG, $DB;
 
-    if(!isset($SESSION->cal_course_referer)) {
-        $SESSION->cal_course_referer = 0;
-    }
-    if(!isset($SESSION->cal_show_global)) {
-        $SESSION->cal_show_global = true;
-    }
-    if(!isset($SESSION->cal_show_groups)) {
-        $SESSION->cal_show_groups = true;
-    }
-    if(!isset($SESSION->cal_show_course)) {
-        $SESSION->cal_show_course = true;
-    }
-    if(!isset($SESSION->cal_show_user)) {
-        $SESSION->cal_show_user = true;
-    }
-    if ($course !== null) {
-        // speedup hack for calendar related blocks
-        if(isset($course->coursenode)) {
-            // coursenode has been set up, which seems to break things further down the line.
-            // Use a clone of $course with coursenode removed.
-            $course = clone $course;
-            unset($course->coursenode);
+    // For backwards compatability we have to check whether the courses array contains
+    // just id's in which case we need to load course objects.
+    $coursestoload = array();
+    foreach ($courseeventsfrom as $id => $something) {
+        if (!is_object($something)) {
+            $coursestoload[] = $id;
+            unset($courseeventsfrom[$id]);
         }
-        $SESSION->cal_courses_shown = array($course->id => $course);
-    } else {
-        $SESSION->cal_courses_shown = calendar_get_default_courses(true);
     }
-    if(empty($SESSION->cal_users_shown)) {
-        // The empty() instead of !isset() here makes a whole world of difference,
-        // as it will automatically change to the user's id when the user first logs
-        // in. With !isset(), it would never do that.
-        $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
-    } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
-        // Follow the white rabbit, for example if a teacher logs in as a student
-        $SESSION->cal_users_shown = $USER->id;
+    if (!empty($coursestoload)) {
+        // TODO remove this in 2.2
+        debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
+        $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
     }
-}
 
-function calendar_set_referring_course($courseid) {
-    global $SESSION;
-    $SESSION->cal_course_referer = intval($courseid);
-}
+    $courses = array();
+    $user = false;
+    $group = false;
 
-function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
-    global $SESSION, $USER, $CFG, $DB;
-
-    // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
-    // the code to function incorrectly UNLESS we convert it to an integer. One case where
-    // PHP's loose type system works against us.
-    if(is_string($SESSION->cal_courses_shown)) {
-        $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
-    }
-    if($courseeventsfrom === NULL) {
-        $courseeventsfrom = $SESSION->cal_courses_shown;
-    }
-
-    // MDL-9059, $courseeventsfrom can be an int, or an array of ints, or an array of course objects
-    // convert all to array of objects
-    // we probably should do some clean up and make sure that session is set to use the proper form
-    if (is_int($courseeventsfrom)) { // case of an int, e.g. calendar view page
-        $c = array();
-        $c[$courseeventsfrom] = $DB->get_record('course', array('id'=>$courseeventsfrom));
-        $courseeventsfrom = $c;
-    } else if (is_array($courseeventsfrom)) { // case of an array of ints, e.g. course home page
-        foreach ($courseeventsfrom as $i=>$courseid) { // TODO: this seems wrong, the array is often constructed as [courseid] => 1 ???
-            if (is_int($courseid)) {
-                $courseeventsfrom[$i] = $DB->get_record('course', array('id'=>$courseid));
-            }
-        }
-    }
+    $isloggedin = isloggedin();
 
-    if($groupeventsfrom === NULL) {
-        $groupeventsfrom = $SESSION->cal_courses_shown;
+    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
+        $courses = array_keys($courseeventsfrom);
     }
-
-    if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
-        if(is_int($courseeventsfrom)) {
-            $courses = array(SITEID, $courseeventsfrom);
-        }
-        else if(is_array($courseeventsfrom)) {
-            $courses = array_keys($courseeventsfrom);
-            $courses[] = SITEID;
-        }
+    if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
+        $courses[] = SITEID;
     }
-    else if($SESSION->cal_show_course) {
-        if(is_int($courseeventsfrom)) {
-            $courses = array($courseeventsfrom);
-        }
-        else if(is_array($courseeventsfrom)) {
-            $courses = array_keys($courseeventsfrom);
-        }
-        $courses = array_diff($courses, array(SITEID));
-    }
-    else if($SESSION->cal_show_global) {
-        $courses = array(SITEID);
-    }
-    else {
-        $courses = false;
-    }
-    //BUG 6130 clean $courses array as SESSION has bad entries.
-    // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
-    if (is_array($courses)) {
-        foreach ($courses as $index => $value) {
-            if (empty($value)) unset($courses[$index]);
-        }
+    $courses = array_unique($courses);
+    sort($courses);
 
+    if (!empty($courses) && in_array(SITEID, $courses)) {
         // Sort courses for consistent colour highlighting
         // Effectively ignoring SITEID as setting as last course id
         $key = array_search(SITEID, $courses);
-        if ($key !== false) {
-            unset($courses[$key]);
-            sort($courses);
-            $courses[] = SITEID;
-        } else {
-            sort($courses);
-        }
+        unset($courses[$key]);
+        $courses[] = SITEID;
     }
 
-    if($SESSION->cal_show_user || $ignorefilters) {
-        // This doesn't work for arrays yet (maybe someday it will)
-        $user = $SESSION->cal_users_shown;
+    if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
+        $user = $USER->id;
     }
-    else {
-        $user = false;
-    }
-    if($SESSION->cal_show_groups || $ignorefilters) {
-        if(is_int($groupeventsfrom)) {
-            $groupcourses = array($groupeventsfrom);
-        }
-        else if(is_array($groupeventsfrom)) {
-            $groupcourses = array_keys($groupeventsfrom);
-        }
 
-        // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
-        if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
+    if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
+
+        if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_system_context())) {
             $group = true;
-        }
-        else {
-            $grouparray = array();
+        } else if ($isloggedin) {
+            $groupids = array();
 
             // We already have the courses to examine in $courses
             // For each course...
-
-            foreach($groupcourses as $courseid) {
-
-                if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
-                    if (is_object($courseeventsfrom[$courseid])) {
-                        $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
-                    }
-                }
-
+            foreach ($courseeventsfrom as $courseid => $course) {
                 // If the user is an editing teacher in there,
-                if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
+                if (!empty($USER->groupmember[$course->id])) {
+                    // We've already cached the users groups for this course so we can just use that
+                    $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
+                } else if (($course->groupmode != NOGROUPS || !$course->groupmodeforce) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $course->id))) {
                     // If this course has groups, show events from all of them
-                    if(is_int($groupeventsfrom)) {
-                        if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
-                            $courserecord = $courseeventsfrom[$courseid];
-                        } else {
-                            $courserecord = $DB->get_record('course', array('id'=>$courseid));
-                        }
-                        $courserecord = $DB->get_record('course', array('id'=>$courseid));
-                        if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
-                            $groupids[] = $courseid;
-                        }
-                    }
-                    else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
-                        $groupids[] = $courseid;
-                    }
-                }
-
-                // Otherwise (not editing teacher) show events from the group he is a member of
-                else if(isset($USER->groupmember[$courseid])) {
-                    //changed to 2D array
-                    foreach ($USER->groupmember[$courseid] as $groupid){
-                        $grouparray[] = $groupid;
-                    }
+                    $coursegroups = groups_get_user_groups($course->id, $USER->id);
+                    $groupids = array_merge($groupids, $coursegroups['0']);
                 }
             }
-
             if (!empty($groupids)) {
-                $sql = "SELECT *
-                        FROM {groups}
-                        WHERE courseid IN (".implode(',', $groupids).')';
-
-                if ($grouprecords = $DB->get_records_sql($sql, null)) {
-                    foreach ($grouprecords as $grouprecord) {
-                        $grouparray[] = $grouprecord->id;
-                    }
-                }
-            }
-
-            if(empty($grouparray)) {
-                $group = false;
-            }
-            else {
-                $group = $grouparray;
+                $group = $groupids;
             }
         }
-
     }
-    else {
-        $group = false;
+    if (empty($courses)) {
+        $courses = false;
     }
+
+    return array($courses, $group, $user);
 }
 
 function calendar_edit_event_allowed($event) {
@@ -1454,23 +1327,32 @@ function calendar_edit_event_allowed($event) {
     return false;
 }
 
-function calendar_get_default_courses($ignoreref = false) {
-    global $USER, $CFG, $SESSION, $DB;
-
-    if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
-        return array($SESSION->cal_course_referer => 1);
-    }
+/**
+ * Returns the default courses to display on the calendar when there isn't a specific
+ * course to display.
+ *
+ * @global moodle_database $DB
+ * @return array Array of courses to display
+ */
+function calendar_get_default_courses() {
+    global $CFG, $DB;
 
     if (!isloggedin()) {
         return array();
     }
 
     $courses = array();
-    if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
-        if (!empty($CFG->calendar_adminseesall)) {
-            $courses = $DB->get_records_sql('SELECT id, 1 FROM {course}');
-            return $courses;
+    if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
+        list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+        $sql = "SELECT c.* $select
+                  FROM {course} c
+                  JOIN {event} e ON e.courseid = c.id
+                  $join";
+        $courses = $DB->get_records_sql($sql, null, 0, 20);
+        foreach ($courses as $course) {
+            context_instance_preload($course);
         }
+        return $courses;
     }
 
     $courses = enrol_get_my_courses();
@@ -1478,17 +1360,15 @@ function calendar_get_default_courses($ignoreref = false) {
     return $courses;
 }
 
-function calendar_preferences_button() {
-    global $CFG, $USER;
+function calendar_preferences_button(stdClass $course) {
+    global $OUTPUT;
 
     // Guests have no preferences
     if (!isloggedin() || isguestuser()) {
         return '';
     }
 
-    return "<form method=\"get\" ".
-           " action=\"$CFG->wwwroot/calendar/preferences.php\">".
-           "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
+    return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
 }
 
 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
@@ -1588,61 +1468,93 @@ function calendar_print_month_selector($name, $selected) {
     echo html_writer::select($months, $name, $selected, false);
 }
 
-function calendar_get_filters_status() {
-    global $SESSION;
-
-    $status = 0;
-    if($SESSION->cal_show_global) {
-        $status += 1;
+/**
+ * Checks to see if the requested type of event should be shown for the given user.
+ *
+ * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
+ *          The type to check the display for (default is to display all)
+ * @param stdClass|int|null $user The user to check for - by default the current user
+ * @return bool True if the tyep should be displayed false otherwise
+ */
+function calendar_show_event_type($type, $user = null) {
+    $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
+    if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
+        global $SESSION;
+        if (!isset($SESSION->calendarshoweventtype)) {
+            $SESSION->calendarshoweventtype = $default;
+        }
+        return $SESSION->calendarshoweventtype & $type;
+    } else {
+        return get_user_preferences('calendar_savedflt', $default, $user) & $type;
     }
-    if($SESSION->cal_show_course) {
-        $status += 2;
+}
+
+/**
+ * Sets the display of the event type given $display.
+ * If $display = true the event type will be shown.
+ * If $display = false the event type will NOT be shown.
+ * If $display = null the current value will be toggled and saved.
+ *
+ * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
+ * @param true|false|null $display
+ * @param stdClass|int|null $user
+ */
+function calendar_set_event_type_display($type, $display = null, $user = null) {
+    $persist = get_user_preferences('calendar_persistflt', 0, $user);
+    $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
+    if ($persist === 0) {
+        global $SESSION;
+        if (!isset($SESSION->calendarshoweventtype)) {
+            $SESSION->calendarshoweventtype = $default;
+        }
+        $preference = $SESSION->calendarshoweventtype;
+    } else {
+        $preference = get_user_preferences('calendar_savedflt', $default, $user);
     }
-    if($SESSION->cal_show_groups) {
-        $status += 4;
+    $current = $preference & $type;
+    if ($display === null) {
+        $display = !$current;
     }
-    if($SESSION->cal_show_user) {
-        $status += 8;
+    if ($display && !$current) {
+        $preference += $type;
+    } else if (!$display && $current) {
+        $preference -= $type;
     }
-    return $status;
-}
-
-function calendar_set_filters_status($packed_bitfield) {
-    global $SESSION, $USER;
-
-    if (!isloggedin()) {
-        return false;
+    if ($persist === 0) {
+        $SESSION->calendarshoweventtype = $preference;
+    } else {
+        if ($preference == $default) {
+            unset_user_preference('calendar_savedflt', $user);
+        } else {
+            set_user_preference('calendar_savedflt', $preference, $user);
+        }
     }
-
-    $SESSION->cal_show_global = ($packed_bitfield & 1);
-    $SESSION->cal_show_course = ($packed_bitfield & 2);
-    $SESSION->cal_show_groups = ($packed_bitfield & 4);
-    $SESSION->cal_show_user   = ($packed_bitfield & 8);
-
-    return true;
 }
 
-function calendar_get_allowed_types(&$allowed) {
-    global $USER, $CFG, $SESSION, $DB;
-    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
-    $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
+function calendar_get_allowed_types(&$allowed, $course = null) {
+    global $USER, $CFG, $DB;
+    $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
     $allowed->groups = false; // This may change just below
     $allowed->courses = false; // This may change just below
     $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
 
-    if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
-        $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
-        $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
+    if (!empty($course)) {
+        if (!is_object($course)) {
+            $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
+        }
+        if ($course->id != SITEID) {
+            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
 
-        if(has_capability('moodle/calendar:manageentries', $coursecontext)) {
-            $allowed->courses = array($course->id => 1);
+            if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
+                $allowed->courses = array($course->id => 1);
 
-            if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
-                $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
-            }
-        } else if(has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
-            if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
-                $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
+                if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
+                    $allowed->groups = groups_get_all_groups($course->id);
+                }
+            } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
+                if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
+                    $allowed->groups = groups_get_all_groups($course->id);
+                }
             }
         }
     }
@@ -1653,8 +1565,11 @@ function calendar_get_allowed_types(&$allowed) {
  * used to print the "New Event" button
  * @return bool
  */
-function calendar_user_can_add_event() {
-    calendar_get_allowed_types($allowed);
+function calendar_user_can_add_event($course) {
+    if (!isloggedin() || isguestuser()) {
+        return false;
+    }
+    calendar_get_allowed_types($allowed, $course);
     return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
 }
 
@@ -2460,6 +2375,21 @@ class calendar_information {
         $this->year = $year;
     }
 
+    /**
+     *
+     * @param stdClass $course
+     * @param array $coursestoload An array of courses [$course->id => $course]
+     * @param type $ignorefilters
+     */
+    public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
+        $this->courseid = $course->id;
+        $this->course = $course;
+        list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
+        $this->courses = $courses;
+        $this->groups = $group;
+        $this->users = $user;
+    }
+
     /**
      * Ensures the date for the calendar is correct and either sets it to now
      * or throws a moodle_exception if not
index a0f7c8d..a36c9f3 100644 (file)
@@ -6,28 +6,35 @@ require_once('../config.php');
 require_once($CFG->dirroot.'/calendar/lib.php');
 require_once($CFG->dirroot.'/calendar/preferences_form.php');
 
-$course = $site = get_site();
-if (!empty($SESSION->cal_course_referer)) {
-    $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer), '*', MUST_EXIST);
-}
+$courseid = required_param('course', PARAM_INT);
+$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
+
+$PAGE->set_url('/calendar/preferences.php', array('id' => $courseid));
+$PAGE->set_pagelayout('standard');
 
-$PAGE->set_url('/calendar/preferences.php');
+require_login($course);
 
-if ($course->id != SITEID) {
-    require_login($course);
+if ($courseid == SITEID) {
+    $viewurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
 } else {
-    require_login();
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); //TODO: wrong
+    $viewurl = new moodle_url('/calendar/view.php', array('view' => 'month', 'course' => $courseid));
 }
-// Initialize the session variables
-calendar_session_vars();
+navigation_node::override_active_url($viewurl);
 
+$defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
+if (isset($CFG->calendar_lookahead)) {
+    $defaultlookahead = intval($CFG->calendar_lookahead);
+}
+$defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
+if (isset($CFG->calendar_maxevents)) {
+    $defaultmaxevents = intval($CFG->calendar_maxevents);
+}
 
 $prefs = new stdClass;
 $prefs->timeformat = get_user_preferences('calendar_timeformat', '');
 $prefs->startwday  = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
-$prefs->maxevents  = get_user_preferences('calendar_maxevents', CALENDAR_UPCOMING_MAXEVENTS);
-$prefs->lookahead  = get_user_preferences('calendar_lookahead', CALENDAR_UPCOMING_DAYS);
+$prefs->maxevents  = get_user_preferences('calendar_maxevents', $defaultmaxevents);
+$prefs->lookahead  = get_user_preferences('calendar_lookahead', $defaultlookahead);
 $prefs->persistflt = get_user_preferences('calendar_persistflt', 0);
 
 $form = new calendar_preferences_form();
@@ -54,7 +61,7 @@ if ($data = $form->get_data() && confirm_sesskey()) {
     }
 
     set_user_preference('calendar_persistflt', intval($data->persistflt));
-    redirect(new moodle_url('/calendar/view.php', array('course'=>$course->id)), get_string('changessaved'), 1);
+    redirect($viewurl, get_string('changessaved'), 1);
     exit;
 }
 
@@ -63,8 +70,8 @@ $strpreferences = get_string('calendarpreferences', 'calendar');
 
 $PAGE->navbar->add($strpreferences, new moodle_url('/calendar/view.php'));
 $PAGE->set_pagelayout('admin');
-$PAGE->set_title("$site->shortname: $strcalendar: $strpreferences");
-$PAGE->set_heading($COURSE->fullname);
+$PAGE->set_title("$course->shortname: $strcalendar: $strpreferences");
+$PAGE->set_heading($course->fullname);
 
 echo $OUTPUT->header();
 echo $OUTPUT->heading($strpreferences);
index 1c906d6..50a3090 100644 (file)
@@ -137,8 +137,7 @@ class core_calendar_renderer extends plugin_renderer_base {
      * @return string
      */
     public function fake_block_filters($courseid, $day, $month, $year, $view, $courses) {
-        $getvars = 'id='.$courseid.'&amp;cal_d='.$day.'&amp;cal_m='.$month.'&amp;cal_y='.$year;
-        return html_writer::tag('div', calendar_filter_controls($view, $getvars, NULL, $courses), array('class'=>'calendar_filters filters'));
+        return html_writer::tag('div', calendar_filter_controls($this->page->url), array('class'=>'calendar_filters filters'));
     }
 
     /**
@@ -216,16 +215,21 @@ class core_calendar_renderer extends plugin_renderer_base {
      * @param calendar_information $calendar
      * @return string
      */
-    public function show_day(calendar_information $calendar) {
+    public function show_day(calendar_information $calendar, moodle_url $returnurl = null) {
+
+        if ($returnurl === null) {
+            $returnurl = $this->page->url;
+        }
+
         $calendar->checkdate();
         $events = calendar_get_upcoming($calendar->courses, $calendar->groups, $calendar->users, 1, 100, $calendar->timestamp_today());
 
         $output  = html_writer::start_tag('div', array('class'=>'header'));
-        if (!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
-            $output .= $this->add_event_button($calendar->courseid, $calendar->day, $calendar->month, $calendar->year);
+        if (calendar_user_can_add_event($calendar->course)) {
+            $output .= $this->add_event_button($calendar->course->id, $calendar->day, $calendar->month, $calendar->year);
         }
         //$output .= html_writer::tag('label', get_string('dayview', 'calendar'), array('for'=>'cal_course_flt_jump'));
-        $output .= $this->course_filter_selector(array('from'=>'day', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year), get_string('dayview', 'calendar'));
+        $output .= $this->course_filter_selector($returnurl, get_string('dayview', 'calendar'));
         $output .= html_writer::end_tag('div');
         // Controls
         $output .= html_writer::tag('div', calendar_top_controls('day', array('id' => $calendar->courseid, 'd' => $calendar->day, 'm' => $calendar->month, 'y' => $calendar->year)), array('class'=>'controls'));
@@ -345,12 +349,15 @@ class core_calendar_renderer extends plugin_renderer_base {
     /**
      * Displays a month in detail
      *
-     * @global array $CALENDARDAYS
      * @param calendar_information $calendar
      * @return string
      */
-    public function show_month_detailed(calendar_information $calendar) {
-        global $CALENDARDAYS;
+    public function show_month_detailed(calendar_information $calendar, moodle_url $returnurl  = null) {
+        global $CFG;
+
+        if (empty($returnurl)) {
+            $returnurl = $this->page->url;
+        }
 
         $date = usergetdate(time());
 
@@ -396,14 +403,16 @@ class core_calendar_renderer extends plugin_renderer_base {
         calendar_events_by_day($events, $calendar->month, $calendar->year, $eventsbyday, $durationbyday, $typesbyday, $calendar->courses);
 
         $output  = html_writer::start_tag('div', array('class'=>'header'));
-        if(!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
-            $output .= $this->add_event_button($calendar->courseid, null, $calendar->month, $calendar->year);
+        if (calendar_user_can_add_event($calendar->course)) {
+            $output .= $this->add_event_button($calendar->course->id, null, $calendar->month, $calendar->year);
         }
-        $output .= get_string('detailedmonthview', 'calendar').': '.$this->course_filter_selector(array('from'=>'month', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year));
+        $output .= get_string('detailedmonthview', 'calendar').': '.$this->course_filter_selector($returnurl);
         $output .= html_writer::end_tag('div', array('class'=>'header'));
         // Controls
         $output .= html_writer::tag('div', calendar_top_controls('month', array('id' => $calendar->courseid, 'm' => $calendar->month, 'y' => $calendar->year)), array('class'=>'controls'));
 
+        $days = calendar_get_days();
+
         $table = new html_table();
         $table->attributes = array('class'=>'calendarmonth calendartable');
         $table->data = array();
@@ -414,7 +423,7 @@ class core_calendar_renderer extends plugin_renderer_base {
         for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
             // This uses the % operator to get the correct weekday no matter what shift we have
             // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
-            $cell = new html_table_cell(get_string($CALENDARDAYS[$i % 7], 'calendar'));
+            $cell = new html_table_cell(get_string($days[$i % 7], 'calendar'));
             $cell->header = true;
             $header->cells[] = $cell;
         }
@@ -432,6 +441,11 @@ class core_calendar_renderer extends plugin_renderer_base {
         }
 
         // Now display all the calendar
+        $weekend = CALENDAR_DEFAULT_WEEKEND;
+        if (isset($CFG->calendar_weekend)) {
+            $weekend = intval($CFG->calendar_weekend);
+        }
+
         for ($calendar->day = 1; $calendar->day <= $display->maxdays; ++$calendar->day, ++$dayweek) {
             if($dayweek > $display->maxwday) {
                 // We need to change week (table row)
@@ -447,7 +461,7 @@ class core_calendar_renderer extends plugin_renderer_base {
 
             $cellclasses = array();
 
-            if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
+            if ($weekend & (1 << ($dayweek % 7))) {
                 // Weekend. This is true no matter what the exact range is.
                 $cellclasses[] = 'weekend';
             }
@@ -532,16 +546,20 @@ class core_calendar_renderer extends plugin_renderer_base {
      * @param calendar_information $calendar
      * @return string
      */
-    protected function filter_selection_table(calendar_information $calendar) {
+    protected function filter_selection_table(calendar_information $calendar, moodle_url $returnurl = null) {
         global $SESSION;
 
+        if ($returnurl === null) {
+            $returnurl = $this->page->url;
+        }
+
         $output  = html_writer::start_tag('div', array('class'=>'filters'));
         $output .= html_writer::start_tag('table');
         $output .= html_writer::start_tag('tr');
 
         // Global events
-        $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showglobal', 'from'=>'month', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year));
-        if($SESSION->cal_show_global) {
+        $link = new moodle_url(CALENDAR_URL.'set.php', array('var' => 'showglobal', 'return' => $returnurl));
+        if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
             $output .= html_writer::tag('td', '', array('class'=>'calendar_event_global', 'style'=>'width:8px;'));
             $output .= html_writer::tag('td', html_writer::tag('strong', get_string('globalevents', 'calendar')).' '.get_string('shown', 'calendar').' ('.html_writer::link($link, get_string('clickhide', 'calendar')).')');
         } else {
@@ -550,8 +568,8 @@ class core_calendar_renderer extends plugin_renderer_base {
         }
 
         // Course events
-        $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showcourses', 'from'=>'month', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year));
-        if(!empty($SESSION->cal_show_course)) {
+        $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showcourses', 'return' => $returnurl));
+        if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
             $output .= html_writer::tag('td', '', array('class'=>'calendar_event_course', 'style'=>'width:8px;'));
             $output .= html_writer::tag('td', html_writer::tag('strong', get_string('courseevents', 'calendar')).' '.get_string('shown', 'calendar').' ('.html_writer::link($link, get_string('clickhide', 'calendar')).')');
         } else {
@@ -563,8 +581,8 @@ class core_calendar_renderer extends plugin_renderer_base {
         if(isloggedin() && !isguestuser()) {
             $output .= html_writer::start_tag('tr');
             // Group events
-            $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showgroups', 'from'=>'month', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year));
-            if($SESSION->cal_show_groups) {
+            $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showgroups', 'return' => $returnurl));
+            if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
                 $output .= html_writer::tag('td', '', array('class'=>'calendar_event_group', 'style'=>'width:8px;'));
                 $output .= html_writer::tag('td', html_writer::tag('strong', get_string('groupevents', 'calendar')).' '.get_string('shown', 'calendar').' ('.html_writer::link($link, get_string('clickhide', 'calendar')).')');
             } else {
@@ -572,8 +590,8 @@ class core_calendar_renderer extends plugin_renderer_base {
                 $output .= html_writer::tag('td', html_writer::tag('strong', get_string('groupevents', 'calendar')).' '.get_string('hidden', 'calendar').' ('.html_writer::link($link, get_string('clickshow', 'calendar')).')');
             }
             // User events
-            $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showuser', 'from'=>'month', 'cal_d'=>$calendar->day, 'cal_m'=>$calendar->month, 'cal_y'=>$calendar->year));
-            if($SESSION->cal_show_user) {
+            $link = new moodle_url(CALENDAR_URL.'set.php', array('var'=>'showuser', 'return' => $returnurl));
+            if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
                 $output .= html_writer::tag('td', '', array('class'=>'calendar_event_user', 'style'=>'width:8px;'));
                 $output .= html_writer::tag('td', html_writer::tag('strong', get_string('userevents', 'calendar')).' '.get_string('shown', 'calendar').' ('.html_writer::link($link, get_string('clickhide', 'calendar')).')');
             } else {
@@ -595,15 +613,20 @@ class core_calendar_renderer extends plugin_renderer_base {
      * @param int $maxevents
      * @return string
      */
-    public function show_upcoming_events(calendar_information $calendar, $futuredays, $maxevents) {
+    public function show_upcoming_events(calendar_information $calendar, $futuredays, $maxevents, moodle_url $returnurl = null) {
+
+        if ($returnurl === null) {
+            $returnurl = $this->page->url;
+        }
+
         $events = calendar_get_upcoming($calendar->courses, $calendar->groups, $calendar->users, $futuredays, $maxevents);
 
         $output  = html_writer::start_tag('div', array('class'=>'header'));
-        if (!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
-            $output .= $this->add_event_button($calendar->courseid);
+        if (calendar_user_can_add_event($calendar->course)) {
+            $output .= $this->add_event_button($calendar->course->id);
         }
         $output .= html_writer::tag('label', get_string('upcomingevents', 'calendar'), array('for'=>'cal_course_flt_jump'));
-        $output .= $this->course_filter_selector(array('from'=>'upcoming'));
+        $output .= $this->course_filter_selector($returnurl);
         $output .= html_writer::end_tag('div');
 
         if ($events) {
@@ -629,7 +652,7 @@ class core_calendar_renderer extends plugin_renderer_base {
      * @param array $getvars
      * @return string
      */
-    protected function course_filter_selector(array $getvars = array(), $label=null) {
+    protected function course_filter_selector(moodle_url $returnurl, $label=null) {
         global $USER, $SESSION, $CFG;
 
         if (!isloggedin() or isguestuser()) {
@@ -650,13 +673,12 @@ class core_calendar_renderer extends plugin_renderer_base {
             $courseoptions[$course->id] = format_string($course->shortname);
         }
 
-        if (is_numeric($SESSION->cal_courses_shown)) {
-            $selected = $SESSION->cal_courses_shown;
+        if ($this->page->course->id !== SITEID) {
+            $selected = $this->page->course->id;
         } else {
             $selected = '';
         }
-        $getvars['var'] = 'setcourse';
-        $select = new single_select(new moodle_url(CALENDAR_URL.'set.php', $getvars), 'id', $courseoptions, $selected, null);
+        $select = new single_select(new moodle_url(CALENDAR_URL.'set.php', array('return' => $returnurl, 'var' => 'setcourse')), 'id', $courseoptions, $selected, null);
         $select->class = 'cal_courses_flt';
         if ($label !== null) {
             $select->label = $label;
index 039139e..447547e 100644 (file)
 require_once('../config.php');
 require_once($CFG->dirroot.'/calendar/lib.php');
 
-$from = required_param('from', PARAM_ALPHA);
+$from = required_param('return', PARAM_ALPHA);
 $var = required_param('var', PARAM_ALPHA);
-$id = optional_param('id', 0, PARAM_INT);
-$cal_d = optional_param('cal_d', 0, PARAM_INT);
-$cal_m = optional_param('cal_m', 0, PARAM_INT);
-$cal_y = optional_param('cal_y', 0, PARAM_INT);
-$action = optional_param('action', '', PARAM_ALPHA);
-$type = optional_param('type', '', PARAM_ALPHA);
 
-$url = new moodle_url('/calendar/set.php', array('from'=>$from,'var'=>$var));
-if ($id !== 0) {
-    $url->param('id', $id);
-}
-if ($cal_d !== 0) {
-    $url->param('cal_d', $cal_d);
-}
-if ($cal_m !== 0) {
-    $url->param('cal_m', $cal_m);
-}
-if ($cal_y !== 0) {
-    $url->param('cal_y', $cal_y);
-}
-if ($action !== 0) {
-    $url->param('action', $action);
-}
-if ($type !== 0) {
-    $url->param('type', $type);
-}
+$url = new moodle_url('/calendar/set.php', array('return'=>$return,'var'=>$var));
 $PAGE->set_url($url);
 $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); //TODO: wrong
 
-// Initialize the session variables
-calendar_session_vars();
-
-// Ensure course id passed if relevant
-// Required due to changes in view/lib.php mainly (calendar_session_vars())
-$courseid = '';
-if (!empty($id)) {
-    $courseid = '&course='.$id;
-}
-
 switch($var) {
-    case 'setuser':
-        // Not implemented yet (or possibly at all)
-    break;
-    case 'setcourse':
-        $id = intval($id);
-        if($id == 0) {
-            $SESSION->cal_courses_shown = array();
-            calendar_set_referring_course(0);
-        }
-        else if($id == 1) {
-            $SESSION->cal_courses_shown = calendar_get_default_courses(true);
-            calendar_set_referring_course(0);
-        }
-        else {
-            if($DB->get_record('course', array('id'=>$id)) === false) {
-                // There is no such course
-                $SESSION->cal_courses_shown = array();
-                calendar_set_referring_course(0);
-            }
-            else {
-                calendar_set_referring_course($id);
-                $SESSION->cal_courses_shown = $id;
-            }
-        }
-    break;
     case 'showgroups':
-        $SESSION->cal_show_groups = !$SESSION->cal_show_groups;
-        set_user_preference('calendar_savedflt', calendar_get_filters_status());
-    break;
+        calendar_set_event_type_display(CALENDAR_EVENT_GROUP);
+        break;
     case 'showcourses':
-        $SESSION->cal_show_course = !$SESSION->cal_show_course;
-        set_user_preference('calendar_savedflt', calendar_get_filters_status());
-    break;
+        calendar_set_event_type_display(CALENDAR_EVENT_COURSE);
+        break;
     case 'showglobal':
-        $SESSION->cal_show_global = !$SESSION->cal_show_global;
-        set_user_preference('calendar_savedflt', calendar_get_filters_status());
-    break;
+        calendar_set_event_type_display(CALENDAR_EVENT_GLOBAL);
+        break;
     case 'showuser':
-        $SESSION->cal_show_user = !$SESSION->cal_show_user;
-        set_user_preference('calendar_savedflt', calendar_get_filters_status());
-    break;
+        calendar_set_event_type_display(CALENDAR_EVENT_USER);
+        break;
 }
 
-switch($from) {
-    case 'event':
-        redirect(CALENDAR_URL.'event.php?action='.$action.'&amp;type='.$type.'&amp;id='.intval($id));
-    break;
-    case 'month':
-        redirect(CALENDAR_URL.'view.php?view=month'.$courseid.'&cal_d='.$cal_d.'&cal_m='.$cal_m.'&cal_y='.$cal_y);
-    break;
-    case 'upcoming':
-        redirect(CALENDAR_URL.'view.php?view=upcoming'.$courseid);
-    break;
-    case 'day':
-        redirect(CALENDAR_URL.'view.php?view=day'.$courseid.'&cal_d='.$cal_d.'&cal_m='.$cal_m.'&cal_y='.$cal_y);
-    break;
-    case 'course':
-        redirect($CFG->wwwroot.'/course/view.php?id='.intval($id));
-    break;
-    default:
-
-}
\ No newline at end of file
+redirect($return);
\ No newline at end of file
index a1a06be..3b4c9b9 100644 (file)
@@ -44,16 +44,14 @@ require_once('../config.php');
 require_once($CFG->dirroot.'/course/lib.php');
 require_once($CFG->dirroot.'/calendar/lib.php');
 
-$courseid = optional_param('course', 0, PARAM_INT);
+$courseid = optional_param('course', SITEID, PARAM_INT);
 $view = optional_param('view', 'upcoming', PARAM_ALPHA);
 $day  = optional_param('cal_d', 0, PARAM_INT);
 $mon  = optional_param('cal_m', 0, PARAM_INT);
 $yr   = optional_param('cal_y', 0, PARAM_INT);
 
-$site = get_site();
-
 $url = new moodle_url('/calendar/view.php');
-if ($courseid !== 0) {
+if ($courseid != SITEID) {
     $url->param('course', $courseid);
 }
 if ($view !== 'upcoming') {
@@ -70,34 +68,27 @@ if ($yr !== 0) {
 }
 $PAGE->set_url($url);
 
-//TODO: the courseid handling in /calendar/ is a bloody mess!!!
-
-if ($courseid && $courseid != SITEID) {
-    require_login($courseid);
-} else if ($CFG->forcelogin) {
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); //TODO: wrong
-    require_login();
+if ($courseid != SITEID && !empty($courseid)) {
+    $course = $DB->get_record('course', array('id' => $courseid));
+    $courses = array($course->id => $course);
+    $issite = false;
+    navigation_node::override_active_url(new moodle_url('/course/view.php', array('id' => $course->id)));
 } else {
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); //TODO: wrong
+    $course = get_site();
+    $courses = calendar_get_default_courses();
+    $issite = true;
 }
+require_course_login($course);
 
 $calendar = new calendar_information($day, $mon, $yr);
-$calendar->courseid = $courseid;
-
-// Initialize the session variables
-calendar_session_vars();
+$calendar->prepare_for_view($course, $courses);
 
-//add_to_log($course->id, "course", "view", "view.php?id=$course->id", "$course->id");
 $now = usergetdate(time());
 $pagetitle = '';
 
 $strcalendar = get_string('calendar', 'calendar');
 
-$link = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming', 'course'=>$courseid)),
-                               $now['mday'], $now['mon'], $now['year']);
-$PAGE->navbar->add($strcalendar, $link);
-
-if(!checkdate($mon, $day, $yr)) {
+if (!checkdate($mon, $day, $yr)) {
     $day = intval($now['mday']);
     $mon = intval($now['mon']);
     $yr = intval($now['year']);
@@ -117,47 +108,12 @@ switch($view) {
         $pagetitle = get_string('upcomingevents', 'calendar');
     break;
 }
-// If a course has been supplied in the URL, change the filters to show that one
-if (!empty($courseid)) {
-    if ($course = $DB->get_record('course', array('id'=>$courseid))) {
-        if ($course->id == SITEID) {
-            // If coming from the home page, show all courses
-            $SESSION->cal_courses_shown = calendar_get_default_courses(true);
-            calendar_set_referring_course(0);
-
-        } else {
-            // Otherwise show just this one
-            $SESSION->cal_courses_shown = $course->id;
-            calendar_set_referring_course($SESSION->cal_courses_shown);
-        }
-    }
-} else {
-    $course = null;
-}
-if (!isloggedin() or isguestuser()) {
-    $defaultcourses = calendar_get_default_courses();
-    calendar_set_filters($calendar->courses, $calendar->groups, $calendar->users, $defaultcourses, $defaultcourses);
-} else {
-    calendar_set_filters($calendar->courses, $calendar->groups, $calendar->users);
-}
-// Let's see if we are supposed to provide a referring course link
-// but NOT for the "main page" course
-if ($SESSION->cal_course_referer != SITEID &&
-   ($shortname = $DB->get_field('course', 'shortname', array('id'=>$SESSION->cal_course_referer))) !== false) {
-    require_login(); //TODO: very wrong!!
-    if (empty($course)) {
-        $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer)); // Useful to have around
-    }
-}
-
-$strcalendar = get_string('calendar', 'calendar');
-$prefsbutton = calendar_preferences_button();
 
 // Print title and header
-$PAGE->set_title("$site->shortname: $strcalendar: $pagetitle");
-$PAGE->set_heading($COURSE->fullname);
-$PAGE->set_button($prefsbutton);
 $PAGE->set_pagelayout('standard');
+$PAGE->set_title("$course->shortname: $strcalendar: $pagetitle");
+$PAGE->set_heading($COURSE->fullname);
+$PAGE->set_button(calendar_preferences_button($course));
 
 $renderer = $PAGE->get_renderer('core_calendar');
 $calendar->add_sidecalendar_blocks($renderer, true, $view);
@@ -174,7 +130,18 @@ switch($view) {
         echo $renderer->show_month_detailed($calendar);
     break;
     case 'upcoming':
-        echo $renderer->show_upcoming_events($calendar, get_user_preferences('calendar_lookahead', CALENDAR_UPCOMING_DAYS), get_user_preferences('calendar_maxevents', CALENDAR_UPCOMING_MAXEVENTS));
+        $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
+        if (isset($CFG->calendar_lookahead)) {
+            $defaultlookahead = intval($CFG->calendar_lookahead);
+        }
+        $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
+
+        $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
+        if (isset($CFG->calendar_maxevents)) {
+            $defaultmaxevents = intval($CFG->calendar_maxevents);
+        }
+        $maxevents = get_user_preferences('calendar_maxevents', $defaultmaxevents);
+        echo $renderer->show_upcoming_events($calendar, $lookahead, $maxevents);
     break;
 }
 
@@ -189,6 +156,7 @@ if (!empty($CFG->enablecalendarexport)) {
         echo html_writer::tag('a', $icon, array('href'=>$link));
     }
 }
+
 echo $OUTPUT->container_end();
 echo html_writer::end_tag('div');
 echo $renderer->complete_layout();
index da83c56..2f32d8a 100644 (file)
@@ -2935,7 +2935,6 @@ class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
      */
     public function write_setting($data) {
         global $SESSION;
-        unset($SESSION->cal_courses_shown);
         return parent::write_setting($data);
     }
 }
index 997d68d..1ecaedc 100644 (file)
@@ -3920,12 +3920,6 @@ function set_login_session_preferences() {
     $SESSION->justloggedin = true;
 
     unset($SESSION->lang);
-
-    // Restore the calendar filters, if saved
-    if (intval(get_user_preferences('calendar_persistflt', 0))) {
-        include_once($CFG->dirroot.'/calendar/lib.php');
-        calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
-    }
 }
 
 
index 3efae16..9691409 100644 (file)
@@ -2267,6 +2267,9 @@ class global_navigation extends navigation_node {
             $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
         }
 
+        // Calendar
+        $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
+        $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
 
         // View course reports
         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports