Merging fix for bug 2264 & improvements from MOODLE_14_STABLE
[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: //
12// Avgoustos Tsinakos (tsinakos@uom.gr) //
13// Jon Papaioannou (pj@uom.gr) //
14// //
15// Programming and development: //
16// Jon Papaioannou (pj@uom.gr) //
17// //
18// For bugs, suggestions, etc contact: //
19// Jon Papaioannou (pj@uom.gr) //
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
bd119567 65// Initialize the session variables here to be sure
66calendar_session_vars();
67
7423f116 68function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
69 global $CFG, $USER;
70
4e17c6f3 71 $display = &New stdClass;
7423f116 72 $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
73 $display->maxwday = $display->minwday + 6;
74
75 $content = '';
76
77 if(!empty($cal_month) && !empty($cal_year)) {
78 $thisdate = usergetdate(time()); // Date and time the user sees at his location
79 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
80 // Navigated to this month
81 $date = $thisdate;
82 $display->thismonth = true;
83 }
84 else {
85 // Navigated to other month, let's do a nice trick and save us a lot of work...
86 if(!checkdate($cal_month, 1, $cal_year)) {
87 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
88 $display->thismonth = true;
89 }
90 else {
91 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
92 $display->thismonth = false;
93 }
94 }
95 }
96 else {
97 $date = usergetdate(time()); // Date and time the user sees at his location
98 $display->thismonth = true;
99 }
100
101 // Fill in the variables we 're going to use, nice and tidy
102 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
103 $display->maxdays = calendar_days_in_month($m, $y);
104
105 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
106 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
107 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
108
109 $startwday = gmdate('w', $display->tstart); // $display->tstart is already GMT, so don't use date(): messes with server's TZ
110
111 // Align the starting weekday to fall in our display range
112 // This is simple, not foolproof.
113 if($startwday < $display->minwday) {
114 $startwday += 7;
115 }
116
117 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
118 $whereclause = calendar_sql_where(usertime($display->tstart), usertime($display->tend), $users, $groups, $courses);
119
120 if($whereclause === false) {
121 $events = array();
122 }
123 else {
a94329a8 124 $events = get_records_select('event', $whereclause, 'timestart');
7423f116 125 }
126
c635dcda 127 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 128 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 129 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
130 // arguments to this function.
131
7bd1677c 132 $morehref = '';
133 if(!empty($courses)) {
e749554e 134 $courses = array_diff($courses, array(SITEID));
7bd1677c 135 if(count($courses) == 1) {
136 $morehref = '&amp;course='.reset($courses);
137 }
c635dcda 138 }
139
7423f116 140 // We want to have easy access by day, since the display is on a per-day basis.
141 // Arguments passed by reference.
7b38bfa6 142 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
143 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday);
7423f116 144
92668ad2 145 $content .= '<table class="calendarmini">'; // Begin table
146 $content .= '<thead><tr>'; // Header row: day names
7423f116 147
148 // Print out the names of the weekdays
149 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
150 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
151 // This uses the % operator to get the correct weekday no matter what shift we have
152 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
92668ad2 153 $content .= '<td>'.get_string($days[$i % 7], 'calendar').'</td>';
7423f116 154 }
155
92668ad2 156 $content .= '</tr></thead><tbody><tr>'; // End of day names; prepare for day numbers
7423f116 157
158 // For the table display. $week is the row; $dayweek is the column.
7423f116 159 $dayweek = $startwday;
160
161 // Paddding (the first week may have blank days in the beginning)
162 for($i = $display->minwday; $i < $startwday; ++$i) {
92668ad2 163 $content .= '<td>&nbsp;</td>'."\n";
7423f116 164 }
165
d56d4e23 166 $strftimetimedayshort = get_string('strftimedayshort');
167
7423f116 168 // Now display all the calendar
169 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
170 if($dayweek > $display->maxwday) {
171 // We need to change week (table row)
d56d4e23 172 $content .= '</tr><tr>';
7423f116 173 $dayweek = $display->minwday;
7423f116 174 }
92668ad2 175
7423f116 176 // Reset vars
7423f116 177 $cell = '';
bb4a2e85 178 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
7423f116 179 // Weekend. This is true no matter what the exact range is.
92668ad2 180 $class = 'cal_weekend';
7423f116 181 }
182 else {
183 // Normal working day.
92668ad2 184 $class = '';
7423f116 185 }
186
187 // Special visual fx if an event is defined
188 if(isset($eventsbyday[$day])) {
c635dcda 189 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
f434283f 190
7423f116 191 // OverLib popup
192 $popupcontent = '';
193 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 194 if (!isset($events[$eventid])) {
195 continue;
4e17c6f3 196 }
41d30a8e 197 $event = $events[$eventid];
41d30a8e 198 if(!empty($event->modulename)) {
199 $popupicon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
200 $popupalt = $event->modulename;
201
9064751b 202 } else if ($event->courseid == SITEID) { // Site event
41d30a8e 203 $popupicon = $CFG->pixpath.'/c/site.gif';
204 $popupalt = '';
c3d3b6d4 205 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
41d30a8e 206 $popupicon = $CFG->pixpath.'/c/course.gif';
c9b05b32 207 $popupalt = '';
41d30a8e 208 } else if ($event->groupid) { // Group event
209 $popupicon = $CFG->pixpath.'/c/group.gif';
210 $popupalt = '';
211 } else if ($event->userid) { // User event
212 $popupicon = $CFG->pixpath.'/c/user.gif';
213 $popupalt = '';
4e17c6f3 214 }
9cb8879b 215 $popupcontent .= '<div><img height="16" width="16" src="'.$popupicon.'" style="vertical-align: middle; margin-right: 4px;" alt="'.$popupalt.'" /><a href="'.$dayhref.'">'.$event->name.'</a></div>';
7423f116 216 }
217
d56d4e23 218 $popupcaption = get_string('eventsfor', 'calendar', userdate($events[$eventid]->timestart, $strftimetimedayshort));
9cb8879b 219 $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
7423f116 220 $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
221
222 // Class and cell content
223 if(isset($typesbyday[$day]['startglobal'])) {
224 $class .= ' cal_event_global';
225 }
226 else if(isset($typesbyday[$day]['startcourse'])) {
227 $class .= ' cal_event_course';
228 }
229 else if(isset($typesbyday[$day]['startgroup'])) {
230 $class .= ' cal_event_group';
231 }
232 else if(isset($typesbyday[$day]['startuser'])) {
233 $class .= ' cal_event_user';
234 }
deaa8842 235 $cell = '<strong><a href="'.$dayhref.'" '.$popup.'>'.$day.'</a></strong>';
7423f116 236 }
237 else {
238 $cell = $day;
239 }
240
241 if(isset($typesbyday[$day]['durationglobal'])) {
242 $class .= ' cal_duration_global';
243 }
244 else if(isset($typesbyday[$day]['durationcourse'])) {
245 $class .= ' cal_duration_course';
246 }
247 else if(isset($typesbyday[$day]['durationgroup'])) {
248 $class .= ' cal_duration_group';
249 }
250 else if(isset($typesbyday[$day]['durationuser'])) {
251 $class .= ' cal_duration_user';
252 }
253
254 // Special visual fx for today
255 if($display->thismonth && $day == $d) {
256 $class .= ' cal_today';
257 }
258
259 // Just display it
92668ad2 260 if(!empty($class)) {
d56d4e23 261 $class = ' class="'.$class.'"';
92668ad2 262 }
263 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 264 }
265
266 // Paddding (the last week may have blank days at the end)
267 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
92668ad2 268 $content .= '<td>&nbsp;</td>';
7423f116 269 }
270 $content .= '</tr>'; // Last row ends
271
92668ad2 272 $content .= '</tbody></table>'; // Tabular display of days ends
7423f116 273
274 return $content;
275}
276
9958a08c 277function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
7423f116 278 global $CFG;
279
c635dcda 280 $display = &New stdClass;
7423f116 281 $display->range = $daysinfuture; // How many days in the future we 'll look
282 $display->maxevents = $maxevents;
283
284 $output = array();
285
286 // Prepare "course caching", since it may save us a lot of queries
287 $coursecache = array();
288
289 $processed = 0;
290 $now = time(); // We 'll need this later
9d567178 291 $usermidnighttoday = usergetmidnight($now);
7423f116 292
9958a08c 293 if ($fromtime) {
294 $display->tstart = $fromtime;
295 } else {
9d567178 296 $display->tstart = $usermidnighttoday;
9958a08c 297 }
7423f116 298
9c6bf80e 299 // This does include DST compensation, but unfortunately only with respect to the server's TZ
300 $display->tend = strtotime('+'.$display->range.' days', $display->tstart) - 1;
7423f116 301
302 // Get the events matching our criteria
303 $whereclause = calendar_sql_where($display->tstart, $display->tend, $users, $groups, $courses);
9958a08c 304 if ($whereclause === false) {
7423f116 305 $events = false;
9958a08c 306 } else {
a94329a8 307 $events = get_records_select('event', $whereclause, 'timestart');
7423f116 308 }
309
c635dcda 310 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 311 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 312 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
313 // arguments to this function.
314
7bd1677c 315 $morehref = '';
316 if(!empty($courses)) {
e749554e 317 $courses = array_diff($courses, array(SITEID));
7bd1677c 318 if(count($courses) == 1) {
319 $morehref = '&amp;course='.reset($courses);
320 }
c635dcda 321 }
322
7423f116 323 if($events !== false) {
324 foreach($events as $event) {
9d567178 325
326 if($processed >= $display->maxevents) {
327 break;
328 }
7423f116 329
8f896582 330 $eventtime = calendar_format_event_time($event, $now, $morehref);
7423f116 331
332 $outkey = count($output);
333
421b0337 334 $output[$outkey] = $event; // Grab the whole raw event by default
335
7423f116 336 // Now we know how to display the time, we have to see how to display the event
41d30a8e 337 if(!empty($event->modulename)) { // Activity event
7423f116 338
339 // The module name is set. I will assume that it has to be displayed, and
340 // also that it is an automatically-generated event. And of course that the
b63c0ee5 341 // fields for get_coursemodule_from_instance are set correctly.
7423f116 342
b63c0ee5 343 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 344
9958a08c 345 if ($module === false) {
7423f116 346 // This shouldn't have happened. What to do now?
347 // Just ignore it
348 continue;
349 }
350
351 $modulename = get_string('modulename', $event->modulename);
352 $eventtype = get_string($event->eventtype, $event->modulename);
353 $icon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
9958a08c 354
deaa8842 355 $output[$outkey]->icon = '<img height="16" width="16" src="'.$icon.'" alt="" title="'.$modulename.'" style="vertical-align: middle;" />';
9958a08c 356 $output[$outkey]->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
7423f116 357 $output[$outkey]->time = $eventtime;
b63c0ee5 358 $output[$outkey]->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
9958a08c 359 $output[$outkey]->cmid = $module->id;
9958a08c 360
361
9064751b 362 } else if($event->courseid == SITEID) { // Site event
deaa8842 363 $output[$outkey]->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/site.gif" alt="" style="vertical-align: middle;" />';
7423f116 364 $output[$outkey]->time = $eventtime;
9958a08c 365
366
c3d3b6d4 367 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
7423f116 368 calendar_get_course_cached($coursecache, $event->courseid);
369
deaa8842 370 $output[$outkey]->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/course.gif" alt="" style="vertical-align: middle;" />';
7423f116 371 $output[$outkey]->time = $eventtime;
9958a08c 372 $output[$outkey]->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
9958a08c 373
374
41d30a8e 375 } else if ($event->groupid) { // Group event
deaa8842 376 $output[$outkey]->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/group.gif" alt="" style="vertical-align: middle;" />';
7423f116 377 $output[$outkey]->time = $eventtime;
9958a08c 378
379
41d30a8e 380 } else if($event->userid) { // User event
deaa8842 381 $output[$outkey]->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/user.gif" alt="" style="vertical-align: middle;" />';
7423f116 382 $output[$outkey]->time = $eventtime;
7423f116 383 }
384 ++$processed;
385 }
386 }
387 return $output;
388}
389
8c165fe9 390function calendar_sql_where($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
7423f116 391 $whereclause = '';
392 // Quick test
393 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
394 return false;
395 }
482dbe0c 396
7423f116 397 if(is_array($users) && !empty($users)) {
398 // Events from a number of users
399 if(!empty($whereclause)) $whereclause .= ' OR';
400 $whereclause .= ' userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0';
401 }
402 else if(is_numeric($users)) {
403 // Events from one user
404 if(!empty($whereclause)) $whereclause .= ' OR';
405 $whereclause .= ' userid = '.$users.' AND courseid = 0 AND groupid = 0';
406 }
407 else if($users === true) {
408 // Events from ALL users
409 if(!empty($whereclause)) $whereclause .= ' OR';
410 $whereclause .= ' userid != 0 AND courseid = 0 AND groupid = 0';
411 }
f52f7413 412 else if($users === false) {
413 // No user at all
09d36284 414 // No need to do anything
f52f7413 415 }
482dbe0c 416
7423f116 417 if(is_array($groups) && !empty($groups)) {
418 // Events from a number of groups
419 if(!empty($whereclause)) $whereclause .= ' OR';
420 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
421 }
422 else if(is_numeric($groups)) {
423 // Events from one group
424 if(!empty($whereclause)) $whereclause .= ' OR ';
425 $whereclause .= ' groupid = '.$groups;
426 }
427 else if($groups === true) {
428 // Events from ALL groups
429 if(!empty($whereclause)) $whereclause .= ' OR ';
430 $whereclause .= ' groupid != 0';
431 }
482dbe0c 432 // boolean false (no groups at all): we don't need to do anything
433
f52f7413 434 if(is_array($courses)) {
435 // A number of courses (maybe none at all!)
436 if(!empty($courses)) {
437 if(!empty($whereclause)) {
438 $whereclause .= ' OR';
439 }
440 $whereclause .= ' groupid = 0 AND courseid IN ('.implode(',', $courses).')';
441 }
442 else {
443 // This means NO courses, not that we don't care!
09d36284 444 // No need to do anything
f52f7413 445 }
7423f116 446 }
447 else if(is_numeric($courses)) {
448 // One course
449 if(!empty($whereclause)) $whereclause .= ' OR';
450 $whereclause .= ' groupid = 0 AND courseid = '.$courses;
451 }
452 else if($courses === true) {
453 // Events from ALL courses
454 if(!empty($whereclause)) $whereclause .= ' OR';
455 $whereclause .= ' groupid = 0 AND courseid != 0';
456 }
8c165fe9 457
482dbe0c 458 // Security check: if, by now, we have NOTHING in $whereclause, then it means
459 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
460 // events no matter what. Allowing the code to proceed might return a completely
461 // valid query with only time constraints, thus selecting ALL events in that time frame!
462 if(empty($whereclause)) {
463 return false;
464 }
465
8c165fe9 466 if ($ignorehidden) {
467 if (!empty($whereclause)) $whereclause .= ' AND';
468 $whereclause .= ' visible = 1';
469 }
470
7423f116 471 if($withduration) {
472 $timeclause = 'timestart + timeduration >= '.$tstart.' AND timestart <= '.$tend;
473 }
474 else {
475 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
476 }
477 if(!empty($whereclause)) {
478 // We have additional constraints
479 $whereclause = $timeclause.' AND ('.$whereclause.')';
480 }
481 else {
482 // Just basic time filtering
483 $whereclause = $timeclause;
484 }
f52f7413 485
09d36284 486 return empty($whereclause) ? false : $whereclause;
7423f116 487}
488
489function calendar_top_controls($type, $data) {
490 global $CFG;
491 $content = '';
492 if(!isset($data['d'])) {
493 $data['d'] = 1;
494 }
00341fea 495 $time = calendar_mktime_check($data['m'], $data['d'], $data['y']);
33683b36 496 $date = getdate($time);
7423f116 497 $data['m'] = $date['mon'];
498 $data['y'] = $date['year'];
7423f116 499
500 switch($type) {
501 case 'frontpage':
502 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
503 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
73341343 504 $nextlink = calendar_get_link_tag('&gt;&gt;', 'index.php?', 0, $nextmonth, $nextyear);
505 $prevlink = calendar_get_link_tag('&lt;&lt;', 'index.php?', 0, $prevmonth, $prevyear);
7423f116 506 $content .= '<table class="generaltable" style="width: 100%;"><tr>';
507 $content .= '<td style="text-align: left; width: 12%;">'.$prevlink."</td>\n";
61854a2f 508 $content .= '<td style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.strftime(get_string('strftimemonthyear'), $time)."</a></td>\n";
7423f116 509 $content .= '<td style="text-align: right; width: 12%;">'.$nextlink."</td>\n";
510 $content .= '</tr></table>';
511 break;
512 case 'course':
513 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
514 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
515 $nextlink = calendar_get_link_tag('&gt;&gt;', 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear);
516 $prevlink = calendar_get_link_tag('&lt;&lt;', 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear);
517 $content .= '<table class="generaltable" style="width: 100%;"><tr>';
518 $content .= '<td style="text-align: left; width: 12%;">'.$prevlink."</td>\n";
227bc46b 519 $content .= '<td style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;course='.$data['id'].'&amp;', 1, $data['m'], $data['y']).'">'.strftime(get_string('strftimemonthyear'), $time)."</a></td>\n";
7423f116 520 $content .= '<td style="text-align: right; width: 12%;">'.$nextlink."</td>\n";
521 $content .= '</tr></table>';
522 break;
523 case 'upcoming':
43c3ffbe 524 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming">'.strftime(get_string('strftimemonthyear'), $time)."</a></div>\n";
7423f116 525 break;
526 case 'display':
aa870ca2 527 $content .= '<div style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.strftime(get_string('strftimemonthyear'), $time)."</a></div>\n";
7423f116 528 break;
529 case 'month':
530 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
531 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
f7656746 532 $prevdate = calendar_mktime_check($prevmonth, 1, $prevyear);
533 $nextdate = calendar_mktime_check($nextmonth, 1, $nextyear);
7423f116 534 $content .= "<table style='width: 100%;'><tr>\n";
aa870ca2 535 $content .= '<td style="text-align: left; width: 30%;"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $prevmonth, $prevyear).'">&lt;&lt; '.strftime(get_string('strftimemonthyear'), $prevdate)."</a></td>\n";
6e8e8ec6 536 $content .= '<td style="text-align: center"><strong>'.strftime(get_string('strftimemonthyear'), $time)."</strong></td>\n";
aa870ca2 537 $content .= '<td style="text-align: right; width: 30%;"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $nextmonth, $nextyear).'">'.strftime(get_string('strftimemonthyear'), $nextdate)." &gt;&gt;</a></td>\n";
7423f116 538 $content .= "</tr></table>\n";
539 break;
540 case 'day':
541 $data['d'] = $date['mday']; // Just for convenience
542 $dayname = calendar_wday_name($date['weekday']);
3c7e1b65 543 $prevdate = getdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
544 $nextdate = getdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
7423f116 545 $prevname = calendar_wday_name($prevdate['weekday']);
546 $nextname = calendar_wday_name($nextdate['weekday']);
547 $content .= "<table style='width: 100%;'><tr>\n";
3696526b 548 $content .= '<td style="text-align: left; width: 20%;"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']).'">&lt;&lt; '.$prevname."</a></td>\n";
6e8e8ec6 549
550 // Get the format string
551 $text = get_string('strftimedaydate');
552 // Regexp hackery to make a link out of the month/year part
553 $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);
554 // Replace with actual values and lose any day leading zero
555 $text = strftime($text, $time);
556 $text = str_replace(' 0', ' ', $text);
557 // Print the actual thing
558 $content .= '<td style="text-align: center"><strong>'.$text."</strong></td>\n";
559
3696526b 560 $content .= '<td style="text-align: right; width: 20%;"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']).'">'.$nextname." &gt;&gt;</a></td>\n";
7423f116 561 $content .= "</tr></table>\n";
562 break;
563 }
564 return $content;
565}
566
3cb9ee39 567function calendar_filter_controls($type, $vars = NULL, $course = NULL) {
43c3ffbe 568 global $CFG, $SESSION, $USER;
7423f116 569
48f508ab 570 $groupevents = true;
3cb9ee39 571 $getvars = '';
d715f7c4 572
34bf3ad4 573 switch($type) {
eb15f829 574 case 'event':
34bf3ad4 575 case 'upcoming':
34bf3ad4 576 case 'day':
c3f463ca 577 case 'month':
eb15f829 578 $getvars = '&amp;from='.$type;
34bf3ad4 579 break;
580 case 'course':
2eb68e6f 581 if (isset($_GET['id'])) {
582 $getvars = '&amp;from=course&amp;id='.$_GET['id'];
583 } else {
584 $getvars = '&amp;from=course';
585 }
3cb9ee39 586 if (isset($course->groupmode) and !$course->groupmode and $course->groupmodeforce) {
34bf3ad4 587 $groupevents = false;
588 }
589 break;
d715f7c4 590 }
34bf3ad4 591
3cb9ee39 592 if (!empty($vars)) {
34bf3ad4 593 $getvars .= '&amp;'.$vars;
48f508ab 594 }
7423f116 595
48f508ab 596 $content = '<table class="cal_controls" style="width: 98%;">';
7423f116 597
48f508ab 598 $content .= '<tr>';
599 if($SESSION->cal_show_global) {
2b7591cc 600 $content .= '<td class="cal_event_global" style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
48f508ab 601 }
602 else {
2b7591cc 603 $content .= '<td style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
48f508ab 604 }
605 if($SESSION->cal_show_course) {
2b7591cc 606 $content .= '<td class="cal_event_course" style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
7423f116 607 }
48f508ab 608 else {
2b7591cc 609 $content .= '<td style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
48f508ab 610 }
48f508ab 611
1066e0dc 612 if(!empty($USER->id) && !isguest()) {
43c3ffbe 613 $content .= "</tr>\n<tr>";
614
615 if($groupevents) {
616 // This course MIGHT have group events defined, so show the filter
617 if($SESSION->cal_show_groups) {
618 $content .= '<td class="cal_event_group" style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
cd6469cb 619 } else {
43c3ffbe 620 $content .= '<td style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
621 }
cd6469cb 622 if ($SESSION->cal_show_user) {
43c3ffbe 623 $content .= '<td class="cal_event_user" style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
cd6469cb 624 } else {
43c3ffbe 625 $content .= '<td style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
626 }
cd6469cb 627
628 } else {
43c3ffbe 629 // This course CANNOT have group events, so lose the filter
cd6469cb 630 $content .= '<td style="width: 8px;"></td><td>&nbsp;</td>'."\n";
631
43c3ffbe 632 if($SESSION->cal_show_user) {
cd6469cb 633 $content .= '<td class="cal_event_user" style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
634 } else {
635 $content .= '<td style="width: 8px;"></td><td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
43c3ffbe 636 }
48f508ab 637 }
638 }
639 $content .= "</tr>\n</table>\n";
640
7423f116 641 return $content;
642}
643
644function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
645
0ef7c973 646 static $shortformat;
647 if(empty($shortformat)) {
e70fdac0 648 $shortformat = get_string('strftimedayshort');
0ef7c973 649 }
650
7423f116 651 if($now === false) {
652 $now = time();
653 }
654
655 // To have it in one place, if a change is needed
e70fdac0 656 $formal = userdate($tstamp, $shortformat);
7423f116 657
7b38bfa6 658 $datestamp = usergetdate($tstamp);
659 $datenow = usergetdate($now);
7423f116 660
661 if($usecommonwords == false) {
662 // We don't want words, just a date
663 return $formal;
664 }
7b38bfa6 665 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 666 // Today
667 return get_string('today', 'calendar');
668 }
7b38bfa6 669 else if(
670 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
671 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
672 ) {
7423f116 673 // Yesterday
674 return get_string('yesterday', 'calendar');
675 }
7b38bfa6 676 else if(
677 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
678 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
679 ) {
7423f116 680 // Tomorrow
681 return get_string('tomorrow', 'calendar');
682 }
683 else {
684 return $formal;
685 }
686}
687
688function calendar_time_representation($time) {
1b0ebe79 689 static $langtimeformat = NULL;
690 if($langtimeformat === NULL) {
691 $langtimeformat = get_string('strftimetime');
692 }
693 $timeformat = get_user_preferences('calendar_timeformat');
694 // The ? is needed because the preference might be present, but empty
695 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 696}
697
698function calendar_get_link_href($linkbase, $d, $m, $y) {
699 if(empty($linkbase)) return '';
700 $paramstr = '';
701 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
702 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
703 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
704 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
705 return $linkbase.$paramstr;
706}
707
708function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
709 $href = calendar_get_link_href($linkbase, $d, $m, $y);
710 if(empty($href)) return $text;
711 return '<a href="'.$href.'">'.$text.'</a>';
712}
713
714function calendar_gmmktime_check($m, $d, $y, $default = false) {
715 if($default === false) $default = time();
716 if(!checkdate($m, $d, $y)) {
717 return $default;
718 }
719 else {
720 return gmmktime(0, 0, 0, $m, $d, $y);
721 }
722}
723
724function calendar_mktime_check($m, $d, $y, $default = false) {
725 if($default === false) $default = time();
726 if(!checkdate($m, $d, $y)) {
727 return $default;
728 }
729 else {
730 return mktime(0, 0, 0, $m, $d, $y);
731 }
732}
733
7423f116 734function calendar_wday_name($englishname) {
735 return get_string(strtolower($englishname), 'calendar');
736}
737
738function calendar_days_in_month($month, $year) {
7b38bfa6 739 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 740}
741
e749554e 742function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
7423f116 743 $content = '';
744 $lines = count($events);
396b61f0 745 if (!$lines) {
746 return $content;
747 }
7423f116 748
396b61f0 749 for ($i = 0; $i < $lines; ++$i) {
7423f116 750 $content .= '<div class="cal_event">'.$events[$i]->icon.' ';
43c3ffbe 751 if (!empty($events[$i]->referer)) {
7423f116 752 // That's an activity event, so let's provide the hyperlink
396b61f0 753 $content .= $events[$i]->referer;
754 } else {
e749554e 755 if(!empty($linkhref)) {
756 $ed = usergetdate($events[$i]->timestart);
757 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
758 $content .= '<a href="'.$href.'">'.$events[$i]->name.'</a>';
759 }
760 else {
761 $content .= $events[$i]->name;
762 }
7423f116 763 }
14fcda78 764 $events[$i]->time = str_replace('->', '<br />->', $events[$i]->time);
d13403fb 765 $content .= '</div><div class="cal_event_date" style="text-align:right;">'.$events[$i]->time.'</div>';
396b61f0 766 if ($i < $lines - 1) $content .= '<hr />';
7423f116 767 }
768
769 return $content;
7423f116 770}
771
772function calendar_add_month($month, $year) {
773 if($month == 12) {
774 return array(1, $year + 1);
775 }
776 else {
777 return array($month + 1, $year);
778 }
779}
780
781function calendar_sub_month($month, $year) {
782 if($month == 1) {
783 return array(12, $year - 1);
784 }
785 else {
786 return array($month - 1, $year);
787 }
788}
789
7b38bfa6 790function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday) {
7423f116 791 $eventsbyday = array();
792 $typesbyday = array();
793 $durationbyday = array();
794
795 if($events === false) {
796 return;
797 }
798
7423f116 799 foreach($events as $event) {
7423f116 800
7b38bfa6 801 $startdate = usergetdate($event->timestart);
802 $enddate = usergetdate($event->timestart + $event->timeduration);
7423f116 803
7b38bfa6 804 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 805 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 806 // Out of bounds
807 continue;
7423f116 808 }
809
7b38bfa6 810 $eventdaystart = intval($startdate['mday']);
7423f116 811
7b38bfa6 812 if($startdate['mon'] == $month && $startdate['year'] == $year) {
813 // Give the event to its day
814 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 815
7b38bfa6 816 // Mark the day as having such an event
9064751b 817 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 818 $typesbyday[$eventdaystart]['startglobal'] = true;
819 }
c3d3b6d4 820 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 821 $typesbyday[$eventdaystart]['startcourse'] = true;
822 }
823 else if($event->groupid) {
824 $typesbyday[$eventdaystart]['startgroup'] = true;
825 }
826 else if($event->userid) {
827 $typesbyday[$eventdaystart]['startuser'] = true;
828 }
829 }
7423f116 830
7b38bfa6 831 if($event->timeduration == 0) {
832 // Proceed with the next
833 continue;
834 }
7423f116 835
7b38bfa6 836 // The event starts on $month $year or before. So...
ef618501 837 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 838
839 // Also, it ends on $month $year or later...
840 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
841
842 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
843 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
844 $durationbyday[$i][] = $event->id;
9064751b 845 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 846 $typesbyday[$i]['durationglobal'] = true;
847 }
c3d3b6d4 848 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 849 $typesbyday[$i]['durationcourse'] = true;
850 }
851 else if($event->groupid) {
852 $typesbyday[$i]['durationgroup'] = true;
853 }
854 else if($event->userid) {
855 $typesbyday[$i]['durationuser'] = true;
7423f116 856 }
857 }
7b38bfa6 858
7423f116 859 }
860 return;
861}
862
b63c0ee5 863function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
864 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 865
866 if($module === false) return false;
b63c0ee5 867 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 868 return false;
869 }
870 return $module;
871}
872
873function calendar_get_course_cached(&$coursecache, $courseid) {
874 if(!isset($coursecache[$courseid])) {
875 $coursecache[$courseid] = get_record('course', 'id', $courseid);
876 }
877 return $coursecache[$courseid];
878}
879
880function calendar_session_vars() {
881 global $SESSION, $USER;
882
1066e0dc 883 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
02ce3848 884 // We just logged in as someone else, update the filtering
885 unset($SESSION->cal_users_shown);
886 unset($SESSION->cal_courses_shown);
887 $SESSION->cal_loggedinas = true;
888 }
1066e0dc 889 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
02ce3848 890 // We just logged back to our real self, update again
891 unset($SESSION->cal_users_shown);
892 unset($SESSION->cal_courses_shown);
893 unset($SESSION->cal_loggedinas);
894 }
895
7423f116 896 if(!isset($SESSION->cal_course_referer)) {
897 $SESSION->cal_course_referer = 0;
898 }
899 if(!isset($SESSION->cal_show_global)) {
900 $SESSION->cal_show_global = true;
901 }
902 if(!isset($SESSION->cal_show_groups)) {
903 $SESSION->cal_show_groups = true;
904 }
905 if(!isset($SESSION->cal_show_course)) {
906 $SESSION->cal_show_course = true;
907 }
908 if(!isset($SESSION->cal_show_user)) {
89adb174 909 $SESSION->cal_show_user = true;
7423f116 910 }
43c3ffbe 911 if(empty($SESSION->cal_courses_shown)) {
912 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
913 }
89adb174 914 if(empty($SESSION->cal_users_shown)) {
915 // The empty() instead of !isset() here makes a whole world of difference,
916 // as it will automatically change to the user's id when the user first logs
917 // in. With !isset(), it would never do that.
918 $SESSION->cal_users_shown = isset($USER->id) ? $USER->id : false;
919 }
920 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
921 // Follow the white rabbit, for example if a teacher logs in as a student
922 $SESSION->cal_users_shown = $USER->id;
923 }
7423f116 924}
925
926function calendar_overlib_html() {
9c6bf80e 927 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
928 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
7423f116 929}
930
7423f116 931function calendar_set_referring_course($courseid) {
932 global $SESSION;
933 $SESSION->cal_course_referer = intval($courseid);
934}
935
43c3ffbe 936function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
7423f116 937 global $SESSION, $USER;
938
43c3ffbe 939 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
51f8a12f 940 // the code to function incorrectly UNLESS we convert it to an integer. One case where
941 // PHP's loose type system works against us.
43c3ffbe 942 if(is_string($SESSION->cal_courses_shown)) {
943 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
51f8a12f 944 }
945
43c3ffbe 946 if($courseeventsfrom === NULL) {
947 $courseeventsfrom = $SESSION->cal_courses_shown;
7423f116 948 }
43c3ffbe 949 if($groupeventsfrom === NULL) {
950 $groupeventsfrom = $SESSION->cal_courses_shown;
7423f116 951 }
952
43c3ffbe 953 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
954 if(is_int($courseeventsfrom)) {
9064751b 955 $courses = array(SITEID, $courseeventsfrom);
7423f116 956 }
43c3ffbe 957 else if(is_array($courseeventsfrom)) {
958 $courses = array_keys($courseeventsfrom);
9064751b 959 $courses[] = SITEID;
7423f116 960 }
961 }
43c3ffbe 962 else if($SESSION->cal_show_course) {
963 if(is_int($courseeventsfrom)) {
964 $courses = array($courseeventsfrom);
7423f116 965 }
43c3ffbe 966 else if(is_array($courseeventsfrom)) {
967 $courses = array_keys($courseeventsfrom);
7423f116 968 }
e749554e 969 $courses = array_diff($courses, array(SITEID));
7423f116 970 }
971 else if($SESSION->cal_show_global) {
e749554e 972 $courses = array(SITEID);
7423f116 973 }
974 else {
975 $courses = false;
976 }
977
43c3ffbe 978 if($SESSION->cal_show_user || $ignorefilters) {
89adb174 979 // This doesn't work for arrays yet (maybe someday it will)
980 $user = $SESSION->cal_users_shown;
7423f116 981 }
982 else {
983 $user = false;
984 }
43c3ffbe 985 if($SESSION->cal_show_groups || $ignorefilters) {
986 if(is_int($groupeventsfrom)) {
987 $groupcourses = array($groupeventsfrom);
7423f116 988 }
43c3ffbe 989 else if(is_array($groupeventsfrom)) {
990 $groupcourses = array_keys($groupeventsfrom);
991 }
992 $grouparray = array();
993
994 // We already have the courses to examine in $courses
995 // For each course...
996 foreach($groupcourses as $courseid) {
997 // If the user is an editing teacher in there,
9c81fc35 998 if(!empty($USER->id) && isteacheredit($courseid, $USER->id)) {
da862d41 999 if (isset($courses[$courseid])) {
1000 $checkcourse = $courses[$courseid];
1001 if (!empty($checkcourse->groupmode)) {
1002 // Show events from all groups
1003 if(($grouprecords = get_groups($courseid)) !== false) {
1004 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1005 }
1006 }
7423f116 1007 }
1008 }
43c3ffbe 1009 // Otherwise show events from the group he is a member of
1010 else if(isset($USER->groupmember[$courseid])) {
1011 $grouparray[] = $USER->groupmember[$courseid];
6c9584d1 1012 }
7423f116 1013 }
43c3ffbe 1014 if(empty($grouparray)) {
1015 $group = false;
7423f116 1016 }
1017 else {
43c3ffbe 1018 $group = $grouparray;
7423f116 1019 }
1020 }
1021 else {
1022 $group = false;
1023 }
1024}
1025
1026function calendar_edit_event_allowed($event) {
1027 global $USER;
1028
1066e0dc 1029 if(empty($USER->id) || isguest($USER->id)) {
f52f7413 1030 return false;
1031 }
1032
421b0337 1033 if (isadmin($USER->id)) return true; // Admins are allowed anything
7423f116 1034
c3d3b6d4 1035 if ($event->courseid != 0 && $event->courseid != SITEID) {
7423f116 1036 // Course event, only editing teachers may... edit :P
1037 if(isteacheredit($event->courseid)) {
1038 return true;
1039 }
421b0337 1040
1041 } else if($event->courseid == 0 && $event->groupid != 0) {
7423f116 1042 // Group event
1043 $group = get_record('groups', 'id', $event->groupid);
1044 if($group === false) return false;
1045 if(isteacheredit($group->courseid)) {
1046 return true;
1047 }
421b0337 1048
1049 } else if($event->courseid == 0 && $event->groupid == 0 && $event->userid == $USER->id) {
7423f116 1050 // User event, owned by this user
1051 return true;
1052 }
1053
1054 return false;
1055}
1056
8c54cec6 1057function calendar_get_default_courses($ignoreref = false) {
9ff136e5 1058 global $USER, $CFG, $SESSION;
1059
8c54cec6 1060 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
4c7d1137 1061 return array($SESSION->cal_course_referer => 1);
9ff136e5 1062 }
7423f116 1063
1066e0dc 1064 if(empty($USER->id)) {
2ef75eee 1065 return array();
1066 }
1067
7423f116 1068 $courses = array();
9c81fc35 1069 if(!empty($USER->id) && isadmin($USER->id)) {
86f092d2 1070 if(!empty($CFG->calendar_adminseesall)) {
1071 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1072 return $courses;
1073 }
95a89225 1074 }
3696526b 1075 if(isset($USER->student) && is_array($USER->student)) {
4c7d1137 1076 $courses = $USER->student;
7423f116 1077 }
3696526b 1078 if(isset($USER->teacher) && is_array($USER->teacher)) {
4c7d1137 1079 $courses = $USER->teacher;
7423f116 1080 }
1081 return $courses;
1082}
1083
7423f116 1084function calendar_preferences_array() {
1085 return array(
86f092d2 1086 'dstpreset' => get_string('pref_dstpreset', 'calendar'),
1087 'startwday' => get_string('pref_startwday', 'calendar'),
1088 'maxevents' => get_string('pref_maxevents', 'calendar'),
1089 'lookahead' => get_string('pref_lookahead', 'calendar'),
1b0ebe79 1090 'timeformat' => get_string('pref_timeformat', 'calendar'),
7423f116 1091 );
1092}
1093
1e1ff33b 1094function calendar_preferences_button() {
1095 global $CFG, $USER;
7423f116 1096
1097 // Guests have no preferences
f52f7413 1098 if (empty($USER->id) || isguest()) {
7423f116 1099 return '';
1100 }
1101
1e1ff33b 1102 return "<form target=\"$CFG->framename\" method=\"get\" ".
1103 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1104 "<input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></form>";
7423f116 1105}
1106
8f896582 1107function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1108 $startdate = usergetdate($event->timestart);
1109 $enddate = usergetdate($event->timestart + $event->timeduration);
1110 $usermidnightstart = usergetmidnight($event->timestart);
1111
1112 if($event->timeduration) {
1113 // To avoid doing the math if one IF is enough :)
1114 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1115 }
1116 else {
1117 $usermidnightend = $usermidnightstart;
1118 }
1119
1120 // OK, now to get a meaningful display...
1121 // First of all we have to construct a human-readable date/time representation
1122
1123 if($event->timestart + $event->timeduration < $now) {
1124 // It has expired, so we don't care about duration
1125 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1126 $time = calendar_time_representation($event->timestart + $event->timeduration);
1127
1128 // This var always has the printable time representation
1129 $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>';
1130
1131 }
1132 else if($event->timeduration) {
1133 // It has a duration
1134 if($usermidnightstart == $usermidnightend) {
1135 // But it's all on the same day
1136 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1137 $timestart = calendar_time_representation($event->timestart);
1138 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1139
1140 // Set printable representation
1141 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1142 ' ('.$timestart.' -> '.$timeend.')';
1143 }
1144 else {
1145 // It spans two or more days
1146 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1147 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1148 $timestart = calendar_time_representation($event->timestart);
1149 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1150
1151 // Set printable representation
1152 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
1153 ' ('.$timestart.') -> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1154 ' ('.$timeend.')';
1155 }
1156 }
1157 else {
1158 // It's an "instantaneous" event
1159 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1160 $time = calendar_time_representation($event->timestart);
1161
1162 // Set printable representation
1163 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1164 }
09d36284 1165
8f896582 1166 return $eventtime;
1167}
09d36284 1168
86f092d2 1169function calendar_human_readable_dst($preset) {
1170 $weekdays = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
1171
1172 $options = new stdClass;
1173 $options->activate_index = ($preset->activate_index == -1) ? get_string('last', 'calendar') : get_string('nth', 'calendar', $preset->activate_index);
1174 $options->activate_weekday = ($preset->activate_day < 0) ? get_string('day', 'calendar') : get_string($weekdays[$preset->activate_day], 'calendar');
1175 $options->activate_month = date('F', mktime(0, 0, 0, $preset->activate_month, 1, 2000));
1176 $options->offset = abs($preset->apply_offset);
1177 $options->direction = $preset->apply_offset > 0 ? get_string('timeforward', 'calendar') : get_string('timerewind', 'calendar');
1178 $options->deactivate_index = ($preset->deactivate_index == -1) ? get_string('last', 'calendar') : get_string('nth', 'calendar', $preset->deactivate_index);
1179 $options->deactivate_weekday = ($preset->deactivate_day < 0) ? get_string('day', 'calendar') : get_string($weekdays[$preset->deactivate_day], 'calendar');
1180 $options->deactivate_month = date('F', mktime(0, 0, 0, $preset->deactivate_month, 1, 2000));
1181
1182 return get_string('dsthumanreadable', 'calendar', $options);
1183 //print_string('dstonthe', 'calendar')
1184 //return 'ID '.$preset->id.': DST is activated on the X of X.';
1185}
1186
1187// "Find the ($index as int, 1st, 2nd, etc, -1 = last) ($weekday as int, sunday = 0) in ($month) of ($year)"
1188function calendar_find_day_in_month($index, $weekday, $month, $year) {
1189 if($weekday == -1) {
1190 // Any day of the week will do
1191 if($index == -1) {
1192 // Last day of that month
1193 $targetday = calendar_days_in_month($month, $year);
1194 }
1195 else {
1196 // Not last day; a straight index value
1197 $targetday = $index;
1198 }
1199 }
1200 else {
1201 // We need to calculate when exactly that weekday is
1202 // Fist of all, what day of the week is the first of that month?
1203
1204 // Convert to timestamp and back to readable representation using the server's timezone;
1205 // this should be correct regardless of what the user's timezone is.
1206 $firstmonthweekday = strftime('%w', mktime(0, 0, 0, $month, 1, $year));
1207//PJ print_object('The first of '.$month.'/'.$year.' is '.$firstmonthweekday);
1208 $daysinmonth = calendar_days_in_month($month, $year);
1209
1210 // This is the first such-named weekday of the month
1211 $targetday = 1 + $weekday - $firstmonthweekday;
1212 if($targetday <= 0) {
1213 $targetday += 7;
1214 }
1215//PJ print_object('The FIRST SPECIFIC '.$weekday.' of '.$month.'/'.$year.' is on '.$targetday);
1216
1217 if($index == -1) {
1218 // To find the LAST such weekday, just keep adding 7 days at a time
1219 while($targetday + 7 <= $daysinmonth) {
1220 $targetday += 7;
1221 }
1222//PJ print_object('The LAST SPECIFIC '.$weekday.' of '.$month.'/'.$year.' is on '.$targetday);
1223 }
1224 else {
1225 // For a specific week, add as many weeks as required
1226 $targetday += $index > 1 ? ($index - 1) * 7 : 0;
1227 }
1228 }
1229
1230 return $targetday;
1231}
1232
1233function calendar_dst_update_preset($dstpreset) {
1234 $now = time();
1235
1236 // What's the date according to our user right now?
1237 $date = usergetdate($now);
1238
1239 $monthdayactivate = calendar_find_day_in_month($dstpreset->activate_index, $dstpreset->activate_day, $dstpreset->activate_month, $date['year']);
1240 $monthdaydeactivate = calendar_find_day_in_month($dstpreset->deactivate_index, $dstpreset->deactivate_day, $dstpreset->deactivate_month, $date['year']);
1241
1242 $timeactivate = make_timestamp($date['year'], $dstpreset->activate_month, $monthdayactivate, $dstpreset->activate_hour, $dstpreset->activate_minute);
1243 $timedeactivate = make_timestamp($date['year'], $dstpreset->deactivate_month, $monthdaydeactivate, $dstpreset->deactivate_hour, $dstpreset->deactivate_minute);
1244
1245 // Great... let's see where exactly we are now.
1246 if($now < $timeactivate) {
1247 print_object("<<");
1248 // DST has not been turned on this year
1249 $dstpreset->next_change = $timeactivate;
1250 // For the last change, we need to fetch the previous year's DST deactivation timestamp
1251 $monthdaydeactivate = calendar_find_day_in_month($dstpreset->deactivate_index, $dstpreset->deactivate_day, $dstpreset->deactivate_month, $date['year'] - 1);
1252 $timedeactivate = make_timestamp($date['year'] - 1, $dstpreset->deactivate_month, $monthdaydeactivate, $dstpreset->deactivate_hour, $dstpreset->deactivate_minute);
1253 $dstpreset->last_change = $timedeactivate;
1254 }
1255 else if($now < $timedeactivate) {
1256 print_object("<>");
1257 // DST is on for this year right now
1258 $dstpreset->last_change = $timeactivate;
1259 $dstpreset->next_change = $timedeactivate;
1260 }
1261 else {
1262 print_object(">>");
1263 // DST has already been turned off; we are nearing the end of the year
1264 $dstpreset->last_change = $timedeactivate;
1265 // For the next change, we need to fetch next year's DST activation timestamp
1266 $monthdayactivate = calendar_find_day_in_month($dstpreset->activate_index, $dstpreset->activate_day, $dstpreset->activate_month, $date['year'] + 1);
1267 $timeactivate = make_timestamp($date['year'] + 1, $dstpreset->activate_month, $monthdayactivate, $dstpreset->activate_hour, $dstpreset->activate_minute);
1268 $dstpreset->next_change = $timeactivate;
1269 }
1270
1271 return $dstpreset;
1272}
1273
1274function calendar_print_month_selector($name, $selected) {
1275
1276 $months = array();
1277
1278 for ($i=1; $i<=12; $i++) {
1279 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 1, 2000), '%B');
1280 }
1281
1282 choose_from_menu($months, $name, $selected, '');
1283}
1284
7423f116 1285?>