set correctly default value for tolerencetype for answers merge from 1.8
[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>.
a84dea2c 623 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
624 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
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']);
a84dea2c 630 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
631 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
632 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
2a06efcc 633 $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>';
a84dea2c 634 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
f2de62da 635 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 636 break;
637 case 'course':
638 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
639 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 640 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
641 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
642 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
a7c385e6 643 $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>';
a84dea2c 644 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
f2de62da 645 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 646 break;
647 case 'upcoming':
5147ad48 648 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
7423f116 649 break;
650 case 'display':
5147ad48 651 $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 652 break;
653 case 'month':
654 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
655 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
5147ad48 656 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
657 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
a84dea2c 658 $content .= "\n".'<div class="calendar-controls">';
659 $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month&amp;', 1, $prevmonth, $prevyear);
a7c385e6 660 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimemonthyear'))."</span>\n";
a84dea2c 661 $content .= '<span class="hide"> | </span>'.calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month&amp;', 1, $nextmonth, $nextyear);
f2de62da 662 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 663 break;
664 case 'day':
665 $data['d'] = $date['mday']; // Just for convenience
5147ad48 666 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
667 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
f2bffd9e 668 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
669 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
a84dea2c 670 $content .= "\n".'<div class="calendar-controls">';
671 $content .= calendar_get_link_previous($prevname, 'view.php?view=day&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
672
6e8e8ec6 673 // Get the format string
674 $text = get_string('strftimedaydate');
3477a900 675 /*
6e8e8ec6 676 // Regexp hackery to make a link out of the month/year part
677 $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 678 $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 679 */
6e8e8ec6 680 // Replace with actual values and lose any day leading zero
3477a900 681 $text = userdate($time, $text);
6e8e8ec6 682 // Print the actual thing
a7c385e6 683 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
6e8e8ec6 684
a84dea2c 685 $content .= '<span class="hide"> | </span>'. calendar_get_link_next($nextname, 'view.php?view=day&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
f2de62da 686 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 687 break;
688 }
689 return $content;
690}
691
3cb9ee39 692function calendar_filter_controls($type, $vars = NULL, $course = NULL) {
43c3ffbe 693 global $CFG, $SESSION, $USER;
7423f116 694
48f508ab 695 $groupevents = true;
3cb9ee39 696 $getvars = '';
7f4d18fc 697
698 $id = optional_param( 'id',0,PARAM_INT );
d715f7c4 699
34bf3ad4 700 switch($type) {
eb15f829 701 case 'event':
34bf3ad4 702 case 'upcoming':
34bf3ad4 703 case 'day':
c3f463ca 704 case 'month':
eb15f829 705 $getvars = '&amp;from='.$type;
34bf3ad4 706 break;
707 case 'course':
fac01360 708 if ($id > 0) {
7f4d18fc 709 $getvars = '&amp;from=course&amp;id='.$id;
2eb68e6f 710 } else {
711 $getvars = '&amp;from=course';
712 }
5a74ffd3 713 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
34bf3ad4 714 $groupevents = false;
715 }
716 break;
d715f7c4 717 }
34bf3ad4 718
3cb9ee39 719 if (!empty($vars)) {
34bf3ad4 720 $getvars .= '&amp;'.$vars;
48f508ab 721 }
7423f116 722
2ad2cbc3 723 $content = '<table>';
7423f116 724
48f508ab 725 $content .= '<tr>';
726 if($SESSION->cal_show_global) {
0d905d9f 727 $content .= '<td class="event_global" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 728 $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 729 }
730 else {
0d905d9f 731 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 732 $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 733 }
734 if($SESSION->cal_show_course) {
0d905d9f 735 $content .= '<td class="event_course" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 736 $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 737 }
48f508ab 738 else {
cf4a39ec 739 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 740 $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 741 }
48f508ab 742
1066e0dc 743 if(!empty($USER->id) && !isguest()) {
43c3ffbe 744 $content .= "</tr>\n<tr>";
745
746 if($groupevents) {
747 // This course MIGHT have group events defined, so show the filter
748 if($SESSION->cal_show_groups) {
0d905d9f 749 $content .= '<td class="event_group" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 750 $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 751 } else {
0d905d9f 752 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 753 $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 754 }
cd6469cb 755 if ($SESSION->cal_show_user) {
0d905d9f 756 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 757 $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 758 } else {
0d905d9f 759 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 760 $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 761 }
cd6469cb 762
763 } else {
43c3ffbe 764 // This course CANNOT have group events, so lose the filter
5c53988f 765 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
cd6469cb 766
43c3ffbe 767 if($SESSION->cal_show_user) {
0d905d9f 768 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
5c53988f 769 $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 770 } else {
0d905d9f 771 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
5c53988f 772 $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 773 }
48f508ab 774 }
775 }
776 $content .= "</tr>\n</table>\n";
777
7423f116 778 return $content;
779}
780
781function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
782
0ef7c973 783 static $shortformat;
784 if(empty($shortformat)) {
e70fdac0 785 $shortformat = get_string('strftimedayshort');
0ef7c973 786 }
787
7423f116 788 if($now === false) {
789 $now = time();
790 }
791
792 // To have it in one place, if a change is needed
e70fdac0 793 $formal = userdate($tstamp, $shortformat);
7423f116 794
7b38bfa6 795 $datestamp = usergetdate($tstamp);
796 $datenow = usergetdate($now);
7423f116 797
798 if($usecommonwords == false) {
799 // We don't want words, just a date
800 return $formal;
801 }
7b38bfa6 802 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 803 // Today
804 return get_string('today', 'calendar');
805 }
7b38bfa6 806 else if(
807 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
808 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
809 ) {
7423f116 810 // Yesterday
811 return get_string('yesterday', 'calendar');
812 }
7b38bfa6 813 else if(
814 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
815 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
816 ) {
7423f116 817 // Tomorrow
818 return get_string('tomorrow', 'calendar');
819 }
820 else {
821 return $formal;
822 }
823}
824
825function calendar_time_representation($time) {
1b0ebe79 826 static $langtimeformat = NULL;
827 if($langtimeformat === NULL) {
828 $langtimeformat = get_string('strftimetime');
829 }
830 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 831 if(empty($timeformat)){
832 $timeformat = get_config(NULL,'calendar_site_timeformat');
833 }
1b0ebe79 834 // The ? is needed because the preference might be present, but empty
835 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 836}
837
838function calendar_get_link_href($linkbase, $d, $m, $y) {
839 if(empty($linkbase)) return '';
840 $paramstr = '';
841 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
842 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
843 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
844 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
845 return $linkbase.$paramstr;
846}
847
848function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
849 $href = calendar_get_link_href($linkbase, $d, $m, $y);
850 if(empty($href)) return $text;
851 return '<a href="'.$href.'">'.$text.'</a>';
852}
853
a84dea2c 854/**
855 * Build and return a previous month HTML link, with an arrow.
856 * @param string $text The text label.
857 * @param string $linkbase The URL stub.
858 * @param int $d $m $y Day of month, month and year numbers.
859 * @param bool $accesshide Default visible, or hide from all except screenreaders.
860 * @return string HTML string.
861 */
862function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
863 $href = calendar_get_link_href($linkbase, $d, $m, $y);
864 if(empty($href)) return $text;
865 return link_arrow_left($text, $href, $accesshide, 'previous');
866}
867
868/**
869 * Build and return a next month HTML link, with an arrow.
870 * @param string $text The text label.
871 * @param string $linkbase The URL stub.
872 * @param int $d $m $y Day of month, month and year numbers.
873 * @param bool $accesshide Default visible, or hide from all except screenreaders.
874 * @return string HTML string.
875 */
876function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
877 $href = calendar_get_link_href($linkbase, $d, $m, $y);
878 if(empty($href)) return $text;
879 return link_arrow_right($text, $href, $accesshide, 'next');
880}
881
7423f116 882function calendar_wday_name($englishname) {
883 return get_string(strtolower($englishname), 'calendar');
884}
885
886function calendar_days_in_month($month, $year) {
7b38bfa6 887 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 888}
889
e749554e 890function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
7423f116 891 $content = '';
892 $lines = count($events);
396b61f0 893 if (!$lines) {
894 return $content;
895 }
7423f116 896
396b61f0 897 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 898 if (!isset($events[$i]->time)) { // Just for robustness
899 continue;
900 }
9df8ff44 901 $events[$i] = calendar_add_event_metadata($events[$i]);
ea21c1f4 902 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
43c3ffbe 903 if (!empty($events[$i]->referer)) {
7423f116 904 // That's an activity event, so let's provide the hyperlink
396b61f0 905 $content .= $events[$i]->referer;
906 } else {
e749554e 907 if(!empty($linkhref)) {
908 $ed = usergetdate($events[$i]->timestart);
909 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
53d8fac0 910 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
e749554e 911 }
912 else {
913 $content .= $events[$i]->name;
914 }
7423f116 915 }
9ecf051d 916 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
917 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 918 if ($i < $lines - 1) $content .= '<hr />';
7423f116 919 }
920
921 return $content;
7423f116 922}
923
924function calendar_add_month($month, $year) {
925 if($month == 12) {
926 return array(1, $year + 1);
927 }
928 else {
929 return array($month + 1, $year);
930 }
931}
932
933function calendar_sub_month($month, $year) {
934 if($month == 1) {
935 return array(12, $year - 1);
936 }
937 else {
938 return array($month - 1, $year);
939 }
940}
941
7b38bfa6 942function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday) {
7423f116 943 $eventsbyday = array();
944 $typesbyday = array();
945 $durationbyday = array();
946
947 if($events === false) {
948 return;
949 }
950
7423f116 951 foreach($events as $event) {
7423f116 952
7b38bfa6 953 $startdate = usergetdate($event->timestart);
954 $enddate = usergetdate($event->timestart + $event->timeduration);
7423f116 955
7b38bfa6 956 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 957 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 958 // Out of bounds
959 continue;
7423f116 960 }
961
7b38bfa6 962 $eventdaystart = intval($startdate['mday']);
7423f116 963
7b38bfa6 964 if($startdate['mon'] == $month && $startdate['year'] == $year) {
965 // Give the event to its day
966 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 967
7b38bfa6 968 // Mark the day as having such an event
9064751b 969 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 970 $typesbyday[$eventdaystart]['startglobal'] = true;
971 }
c3d3b6d4 972 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 973 $typesbyday[$eventdaystart]['startcourse'] = true;
974 }
975 else if($event->groupid) {
976 $typesbyday[$eventdaystart]['startgroup'] = true;
977 }
978 else if($event->userid) {
979 $typesbyday[$eventdaystart]['startuser'] = true;
980 }
981 }
7423f116 982
7b38bfa6 983 if($event->timeduration == 0) {
984 // Proceed with the next
985 continue;
986 }
7423f116 987
7b38bfa6 988 // The event starts on $month $year or before. So...
ef618501 989 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 990
991 // Also, it ends on $month $year or later...
992 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
993
994 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
995 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
996 $durationbyday[$i][] = $event->id;
9064751b 997 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 998 $typesbyday[$i]['durationglobal'] = true;
999 }
c3d3b6d4 1000 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1001 $typesbyday[$i]['durationcourse'] = true;
1002 }
1003 else if($event->groupid) {
1004 $typesbyday[$i]['durationgroup'] = true;
1005 }
1006 else if($event->userid) {
1007 $typesbyday[$i]['durationuser'] = true;
7423f116 1008 }
1009 }
7b38bfa6 1010
7423f116 1011 }
1012 return;
1013}
1014
b63c0ee5 1015function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1016 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 1017
1018 if($module === false) return false;
b63c0ee5 1019 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 1020 return false;
1021 }
1022 return $module;
1023}
1024
1025function calendar_get_course_cached(&$coursecache, $courseid) {
1026 if(!isset($coursecache[$courseid])) {
1027 $coursecache[$courseid] = get_record('course', 'id', $courseid);
1028 }
1029 return $coursecache[$courseid];
1030}
1031
1032function calendar_session_vars() {
1033 global $SESSION, $USER;
1034
1066e0dc 1035 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
02ce3848 1036 // We just logged in as someone else, update the filtering
1037 unset($SESSION->cal_users_shown);
1038 unset($SESSION->cal_courses_shown);
1039 $SESSION->cal_loggedinas = true;
054193be 1040 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1041 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1042 }
02ce3848 1043 }
1066e0dc 1044 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
02ce3848 1045 // We just logged back to our real self, update again
1046 unset($SESSION->cal_users_shown);
1047 unset($SESSION->cal_courses_shown);
1048 unset($SESSION->cal_loggedinas);
054193be 1049 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1050 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1051 }
02ce3848 1052 }
1053
7423f116 1054 if(!isset($SESSION->cal_course_referer)) {
1055 $SESSION->cal_course_referer = 0;
1056 }
1057 if(!isset($SESSION->cal_show_global)) {
1058 $SESSION->cal_show_global = true;
1059 }
1060 if(!isset($SESSION->cal_show_groups)) {
1061 $SESSION->cal_show_groups = true;
1062 }
1063 if(!isset($SESSION->cal_show_course)) {
1064 $SESSION->cal_show_course = true;
1065 }
1066 if(!isset($SESSION->cal_show_user)) {
89adb174 1067 $SESSION->cal_show_user = true;
7423f116 1068 }
6b4aeb31 1069 // if(empty($SESSION->cal_courses_shown)) {
43c3ffbe 1070 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
6b4aeb31 1071 //}
89adb174 1072 if(empty($SESSION->cal_users_shown)) {
1073 // The empty() instead of !isset() here makes a whole world of difference,
1074 // as it will automatically change to the user's id when the user first logs
1075 // in. With !isset(), it would never do that.
86a1ba04 1076 $SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false;
89adb174 1077 }
1078 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
1079 // Follow the white rabbit, for example if a teacher logs in as a student
1080 $SESSION->cal_users_shown = $USER->id;
1081 }
7423f116 1082}
1083
1084function calendar_overlib_html() {
9c6bf80e 1085 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
1086 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
7423f116 1087}
1088
7423f116 1089function calendar_set_referring_course($courseid) {
1090 global $SESSION;
1091 $SESSION->cal_course_referer = intval($courseid);
1092}
1093
43c3ffbe 1094function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
257e3f4c 1095 global $SESSION, $USER, $CFG;
1096
43c3ffbe 1097 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
51f8a12f 1098 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1099 // PHP's loose type system works against us.
43c3ffbe 1100 if(is_string($SESSION->cal_courses_shown)) {
1101 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
51f8a12f 1102 }
1103
43c3ffbe 1104 if($courseeventsfrom === NULL) {
1105 $courseeventsfrom = $SESSION->cal_courses_shown;
7423f116 1106 }
43c3ffbe 1107 if($groupeventsfrom === NULL) {
1108 $groupeventsfrom = $SESSION->cal_courses_shown;
7423f116 1109 }
1110
43c3ffbe 1111 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1112 if(is_int($courseeventsfrom)) {
9064751b 1113 $courses = array(SITEID, $courseeventsfrom);
7423f116 1114 }
43c3ffbe 1115 else if(is_array($courseeventsfrom)) {
1116 $courses = array_keys($courseeventsfrom);
9064751b 1117 $courses[] = SITEID;
7423f116 1118 }
1119 }
43c3ffbe 1120 else if($SESSION->cal_show_course) {
1121 if(is_int($courseeventsfrom)) {
1122 $courses = array($courseeventsfrom);
7423f116 1123 }
43c3ffbe 1124 else if(is_array($courseeventsfrom)) {
1125 $courses = array_keys($courseeventsfrom);
7423f116 1126 }
e749554e 1127 $courses = array_diff($courses, array(SITEID));
7423f116 1128 }
1129 else if($SESSION->cal_show_global) {
e749554e 1130 $courses = array(SITEID);
7423f116 1131 }
1132 else {
1133 $courses = false;
1134 }
0e6a8f4b 1135 //BUG 6130 clean $courses array as SESSION has bad entries.
1136 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1384da1e 1137 if (is_array($courses)) {
1138 foreach ($courses as $index => $value) {
1139 if (empty($value)) unset($courses[$index]);
1140 }
0e6a8f4b 1141 }
7423f116 1142
43c3ffbe 1143 if($SESSION->cal_show_user || $ignorefilters) {
89adb174 1144 // This doesn't work for arrays yet (maybe someday it will)
1145 $user = $SESSION->cal_users_shown;
7423f116 1146 }
1147 else {
1148 $user = false;
1149 }
43c3ffbe 1150 if($SESSION->cal_show_groups || $ignorefilters) {
1151 if(is_int($groupeventsfrom)) {
1152 $groupcourses = array($groupeventsfrom);
7423f116 1153 }
43c3ffbe 1154 else if(is_array($groupeventsfrom)) {
1155 $groupcourses = array_keys($groupeventsfrom);
1156 }
257e3f4c 1157
9c37662f 1158 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1159 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($CFG->calendar_adminseesall)) {
257e3f4c 1160 $group = true;
1161 }
1162 else {
1163 $grouparray = array();
69762501 1164
257e3f4c 1165 // We already have the courses to examine in $courses
1166 // For each course...
37d87d11 1167
257e3f4c 1168 foreach($groupcourses as $courseid) {
69762501 1169
257e3f4c 1170 // If the user is an editing teacher in there,
cc398c72 1171 if(!empty($USER->id) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
69762501 1172 // If this course has groups, show events from all of them
b8227b88 1173 if(is_int($groupeventsfrom)) {
1174 $courserecord = get_record('course', 'id', $courseid);
1175 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1176 $groupids[] = $courseid;
1177 }
1178 }
1179 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
37d87d11 1180 $groupids[] = $courseid;
257e3f4c 1181 }
1182 }
69762501 1183
1184 // Otherwise (not editing teacher) show events from the group he is a member of
257e3f4c 1185 else if(isset($USER->groupmember[$courseid])) {
fa22fd5f 1186 //changed to 2D array
1187 foreach ($USER->groupmember[$courseid] as $groupid){
1188 $grouparray[] = $groupid;
1189 }
7423f116 1190 }
1191 }
37d87d11 1192
6b4aeb31 1193 if (!empty($groupids)) {
1194 $sql = "SELECT id, groupid
1195 FROM {$CFG->prefix}groups_courses_groups
1196 WHERE courseid IN (".implode(',', $groupids).')';
1197
1198 if ($grouprecords= get_records_sql($sql)) {
1199 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1200 }
1201 }
37d87d11 1202
257e3f4c 1203 if(empty($grouparray)) {
1204 $group = false;
1205 }
1206 else {
1207 $group = $grouparray;
6c9584d1 1208 }
7423f116 1209 }
257e3f4c 1210
7423f116 1211 }
1212 else {
1213 $group = false;
1214 }
1215}
1216
1217function calendar_edit_event_allowed($event) {
89491dbd 1218
7423f116 1219 global $USER;
1220
89491dbd 1221 // can not be using guest account
1222 if ($USER->username == "guest") {
1223 return false;
1224 }
cc398c72 1225
89491dbd 1226 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1227 // if user has manageentries at site level, return true
28ee98c5 1228 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1229 return true;
f52f7413 1230 }
c0a2c361 1231
1232 // if groupid is set, it's definitely a group event
1233 if ($event->groupid) {
3c49918a 1234 //TODO:check.
1235 if (! groups_group_exists($event->groupid)) {
69244b91 1236 return false;
89491dbd 1237 }
cc398c72 1238
89491dbd 1239 // this is ok because if you have this capability at course level, you should be able
1240 // to edit group calendar too
1241 // there is no need to check membership, because if you have this capability
1242 // you will have a role in this group context
c0a2c361 1243 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
89491dbd 1244 } else if ($event->courseid) {
c0a2c361 1245 // if groupid is not set, but course is set,
1246 // it's definiely a course event
1247 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1248 } else if ($event->userid && $event->userid == $USER->id) {
1249 // if course is not set, but userid id set, it's a user event
1250 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1251 }
7423f116 1252 return false;
1253}
1254
8c54cec6 1255function calendar_get_default_courses($ignoreref = false) {
9ff136e5 1256 global $USER, $CFG, $SESSION;
1257
8c54cec6 1258 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
4c7d1137 1259 return array($SESSION->cal_course_referer => 1);
9ff136e5 1260 }
7423f116 1261
1066e0dc 1262 if(empty($USER->id)) {
2ef75eee 1263 return array();
1264 }
1265
7423f116 1266 $courses = array();
03bb25e1 1267 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1268 if (!empty($CFG->calendar_adminseesall)) {
86f092d2 1269 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1270 return $courses;
1271 }
95a89225 1272 }
03bb25e1 1273
daaf61f4 1274 if (isset($CFG->adminseesall)) {
0a66585b 1275 $courses = get_my_courses($USER->id, 'visible DESC', null, $CFG->adminseesall);
daaf61f4 1276 }
1277 else {
0a66585b 1278 $courses = get_my_courses($USER->id, 'visible DESC', null, false);
7423f116 1279 }
37d87d11 1280
1281 return $courses;
7423f116 1282}
1283
1e1ff33b 1284function calendar_preferences_button() {
1285 global $CFG, $USER;
7423f116 1286
1287 // Guests have no preferences
f52f7413 1288 if (empty($USER->id) || isguest()) {
7423f116 1289 return '';
1290 }
1291
fa738731 1292 return "<form $CFG->frametarget method=\"get\" ".
1e1ff33b 1293 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
2aab6488 1294 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
7423f116 1295}
1296
8f896582 1297function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1298 $startdate = usergetdate($event->timestart);
1299 $enddate = usergetdate($event->timestart + $event->timeduration);
1300 $usermidnightstart = usergetmidnight($event->timestart);
1301
1302 if($event->timeduration) {
1303 // To avoid doing the math if one IF is enough :)
1304 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1305 }
1306 else {
1307 $usermidnightend = $usermidnightstart;
1308 }
1309
1310 // OK, now to get a meaningful display...
1311 // First of all we have to construct a human-readable date/time representation
1312
1313 if($event->timestart + $event->timeduration < $now) {
1314 // It has expired, so we don't care about duration
1315 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1316 $time = calendar_time_representation($event->timestart + $event->timeduration);
1317
1318 // This var always has the printable time representation
1319 $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>';
1320
1321 }
1322 else if($event->timeduration) {
1323 // It has a duration
1324 if($usermidnightstart == $usermidnightend) {
1325 // But it's all on the same day
1326 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1327 $timestart = calendar_time_representation($event->timestart);
1328 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1329
1330 // Set printable representation
1331 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
7d50b363 1332 ' ('.$timestart.' <strong>&raquo;</strong> '.$timeend.')';
8f896582 1333 }
1334 else {
1335 // It spans two or more days
1336 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1337 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1338 $timestart = calendar_time_representation($event->timestart);
1339 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1340
1341 // Set printable representation
1342 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
7d50b363 1343 ' ('.$timestart.') <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
8f896582 1344 ' ('.$timeend.')';
1345 }
1346 }
1347 else {
1348 // It's an "instantaneous" event
1349 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1350 $time = calendar_time_representation($event->timestart);
1351
1352 // Set printable representation
1353 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1354 }
09d36284 1355
8f896582 1356 return $eventtime;
1357}
054193be 1358
86f092d2 1359function calendar_print_month_selector($name, $selected) {
1360
1361 $months = array();
1362
1363 for ($i=1; $i<=12; $i++) {
76ab1c33 1364 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1365 }
1366
1367 choose_from_menu($months, $name, $selected, '');
1368}
1369
054193be 1370function calendar_get_filters_status() {
1371 global $SESSION;
1372
1373 $status = 0;
1374 if($SESSION->cal_show_global) {
1375 $status += 1;
1376 }
1377 if($SESSION->cal_show_course) {
1378 $status += 2;
1379 }
1380 if($SESSION->cal_show_groups) {
1381 $status += 4;
1382 }
1383 if($SESSION->cal_show_user) {
1384 $status += 8;
1385 }
1386 return $status;
1387}
1388
1389function calendar_set_filters_status($packed_bitfield) {
1390 global $SESSION, $USER;
1391
1392 if(!isset($USER) || empty($USER->id)) {
1393 return false;
1394 }
1395
1396 $SESSION->cal_show_global = ($packed_bitfield & 1);
1397 $SESSION->cal_show_course = ($packed_bitfield & 2);
1398 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1399 $SESSION->cal_show_user = ($packed_bitfield & 8);
1400
1401 return true;
1402}
1403
d0a32914 1404?>