Removed maxmodel unuseful variable
[moodle.git] / calendar / lib.php
CommitLineData
7423f116 1<?php // $Id$
2
3/////////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Calendar extension //
8// //
9// Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10// //
11// Designed by: //
bdcb26b7 12// Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13// Jon Papaioannou (pj@moodle.org) //
7423f116 14// //
15// Programming and development: //
bdcb26b7 16// Jon Papaioannou (pj@moodle.org) //
7423f116 17// //
18// For bugs, suggestions, etc contact: //
bdcb26b7 19// Jon Papaioannou (pj@moodle.org) //
7423f116 20// //
21// The current module was developed at the University of Macedonia //
22// (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23// The aim of this project is to provide additional and improved //
24// functionality to the Asynchronous Distance Education service that the //
25// Greek School Network deploys. //
26// //
27// This program is free software; you can redistribute it and/or modify //
28// it under the terms of the GNU General Public License as published by //
29// the Free Software Foundation; either version 2 of the License, or //
30// (at your option) any later version. //
31// //
32// This program is distributed in the hope that it will be useful, //
33// but WITHOUT ANY WARRANTY; without even the implied warranty of //
34// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35// GNU General Public License for more details: //
36// //
37// http://www.gnu.org/copyleft/gpl.html //
38// //
39/////////////////////////////////////////////////////////////////////////////
40
bb4a2e85 41// These are read by the administration component to provide default values
42define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
45// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
46// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
47define('CALENDAR_DEFAULT_WEEKEND', 65);
48
49// Fetch the correct values from admin settings/lang pack
50// If no such settings found, use the above defaults
51$firstday = isset($CFG->calendar_startwday) ? $CFG->calendar_startwday : get_string('firstdayofweek');
52if(!is_numeric($firstday)) {
53 define ('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
ed151929 54}
55else {
56 define ('CALENDAR_STARTING_WEEKDAY', intval($firstday) % 7);
57}
bb4a2e85 58define ('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
59define ('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
60define ('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
7423f116 61define ('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
1b0ebe79 62define ('CALENDAR_TF_24', '%H:%M');
63define ('CALENDAR_TF_12', '%I:%M %p');
7423f116 64
f2bffd9e 65$CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
66
37d87d11 67
bd119567 68
7423f116 69function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
70 global $CFG, $USER;
71
4e17c6f3 72 $display = &New stdClass;
7423f116 73 $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
74 $display->maxwday = $display->minwday + 6;
75
76 $content = '';
77
78 if(!empty($cal_month) && !empty($cal_year)) {
79 $thisdate = usergetdate(time()); // Date and time the user sees at his location
80 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
81 // Navigated to this month
82 $date = $thisdate;
83 $display->thismonth = true;
84 }
85 else {
86 // Navigated to other month, let's do a nice trick and save us a lot of work...
87 if(!checkdate($cal_month, 1, $cal_year)) {
88 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
89 $display->thismonth = true;
90 }
91 else {
92 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
93 $display->thismonth = false;
94 }
95 }
96 }
97 else {
98 $date = usergetdate(time()); // Date and time the user sees at his location
99 $display->thismonth = true;
100 }
101
102 // Fill in the variables we 're going to use, nice and tidy
103 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
104 $display->maxdays = calendar_days_in_month($m, $y);
105
d6198903 106 if (get_user_timezone_offset() < 99) {
107 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
61240489 108 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
109 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
d6198903 110 } else {
111 // no timezone info specified
61240489 112 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
113 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
d6198903 114 }
7423f116 115
69244b91 116 $startwday = dayofweek(1, $m, $y);
7423f116 117
118 // Align the starting weekday to fall in our display range
119 // This is simple, not foolproof.
120 if($startwday < $display->minwday) {
121 $startwday += 7;
122 }
123
c0b507d1 124 // TODO: THIS IS TEMPORARY CODE!
125 // [pj] I was just reading through this and realized that I when writing this code I was probably
126 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
127 // make_timestamp would accomplish the same thing. So here goes a test:
1747ee05 128 //$test_start = make_timestamp($y, $m, 1);
129 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
130 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
131 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
132 //}
133 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
134 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
135 //}
c0b507d1 136
137
7423f116 138 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
d3555a2f 139 $whereclause = calendar_sql_where(
140 usertime($display->tstart) - dst_offset_on($display->tstart),
141 usertime($display->tend) - dst_offset_on($display->tend),
142 $users, $groups, $courses);
7423f116 143
144 if($whereclause === false) {
145 $events = array();
146 }
147 else {
a94329a8 148 $events = get_records_select('event', $whereclause, 'timestart');
7423f116 149 }
150
c635dcda 151 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 152 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 153 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
154 // arguments to this function.
155
7bd1677c 156 $morehref = '';
157 if(!empty($courses)) {
e749554e 158 $courses = array_diff($courses, array(SITEID));
7bd1677c 159 if(count($courses) == 1) {
160 $morehref = '&amp;course='.reset($courses);
161 }
c635dcda 162 }
163
7423f116 164 // We want to have easy access by day, since the display is on a per-day basis.
165 // Arguments passed by reference.
7b38bfa6 166 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
167 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday);
7423f116 168
f20c4d02 169 //Accessibility: added summary and <abbr> elements.
170 ///global $CALENDARDAYS; appears to be broken.
171 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
172
2a06efcc 173 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
174 $summary = get_string('tabledata', 'access', $summary);
175 $content .= '<table class="minicalendar" summary="'.$summary.'">'; // Begin table
f136e4c5 176 $content .= '<tr class="weekdays">'; // Header row: day names
7423f116 177
178 // Print out the names of the weekdays
179 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
180 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
181 // This uses the % operator to get the correct weekday no matter what shift we have
182 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
f20c4d02 183 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
184 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
7423f116 185 }
186
f136e4c5 187 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
7423f116 188
189 // For the table display. $week is the row; $dayweek is the column.
7423f116 190 $dayweek = $startwday;
191
192 // Paddding (the first week may have blank days in the beginning)
193 for($i = $display->minwday; $i < $startwday; ++$i) {
92668ad2 194 $content .= '<td>&nbsp;</td>'."\n";
7423f116 195 }
196
197 // Now display all the calendar
198 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
199 if($dayweek > $display->maxwday) {
200 // We need to change week (table row)
d56d4e23 201 $content .= '</tr><tr>';
7423f116 202 $dayweek = $display->minwday;
7423f116 203 }
92668ad2 204
7423f116 205 // Reset vars
7423f116 206 $cell = '';
bb4a2e85 207 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
7423f116 208 // Weekend. This is true no matter what the exact range is.
e2aa618b 209 $class = 'weekend day';
7423f116 210 }
211 else {
212 // Normal working day.
e2aa618b 213 $class = 'day';
7423f116 214 }
215
216 // Special visual fx if an event is defined
217 if(isset($eventsbyday[$day])) {
c635dcda 218 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
f434283f 219
7423f116 220 // OverLib popup
221 $popupcontent = '';
222 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 223 if (!isset($events[$eventid])) {
224 continue;
4e17c6f3 225 }
41d30a8e 226 $event = $events[$eventid];
41d30a8e 227 if(!empty($event->modulename)) {
228 $popupicon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
229 $popupalt = $event->modulename;
230
9064751b 231 } else if ($event->courseid == SITEID) { // Site event
41d30a8e 232 $popupicon = $CFG->pixpath.'/c/site.gif';
233 $popupalt = '';
c3d3b6d4 234 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
41d30a8e 235 $popupicon = $CFG->pixpath.'/c/course.gif';
c9b05b32 236 $popupalt = '';
41d30a8e 237 } else if ($event->groupid) { // Group event
238 $popupicon = $CFG->pixpath.'/c/group.gif';
239 $popupalt = '';
240 } else if ($event->userid) { // User event
241 $popupicon = $CFG->pixpath.'/c/user.gif';
242 $popupalt = '';
4e17c6f3 243 }
53d8fac0 244 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
7423f116 245 }
b5c42e70 246
247 //Accessibility: functionality moved to calendar_get_popup.
248 if($display->thismonth && $day == $d) {
450a0a7d 249 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
b5c42e70 250 } else {
450a0a7d 251 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
b5c42e70 252 }
f20c4d02 253
7423f116 254 // Class and cell content
255 if(isset($typesbyday[$day]['startglobal'])) {
edbe6c1b 256 $class .= ' event_global';
7423f116 257 }
258 else if(isset($typesbyday[$day]['startcourse'])) {
edbe6c1b 259 $class .= ' event_course';
7423f116 260 }
261 else if(isset($typesbyday[$day]['startgroup'])) {
edbe6c1b 262 $class .= ' event_group';
7423f116 263 }
264 else if(isset($typesbyday[$day]['startuser'])) {
edbe6c1b 265 $class .= ' event_user';
7423f116 266 }
05fcc5fd 267 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
7423f116 268 }
269 else {
05fcc5fd 270 $cell = $day;
7423f116 271 }
272
273 if(isset($typesbyday[$day]['durationglobal'])) {
edbe6c1b 274 $class .= ' duration_global';
7423f116 275 }
276 else if(isset($typesbyday[$day]['durationcourse'])) {
edbe6c1b 277 $class .= ' duration_course';
7423f116 278 }
279 else if(isset($typesbyday[$day]['durationgroup'])) {
edbe6c1b 280 $class .= ' duration_group';
7423f116 281 }
282 else if(isset($typesbyday[$day]['durationuser'])) {
edbe6c1b 283 $class .= ' duration_user';
7423f116 284 }
285
286 // Special visual fx for today
450a0a7d 287 //Accessibility: hidden text for today, and popup.
7423f116 288 if($display->thismonth && $day == $d) {
edbe6c1b 289 $class .= ' today';
b5c42e70 290 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
291
292 if(! isset($eventsbyday[$day])) {
450a0a7d 293 $class .= ' eventnone';
294 $popup = calendar_get_popup(true, false);
295 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
b5c42e70 296 }
297 $cell = '<span class="accesshide">'.$today.' </span>'.$cell;
7423f116 298 }
299
300 // Just display it
92668ad2 301 if(!empty($class)) {
d56d4e23 302 $class = ' class="'.$class.'"';
92668ad2 303 }
304 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 305 }
306
307 // Paddding (the last week may have blank days at the end)
308 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
92668ad2 309 $content .= '<td>&nbsp;</td>';
7423f116 310 }
311 $content .= '</tr>'; // Last row ends
312
f136e4c5 313 $content .= '</table>'; // Tabular display of days ends
7423f116 314
315 return $content;
316}
317
b5c42e70 318/**
319 * calendar_get_popup, called at multiple points in from calendar_get_mini.
320 * Copied and modified from calendar_get_mini.
321 * @uses OverLib popup.
322 * @param $is_today bool, false except when called on the current day.
323 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
324 * @param $popupcontent string.
325 * @return $popup string, contains onmousover and onmouseout events.
326 */
327function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
328 $popupcaption = '';
329 if($is_today) {
330 $popupcaption = get_string('today', 'calendar').' ';
331 }
332 if (false === $event_timestart) {
333 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
334 $popupcontent = get_string('eventnone', 'calendar');
450a0a7d 335
b5c42e70 336 } else {
337 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
338 }
339 $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
d8947f95 340 $popupcaption = str_replace("'", "\'", htmlspecialchars($popupcaption));
b5c42e70 341 $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
450a0a7d 342 return $popup;
b5c42e70 343}
344
9958a08c 345function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
7423f116 346 global $CFG;
347
1f473774 348 $display = &new stdClass;
7423f116 349 $display->range = $daysinfuture; // How many days in the future we 'll look
350 $display->maxevents = $maxevents;
351
352 $output = array();
353
354 // Prepare "course caching", since it may save us a lot of queries
355 $coursecache = array();
356
357 $processed = 0;
358 $now = time(); // We 'll need this later
9d567178 359 $usermidnighttoday = usergetmidnight($now);
7423f116 360
9958a08c 361 if ($fromtime) {
362 $display->tstart = $fromtime;
363 } else {
9d567178 364 $display->tstart = $usermidnighttoday;
9958a08c 365 }
7423f116 366
1f473774 367 // This works correctly with respect to the user's DST, but it is accurate
368 // only because $fromtime is always the exact midnight of some day!
369 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
7423f116 370
371 // Get the events matching our criteria
372 $whereclause = calendar_sql_where($display->tstart, $display->tend, $users, $groups, $courses);
9958a08c 373 if ($whereclause === false) {
7423f116 374 $events = false;
9958a08c 375 } else {
a94329a8 376 $events = get_records_select('event', $whereclause, 'timestart');
7423f116 377 }
378
c635dcda 379 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 380 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 381 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
382 // arguments to this function.
383
7bd1677c 384 $morehref = '';
385 if(!empty($courses)) {
e749554e 386 $courses = array_diff($courses, array(SITEID));
7bd1677c 387 if(count($courses) == 1) {
388 $morehref = '&amp;course='.reset($courses);
389 }
c635dcda 390 }
391
7423f116 392 if($events !== false) {
fa22fd5f 393
7423f116 394 foreach($events as $event) {
9d567178 395
396 if($processed >= $display->maxevents) {
397 break;
398 }
7423f116 399
3c134875 400 $event->time = calendar_format_event_time($event, $now, $morehref);
401 $output[] = $event;
402 ++$processed;
403 }
404 }
405 return $output;
406}
7423f116 407
9df8ff44 408function calendar_add_event_metadata($event) {
409 global $CFG;
fb73f3b3 410
411 //Support multilang in event->name
412 $event->name = format_string($event->name,true);
413
3c134875 414 if(!empty($event->modulename)) { // Activity event
415 // The module name is set. I will assume that it has to be displayed, and
416 // also that it is an automatically-generated event. And of course that the
417 // fields for get_coursemodule_from_instance are set correctly.
418 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 419
3c134875 420 if ($module === false) {
421 return;
422 }
9958a08c 423
3c134875 424 $modulename = get_string('modulename', $event->modulename);
425 $eventtype = get_string($event->eventtype, $event->modulename);
426 $icon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
9958a08c 427
10daca92 428 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
fb73f3b3 429 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
3c134875 430 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
431 $event->cmid = $module->id;
9958a08c 432
9958a08c 433
3c134875 434 } else if($event->courseid == SITEID) { // Site event
10daca92 435 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/site.gif" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
3c49918a 436 $event->cssclass = 'event_global';
3c134875 437 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
438 calendar_get_course_cached($coursecache, $event->courseid);
10daca92 439 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/course.gif" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
3c134875 440 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
3c49918a 441 $event->cssclass = 'event_course';
3c134875 442 } else if ($event->groupid) { // Group event
10daca92 443 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/group.gif" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
3c49918a 444 $event->cssclass = 'event_group';
3c134875 445 } else if($event->userid) { // User event
10daca92 446 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/user.gif" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
3c49918a 447 $event->cssclass = 'event_user';
3c134875 448 }
9df8ff44 449 return $event;
450}
451
452function calendar_print_event($event) {
453 global $CFG, $USER;
454
455 static $strftimetime;
456
457 $event = calendar_add_event_metadata($event);
53d8fac0 458 echo '<a name="event_'.$event->id.'"></a><table class="event" cellspacing="0">';
ed8ea92b 459 echo '<tr><td class="picture">';
3c134875 460 if (!empty($event->icon)) {
461 echo $event->icon;
462 } else {
463 print_spacer(16,16);
464 }
465 echo '</td>';
df349d1d 466 echo '<td class="topic">';
9958a08c 467
3c134875 468 if (!empty($event->referer)) {
e96ba29d 469 echo '<div class="referer">'.$event->referer.'</div>';
3c134875 470 } else {
ed8ea92b 471 echo '<div class="name">'.$event->name."</div>";
3c134875 472 }
473 if (!empty($event->courselink)) {
ed8ea92b 474 echo '<div class="course">'.$event->courselink.' </div>';
3c134875 475 }
476 if (!empty($event->time)) {
ed8ea92b 477 echo '<span class="date">'.$event->time.'</span>';
3c134875 478 } else {
ed8ea92b 479 echo '<span class="date">'.calendar_time_representation($event->timestart).'</span>';
3c134875 480 }
9958a08c 481
ed8ea92b 482 echo '</td></tr>';
483 echo '<tr><td class="side">&nbsp;</td>';
3c49918a 484 echo '<td class="description '.$event->cssclass.'">';
3c134875 485 echo format_text($event->description, FORMAT_HTML);
486 if (calendar_edit_event_allowed($event)) {
ed8ea92b 487 echo '<div class="commands">';
3c134875 488 if (empty($event->cmid)) {
489 $editlink = CALENDAR_URL.'event.php?action=edit&amp;id='.$event->id;
490 $deletelink = CALENDAR_URL.'event.php?action=delete&amp;id='.$event->id;
491 } else {
492 $editlink = $CFG->wwwroot.'/course/mod.php?update='.$event->cmid.'&amp;return=true&amp;sesskey='.$USER->sesskey;
493 $deletelink = $CFG->wwwroot.'/course/mod.php?delete='.$event->cmid.'&amp;sesskey='.$USER->sesskey;;
7423f116 494 }
3c134875 495 echo ' <a href="'.$editlink.'"><img
496 src="'.$CFG->pixpath.'/t/edit.gif" alt="'.get_string('tt_editevent', 'calendar').'"
497 title="'.get_string('tt_editevent', 'calendar').'" /></a>';
498 echo ' <a href="'.$deletelink.'"><img
499 src="'.$CFG->pixpath.'/t/delete.gif" alt="'.get_string('tt_deleteevent', 'calendar').'"
500 title="'.get_string('tt_deleteevent', 'calendar').'" /></a>';
501 echo '</div>';
7423f116 502 }
3c134875 503 echo '</td></tr></table>';
504
7423f116 505}
506
8c165fe9 507function calendar_sql_where($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
7423f116 508 $whereclause = '';
509 // Quick test
510 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
511 return false;
512 }
482dbe0c 513
7423f116 514 if(is_array($users) && !empty($users)) {
515 // Events from a number of users
516 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 517 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
7423f116 518 }
519 else if(is_numeric($users)) {
520 // Events from one user
521 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 522 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
7423f116 523 }
524 else if($users === true) {
525 // Events from ALL users
526 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 527 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
7423f116 528 }
f52f7413 529 else if($users === false) {
6e957c41 530 // No user at all, do nothing
f52f7413 531 }
482dbe0c 532
7423f116 533 if(is_array($groups) && !empty($groups)) {
534 // Events from a number of groups
535 if(!empty($whereclause)) $whereclause .= ' OR';
536 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
537 }
538 else if(is_numeric($groups)) {
539 // Events from one group
540 if(!empty($whereclause)) $whereclause .= ' OR ';
541 $whereclause .= ' groupid = '.$groups;
542 }
543 else if($groups === true) {
544 // Events from ALL groups
545 if(!empty($whereclause)) $whereclause .= ' OR ';
546 $whereclause .= ' groupid != 0';
547 }
482dbe0c 548 // boolean false (no groups at all): we don't need to do anything
549
f52f7413 550 if(is_array($courses)) {
551 // A number of courses (maybe none at all!)
552 if(!empty($courses)) {
553 if(!empty($whereclause)) {
554 $whereclause .= ' OR';
555 }
6e957c41 556 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
f52f7413 557 }
558 else {
559 // This means NO courses, not that we don't care!
09d36284 560 // No need to do anything
f52f7413 561 }
7423f116 562 }
563 else if(is_numeric($courses)) {
564 // One course
565 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 566 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
7423f116 567 }
568 else if($courses === true) {
569 // Events from ALL courses
570 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 571 $whereclause .= ' (groupid = 0 AND courseid != 0)';
7423f116 572 }
8c165fe9 573
482dbe0c 574 // Security check: if, by now, we have NOTHING in $whereclause, then it means
575 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
576 // events no matter what. Allowing the code to proceed might return a completely
577 // valid query with only time constraints, thus selecting ALL events in that time frame!
578 if(empty($whereclause)) {
579 return false;
580 }
581
7423f116 582 if($withduration) {
583 $timeclause = 'timestart + timeduration >= '.$tstart.' AND timestart <= '.$tend;
584 }
585 else {
586 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
587 }
588 if(!empty($whereclause)) {
589 // We have additional constraints
590 $whereclause = $timeclause.' AND ('.$whereclause.')';
591 }
592 else {
593 // Just basic time filtering
594 $whereclause = $timeclause;
595 }
f52f7413 596
0ad072de 597 if ($ignorehidden) {
598 $whereclause .= ' AND visible = 1';
599 }
600
601 return $whereclause;
7423f116 602}
603
604function calendar_top_controls($type, $data) {
57100a90 605 global $CFG, $CALENDARDAYS, $THEME;
7423f116 606 $content = '';
607 if(!isset($data['d'])) {
608 $data['d'] = 1;
609 }
5147ad48 610
611 if(!checkdate($data['m'], $data['d'], $data['y'])) {
612 $time = time();
613 }
614 else {
615 $time = make_timestamp($data['y'], $data['m'], $data['d']);
616 }
617 $date = usergetdate($time);
618
7423f116 619 $data['m'] = $date['mon'];
620 $data['y'] = $date['year'];
7423f116 621
2a06efcc 622 //Accessibility: calendar block controls, replaced <table> with <div>.
ce3735d4 623 $nexttext = get_arrow_right().'<span class="accesshide">'.get_string('monthnext','access').'</span>';
624 $prevtext = get_arrow_left() .'<span class="accesshide">'.get_string('monthprev','access').'</span>';
2a06efcc 625
7423f116 626 switch($type) {
627 case 'frontpage':
628 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
629 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
2a06efcc 630 $nextlink = calendar_get_link_tag($nexttext, 'index.php?', 0, $nextmonth, $nextyear);
631 $prevlink = calendar_get_link_tag($prevtext, 'index.php?', 0, $prevmonth, $prevyear);
632 $content .= '<div class="calendar-controls">';
633 $content .= '<span class="previous" title="'.get_string('monthprev','access').'">'.$prevlink."</span>\n";
634 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
635 $content .= '<span class="hide"> | </span><span class="next" title="'.get_string('monthnext','access').'">'.$nextlink."</span>\n";
f2de62da 636 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 637 break;
638 case 'course':
639 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
640 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a7c385e6 641 $nextlink = calendar_get_link_tag($nexttext, 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear);
642 $prevlink = calendar_get_link_tag($prevtext, 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear);
643 $content .= '<div class="calendar-controls">';
644 $content .= '<span class="previous" title="'.get_string('monthprev','access').'">'.$prevlink."</span>\n";
645 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;course='.$data['id'].'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
646 $content .= '<span class="hide"> | </span><span class="next" title="'.get_string('monthnext','access').'">'.$nextlink."</span>\n";
f2de62da 647 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 648 break;
649 case 'upcoming':
5147ad48 650 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
7423f116 651 break;
652 case 'display':
5147ad48 653 $content .= '<div style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
7423f116 654 break;
655 case 'month':
656 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
657 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
5147ad48 658 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
659 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
a7c385e6 660 $content .= '<div class="calendar-controls">';
57100a90 661 $content .= '<span class="previous"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $prevmonth, $prevyear)."\"> $THEME->larrow ".userdate($prevdate, get_string('strftimemonthyear')).'</a></span>';
a7c385e6 662 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimemonthyear'))."</span>\n";
ce3735d4 663 $content .= '<span class="hide"> | </span><span class="next"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $nextmonth, $nextyear).'">'.userdate($nextdate, get_string('strftimemonthyear')).' '.get_arrow_left()."</a></span>\n";
f2de62da 664 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 665 break;
666 case 'day':
667 $data['d'] = $date['mday']; // Just for convenience
5147ad48 668 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
669 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
f2bffd9e 670 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
671 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
a7c385e6 672 $content .= '<div class="calendar-controls">';
57100a90 673 $content .= '<span class="previous"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year'])."\">$THEME->larrow ".$prevname."</a></span>\n";
6e8e8ec6 674
675 // Get the format string
676 $text = get_string('strftimedaydate');
3477a900 677 /*
6e8e8ec6 678 // Regexp hackery to make a link out of the month/year part
679 $text = ereg_replace('(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
5147ad48 680 $text = ereg_replace('(F.+Y|Y.+F|Y.+m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
3477a900 681 */
6e8e8ec6 682 // Replace with actual values and lose any day leading zero
3477a900 683 $text = userdate($time, $text);
6e8e8ec6 684 // Print the actual thing
a7c385e6 685 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
6e8e8ec6 686
ce3735d4 687 $content .= '<span class="hide"> | </span><span class="next"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']).'">'.$nextname.' '.get_arrow_right()."</a></span>\n";
f2de62da 688 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 689 break;
690 }
691 return $content;
692}
693
3cb9ee39 694function calendar_filter_controls($type, $vars = NULL, $course = NULL) {
43c3ffbe 695 global $CFG, $SESSION, $USER;
7423f116 696
48f508ab 697 $groupevents = true;
3cb9ee39 698 $getvars = '';
7f4d18fc 699
700 $id = optional_param( 'id',0,PARAM_INT );
d715f7c4 701
34bf3ad4 702 switch($type) {
eb15f829 703 case 'event':
34bf3ad4 704 case 'upcoming':
34bf3ad4 705 case 'day':
c3f463ca 706 case 'month':
eb15f829 707 $getvars = '&amp;from='.$type;
34bf3ad4 708 break;
709 case 'course':
fac01360 710 if ($id > 0) {
7f4d18fc 711 $getvars = '&amp;from=course&amp;id='.$id;
2eb68e6f 712 } else {
713 $getvars = '&amp;from=course';
714 }
5a74ffd3 715 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
34bf3ad4 716 $groupevents = false;
717 }
718 break;
d715f7c4 719 }
34bf3ad4 720
3cb9ee39 721 if (!empty($vars)) {
34bf3ad4 722 $getvars .= '&amp;'.$vars;
48f508ab 723 }
7423f116 724
2ad2cbc3 725 $content = '<table>';
7423f116 726
48f508ab 727 $content .= '<tr>';
728 if($SESSION->cal_show_global) {
0d905d9f 729 $content .= '<td class="event_global" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 730 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
48f508ab 731 }
732 else {
0d905d9f 733 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 734 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
48f508ab 735 }
736 if($SESSION->cal_show_course) {
0d905d9f 737 $content .= '<td class="event_course" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 738 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
7423f116 739 }
48f508ab 740 else {
cf4a39ec 741 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 742 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
48f508ab 743 }
48f508ab 744
1066e0dc 745 if(!empty($USER->id) && !isguest()) {
43c3ffbe 746 $content .= "</tr>\n<tr>";
747
748 if($groupevents) {
749 // This course MIGHT have group events defined, so show the filter
750 if($SESSION->cal_show_groups) {
0d905d9f 751 $content .= '<td class="event_group" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 752 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
cd6469cb 753 } else {
0d905d9f 754 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 755 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
43c3ffbe 756 }
cd6469cb 757 if ($SESSION->cal_show_user) {
0d905d9f 758 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 759 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
cd6469cb 760 } else {
0d905d9f 761 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 762 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
43c3ffbe 763 }
cd6469cb 764
765 } else {
43c3ffbe 766 // This course CANNOT have group events, so lose the filter
5c53988f 767 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
cd6469cb 768
43c3ffbe 769 if($SESSION->cal_show_user) {
0d905d9f 770 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 771 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
cd6469cb 772 } else {
0d905d9f 773 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 774 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
43c3ffbe 775 }
48f508ab 776 }
777 }
778 $content .= "</tr>\n</table>\n";
779
7423f116 780 return $content;
781}
782
783function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
784
0ef7c973 785 static $shortformat;
786 if(empty($shortformat)) {
e70fdac0 787 $shortformat = get_string('strftimedayshort');
0ef7c973 788 }
789
7423f116 790 if($now === false) {
791 $now = time();
792 }
793
794 // To have it in one place, if a change is needed
e70fdac0 795 $formal = userdate($tstamp, $shortformat);
7423f116 796
7b38bfa6 797 $datestamp = usergetdate($tstamp);
798 $datenow = usergetdate($now);
7423f116 799
800 if($usecommonwords == false) {
801 // We don't want words, just a date
802 return $formal;
803 }
7b38bfa6 804 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 805 // Today
806 return get_string('today', 'calendar');
807 }
7b38bfa6 808 else if(
809 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
810 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
811 ) {
7423f116 812 // Yesterday
813 return get_string('yesterday', 'calendar');
814 }
7b38bfa6 815 else if(
816 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
817 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
818 ) {
7423f116 819 // Tomorrow
820 return get_string('tomorrow', 'calendar');
821 }
822 else {
823 return $formal;
824 }
825}
826
827function calendar_time_representation($time) {
1b0ebe79 828 static $langtimeformat = NULL;
829 if($langtimeformat === NULL) {
830 $langtimeformat = get_string('strftimetime');
831 }
832 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 833 if(empty($timeformat)){
834 $timeformat = get_config(NULL,'calendar_site_timeformat');
835 }
1b0ebe79 836 // The ? is needed because the preference might be present, but empty
837 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 838}
839
840function calendar_get_link_href($linkbase, $d, $m, $y) {
841 if(empty($linkbase)) return '';
842 $paramstr = '';
843 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
844 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
845 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
846 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
847 return $linkbase.$paramstr;
848}
849
850function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
851 $href = calendar_get_link_href($linkbase, $d, $m, $y);
852 if(empty($href)) return $text;
853 return '<a href="'.$href.'">'.$text.'</a>';
854}
855
7423f116 856function calendar_wday_name($englishname) {
857 return get_string(strtolower($englishname), 'calendar');
858}
859
860function calendar_days_in_month($month, $year) {
7b38bfa6 861 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 862}
863
e749554e 864function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
7423f116 865 $content = '';
866 $lines = count($events);
396b61f0 867 if (!$lines) {
868 return $content;
869 }
7423f116 870
396b61f0 871 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 872 if (!isset($events[$i]->time)) { // Just for robustness
873 continue;
874 }
9df8ff44 875 $events[$i] = calendar_add_event_metadata($events[$i]);
ea21c1f4 876 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
43c3ffbe 877 if (!empty($events[$i]->referer)) {
7423f116 878 // That's an activity event, so let's provide the hyperlink
396b61f0 879 $content .= $events[$i]->referer;
880 } else {
e749554e 881 if(!empty($linkhref)) {
882 $ed = usergetdate($events[$i]->timestart);
883 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
53d8fac0 884 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
e749554e 885 }
886 else {
887 $content .= $events[$i]->name;
888 }
7423f116 889 }
9ecf051d 890 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
891 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 892 if ($i < $lines - 1) $content .= '<hr />';
7423f116 893 }
894
895 return $content;
7423f116 896}
897
898function calendar_add_month($month, $year) {
899 if($month == 12) {
900 return array(1, $year + 1);
901 }
902 else {
903 return array($month + 1, $year);
904 }
905}
906
907function calendar_sub_month($month, $year) {
908 if($month == 1) {
909 return array(12, $year - 1);
910 }
911 else {
912 return array($month - 1, $year);
913 }
914}
915
7b38bfa6 916function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday) {
7423f116 917 $eventsbyday = array();
918 $typesbyday = array();
919 $durationbyday = array();
920
921 if($events === false) {
922 return;
923 }
924
7423f116 925 foreach($events as $event) {
7423f116 926
7b38bfa6 927 $startdate = usergetdate($event->timestart);
928 $enddate = usergetdate($event->timestart + $event->timeduration);
7423f116 929
7b38bfa6 930 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 931 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 932 // Out of bounds
933 continue;
7423f116 934 }
935
7b38bfa6 936 $eventdaystart = intval($startdate['mday']);
7423f116 937
7b38bfa6 938 if($startdate['mon'] == $month && $startdate['year'] == $year) {
939 // Give the event to its day
940 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 941
7b38bfa6 942 // Mark the day as having such an event
9064751b 943 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 944 $typesbyday[$eventdaystart]['startglobal'] = true;
945 }
c3d3b6d4 946 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 947 $typesbyday[$eventdaystart]['startcourse'] = true;
948 }
949 else if($event->groupid) {
950 $typesbyday[$eventdaystart]['startgroup'] = true;
951 }
952 else if($event->userid) {
953 $typesbyday[$eventdaystart]['startuser'] = true;
954 }
955 }
7423f116 956
7b38bfa6 957 if($event->timeduration == 0) {
958 // Proceed with the next
959 continue;
960 }
7423f116 961
7b38bfa6 962 // The event starts on $month $year or before. So...
ef618501 963 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 964
965 // Also, it ends on $month $year or later...
966 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
967
968 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
969 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
970 $durationbyday[$i][] = $event->id;
9064751b 971 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 972 $typesbyday[$i]['durationglobal'] = true;
973 }
c3d3b6d4 974 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 975 $typesbyday[$i]['durationcourse'] = true;
976 }
977 else if($event->groupid) {
978 $typesbyday[$i]['durationgroup'] = true;
979 }
980 else if($event->userid) {
981 $typesbyday[$i]['durationuser'] = true;
7423f116 982 }
983 }
7b38bfa6 984
7423f116 985 }
986 return;
987}
988
b63c0ee5 989function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
990 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 991
992 if($module === false) return false;
b63c0ee5 993 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 994 return false;
995 }
996 return $module;
997}
998
999function calendar_get_course_cached(&$coursecache, $courseid) {
1000 if(!isset($coursecache[$courseid])) {
1001 $coursecache[$courseid] = get_record('course', 'id', $courseid);
1002 }
1003 return $coursecache[$courseid];
1004}
1005
1006function calendar_session_vars() {
1007 global $SESSION, $USER;
1008
1066e0dc 1009 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
02ce3848 1010 // We just logged in as someone else, update the filtering
1011 unset($SESSION->cal_users_shown);
1012 unset($SESSION->cal_courses_shown);
1013 $SESSION->cal_loggedinas = true;
054193be 1014 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1015 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1016 }
02ce3848 1017 }
1066e0dc 1018 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
02ce3848 1019 // We just logged back to our real self, update again
1020 unset($SESSION->cal_users_shown);
1021 unset($SESSION->cal_courses_shown);
1022 unset($SESSION->cal_loggedinas);
054193be 1023 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1024 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1025 }
02ce3848 1026 }
1027
7423f116 1028 if(!isset($SESSION->cal_course_referer)) {
1029 $SESSION->cal_course_referer = 0;
1030 }
1031 if(!isset($SESSION->cal_show_global)) {
1032 $SESSION->cal_show_global = true;
1033 }
1034 if(!isset($SESSION->cal_show_groups)) {
1035 $SESSION->cal_show_groups = true;
1036 }
1037 if(!isset($SESSION->cal_show_course)) {
1038 $SESSION->cal_show_course = true;
1039 }
1040 if(!isset($SESSION->cal_show_user)) {
89adb174 1041 $SESSION->cal_show_user = true;
7423f116 1042 }
6b4aeb31 1043 // if(empty($SESSION->cal_courses_shown)) {
43c3ffbe 1044 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
6b4aeb31 1045 //}
89adb174 1046 if(empty($SESSION->cal_users_shown)) {
1047 // The empty() instead of !isset() here makes a whole world of difference,
1048 // as it will automatically change to the user's id when the user first logs
1049 // in. With !isset(), it would never do that.
86a1ba04 1050 $SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false;
89adb174 1051 }
1052 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
1053 // Follow the white rabbit, for example if a teacher logs in as a student
1054 $SESSION->cal_users_shown = $USER->id;
1055 }
7423f116 1056}
1057
1058function calendar_overlib_html() {
9c6bf80e 1059 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
1060 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
7423f116 1061}
1062
7423f116 1063function calendar_set_referring_course($courseid) {
1064 global $SESSION;
1065 $SESSION->cal_course_referer = intval($courseid);
1066}
1067
43c3ffbe 1068function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
257e3f4c 1069 global $SESSION, $USER, $CFG;
1070
43c3ffbe 1071 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
51f8a12f 1072 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1073 // PHP's loose type system works against us.
43c3ffbe 1074 if(is_string($SESSION->cal_courses_shown)) {
1075 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
51f8a12f 1076 }
1077
43c3ffbe 1078 if($courseeventsfrom === NULL) {
1079 $courseeventsfrom = $SESSION->cal_courses_shown;
7423f116 1080 }
43c3ffbe 1081 if($groupeventsfrom === NULL) {
1082 $groupeventsfrom = $SESSION->cal_courses_shown;
7423f116 1083 }
1084
43c3ffbe 1085 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1086 if(is_int($courseeventsfrom)) {
9064751b 1087 $courses = array(SITEID, $courseeventsfrom);
7423f116 1088 }
43c3ffbe 1089 else if(is_array($courseeventsfrom)) {
1090 $courses = array_keys($courseeventsfrom);
9064751b 1091 $courses[] = SITEID;
7423f116 1092 }
1093 }
43c3ffbe 1094 else if($SESSION->cal_show_course) {
1095 if(is_int($courseeventsfrom)) {
1096 $courses = array($courseeventsfrom);
7423f116 1097 }
43c3ffbe 1098 else if(is_array($courseeventsfrom)) {
1099 $courses = array_keys($courseeventsfrom);
7423f116 1100 }
e749554e 1101 $courses = array_diff($courses, array(SITEID));
7423f116 1102 }
1103 else if($SESSION->cal_show_global) {
e749554e 1104 $courses = array(SITEID);
7423f116 1105 }
1106 else {
1107 $courses = false;
1108 }
0e6a8f4b 1109 //BUG 6130 clean $courses array as SESSION has bad entries.
1110 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1384da1e 1111 if (is_array($courses)) {
1112 foreach ($courses as $index => $value) {
1113 if (empty($value)) unset($courses[$index]);
1114 }
0e6a8f4b 1115 }
7423f116 1116
43c3ffbe 1117 if($SESSION->cal_show_user || $ignorefilters) {
89adb174 1118 // This doesn't work for arrays yet (maybe someday it will)
1119 $user = $SESSION->cal_users_shown;
7423f116 1120 }
1121 else {
1122 $user = false;
1123 }
43c3ffbe 1124 if($SESSION->cal_show_groups || $ignorefilters) {
1125 if(is_int($groupeventsfrom)) {
1126 $groupcourses = array($groupeventsfrom);
7423f116 1127 }
43c3ffbe 1128 else if(is_array($groupeventsfrom)) {
1129 $groupcourses = array_keys($groupeventsfrom);
1130 }
257e3f4c 1131
9c37662f 1132 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1133 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($CFG->calendar_adminseesall)) {
257e3f4c 1134 $group = true;
1135 }
1136 else {
1137 $grouparray = array();
69762501 1138
257e3f4c 1139 // We already have the courses to examine in $courses
1140 // For each course...
37d87d11 1141
257e3f4c 1142 foreach($groupcourses as $courseid) {
69762501 1143
257e3f4c 1144 // If the user is an editing teacher in there,
cc398c72 1145 if(!empty($USER->id) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
69762501 1146 // If this course has groups, show events from all of them
b8227b88 1147 if(is_int($groupeventsfrom)) {
1148 $courserecord = get_record('course', 'id', $courseid);
1149 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1150 $groupids[] = $courseid;
1151 }
1152 }
1153 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
37d87d11 1154 $groupids[] = $courseid;
257e3f4c 1155 }
1156 }
69762501 1157
1158 // Otherwise (not editing teacher) show events from the group he is a member of
257e3f4c 1159 else if(isset($USER->groupmember[$courseid])) {
fa22fd5f 1160 //changed to 2D array
1161 foreach ($USER->groupmember[$courseid] as $groupid){
1162 $grouparray[] = $groupid;
1163 }
7423f116 1164 }
1165 }
37d87d11 1166
6b4aeb31 1167 if (!empty($groupids)) {
1168 $sql = "SELECT id, groupid
1169 FROM {$CFG->prefix}groups_courses_groups
1170 WHERE courseid IN (".implode(',', $groupids).')';
1171
1172 if ($grouprecords= get_records_sql($sql)) {
1173 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1174 }
1175 }
37d87d11 1176
257e3f4c 1177 if(empty($grouparray)) {
1178 $group = false;
1179 }
1180 else {
1181 $group = $grouparray;
6c9584d1 1182 }
7423f116 1183 }
257e3f4c 1184
7423f116 1185 }
1186 else {
1187 $group = false;
1188 }
1189}
1190
1191function calendar_edit_event_allowed($event) {
89491dbd 1192
7423f116 1193 global $USER;
1194
89491dbd 1195 // can not be using guest account
1196 if ($USER->username == "guest") {
1197 return false;
1198 }
cc398c72 1199
89491dbd 1200 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1201 // if user has manageentries at site level, return true
28ee98c5 1202 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1203 return true;
f52f7413 1204 }
c0a2c361 1205
1206 // if groupid is set, it's definitely a group event
1207 if ($event->groupid) {
3c49918a 1208 //TODO:check.
1209 if (! groups_group_exists($event->groupid)) {
69244b91 1210 return false;
89491dbd 1211 }
cc398c72 1212
89491dbd 1213 // this is ok because if you have this capability at course level, you should be able
1214 // to edit group calendar too
1215 // there is no need to check membership, because if you have this capability
1216 // you will have a role in this group context
c0a2c361 1217 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
89491dbd 1218 } else if ($event->courseid) {
c0a2c361 1219 // if groupid is not set, but course is set,
1220 // it's definiely a course event
1221 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1222 } else if ($event->userid && $event->userid == $USER->id) {
1223 // if course is not set, but userid id set, it's a user event
1224 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1225 }
7423f116 1226 return false;
1227}
1228
8c54cec6 1229function calendar_get_default_courses($ignoreref = false) {
9ff136e5 1230 global $USER, $CFG, $SESSION;
1231
8c54cec6 1232 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
4c7d1137 1233 return array($SESSION->cal_course_referer => 1);
9ff136e5 1234 }
7423f116 1235
1066e0dc 1236 if(empty($USER->id)) {
2ef75eee 1237 return array();
1238 }
1239
7423f116 1240 $courses = array();
03bb25e1 1241 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1242 if (!empty($CFG->calendar_adminseesall)) {
86f092d2 1243 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1244 return $courses;
1245 }
95a89225 1246 }
03bb25e1 1247
daaf61f4 1248 if (isset($CFG->adminseesall)) {
0a66585b 1249 $courses = get_my_courses($USER->id, 'visible DESC', null, $CFG->adminseesall);
daaf61f4 1250 }
1251 else {
0a66585b 1252 $courses = get_my_courses($USER->id, 'visible DESC', null, false);
7423f116 1253 }
37d87d11 1254
1255 return $courses;
7423f116 1256}
1257
1e1ff33b 1258function calendar_preferences_button() {
1259 global $CFG, $USER;
7423f116 1260
1261 // Guests have no preferences
f52f7413 1262 if (empty($USER->id) || isguest()) {
7423f116 1263 return '';
1264 }
1265
fa738731 1266 return "<form $CFG->frametarget method=\"get\" ".
1e1ff33b 1267 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
2aab6488 1268 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
7423f116 1269}
1270
8f896582 1271function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1272 $startdate = usergetdate($event->timestart);
1273 $enddate = usergetdate($event->timestart + $event->timeduration);
1274 $usermidnightstart = usergetmidnight($event->timestart);
1275
1276 if($event->timeduration) {
1277 // To avoid doing the math if one IF is enough :)
1278 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1279 }
1280 else {
1281 $usermidnightend = $usermidnightstart;
1282 }
1283
1284 // OK, now to get a meaningful display...
1285 // First of all we have to construct a human-readable date/time representation
1286
1287 if($event->timestart + $event->timeduration < $now) {
1288 // It has expired, so we don't care about duration
1289 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1290 $time = calendar_time_representation($event->timestart + $event->timeduration);
1291
1292 // This var always has the printable time representation
1293 $eventtime = '<span class="dimmed_text"><a class="dimmed" href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).'">'.$day.'</a> ('.$time.')</span>';
1294
1295 }
1296 else if($event->timeduration) {
1297 // It has a duration
1298 if($usermidnightstart == $usermidnightend) {
1299 // But it's all on the same day
1300 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1301 $timestart = calendar_time_representation($event->timestart);
1302 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1303
1304 // Set printable representation
1305 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
7d50b363 1306 ' ('.$timestart.' <strong>&raquo;</strong> '.$timeend.')';
8f896582 1307 }
1308 else {
1309 // It spans two or more days
1310 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1311 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1312 $timestart = calendar_time_representation($event->timestart);
1313 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1314
1315 // Set printable representation
1316 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
7d50b363 1317 ' ('.$timestart.') <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
8f896582 1318 ' ('.$timeend.')';
1319 }
1320 }
1321 else {
1322 // It's an "instantaneous" event
1323 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1324 $time = calendar_time_representation($event->timestart);
1325
1326 // Set printable representation
1327 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1328 }
09d36284 1329
8f896582 1330 return $eventtime;
1331}
054193be 1332
86f092d2 1333function calendar_print_month_selector($name, $selected) {
1334
1335 $months = array();
1336
1337 for ($i=1; $i<=12; $i++) {
76ab1c33 1338 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1339 }
1340
1341 choose_from_menu($months, $name, $selected, '');
1342}
1343
054193be 1344function calendar_get_filters_status() {
1345 global $SESSION;
1346
1347 $status = 0;
1348 if($SESSION->cal_show_global) {
1349 $status += 1;
1350 }
1351 if($SESSION->cal_show_course) {
1352 $status += 2;
1353 }
1354 if($SESSION->cal_show_groups) {
1355 $status += 4;
1356 }
1357 if($SESSION->cal_show_user) {
1358 $status += 8;
1359 }
1360 return $status;
1361}
1362
1363function calendar_set_filters_status($packed_bitfield) {
1364 global $SESSION, $USER;
1365
1366 if(!isset($USER) || empty($USER->id)) {
1367 return false;
1368 }
1369
1370 $SESSION->cal_show_global = ($packed_bitfield & 1);
1371 $SESSION->cal_show_course = ($packed_bitfield & 2);
1372 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1373 $SESSION->cal_show_user = ($packed_bitfield & 8);
1374
1375 return true;
1376}
1377
d0a32914 1378?>