Ïîñëåäíèå íîâîñòè -> Ïîñëåäíèå äåéñòâèÿ
[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
7d50b363 145 $content .= '<table class="minicalendar">'; // Begin table
92668ad2 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
7d50b363 153 $content .= '<th>'.get_string($days[$i % 7], 'calendar').'</th>';
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.
edbe6c1b 180 $class = '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'])) {
edbe6c1b 224 $class .= ' event_global';
7423f116 225 }
226 else if(isset($typesbyday[$day]['startcourse'])) {
edbe6c1b 227 $class .= ' event_course';
7423f116 228 }
229 else if(isset($typesbyday[$day]['startgroup'])) {
edbe6c1b 230 $class .= ' event_group';
7423f116 231 }
232 else if(isset($typesbyday[$day]['startuser'])) {
edbe6c1b 233 $class .= ' event_user';
7423f116 234 }
edbe6c1b 235 $cell = '<div class="day"><a href="'.$dayhref.'" '.$popup.'>'.$day.'</a></div>';
7423f116 236 }
237 else {
edbe6c1b 238 $cell = '<div class="day">'.$day.'</div>';
7423f116 239 }
240
241 if(isset($typesbyday[$day]['durationglobal'])) {
edbe6c1b 242 $class .= ' duration_global';
7423f116 243 }
244 else if(isset($typesbyday[$day]['durationcourse'])) {
edbe6c1b 245 $class .= ' duration_course';
7423f116 246 }
247 else if(isset($typesbyday[$day]['durationgroup'])) {
edbe6c1b 248 $class .= ' duration_group';
7423f116 249 }
250 else if(isset($typesbyday[$day]['durationuser'])) {
edbe6c1b 251 $class .= ' duration_user';
7423f116 252 }
253
254 // Special visual fx for today
255 if($display->thismonth && $day == $d) {
edbe6c1b 256 $class .= ' today';
7423f116 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
2ad2cbc3 596 $content = '<table>';
7423f116 597
48f508ab 598 $content .= '<tr>';
599 if($SESSION->cal_show_global) {
edbe6c1b 600 $content .= '<td class="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) {
edbe6c1b 606 $content .= '<td class="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) {
edbe6c1b 618 $content .= '<td class="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) {
edbe6c1b 623 $content .= '<td class="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) {
edbe6c1b 633 $content .= '<td class="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 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) {
edbe6c1b 750 $content .= '<div class="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 }
9ecf051d 764 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
765 $content .= '<div class="date">'.$events[$i]->time.'</div></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;
054193be 888 if(intval(get_user_preferences('calendar_persistflt', 0))) {
889 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
890 }
02ce3848 891 }
1066e0dc 892 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
02ce3848 893 // We just logged back to our real self, update again
894 unset($SESSION->cal_users_shown);
895 unset($SESSION->cal_courses_shown);
896 unset($SESSION->cal_loggedinas);
054193be 897 if(intval(get_user_preferences('calendar_persistflt', 0))) {
898 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
899 }
02ce3848 900 }
901
7423f116 902 if(!isset($SESSION->cal_course_referer)) {
903 $SESSION->cal_course_referer = 0;
904 }
905 if(!isset($SESSION->cal_show_global)) {
906 $SESSION->cal_show_global = true;
907 }
908 if(!isset($SESSION->cal_show_groups)) {
909 $SESSION->cal_show_groups = true;
910 }
911 if(!isset($SESSION->cal_show_course)) {
912 $SESSION->cal_show_course = true;
913 }
914 if(!isset($SESSION->cal_show_user)) {
89adb174 915 $SESSION->cal_show_user = true;
7423f116 916 }
43c3ffbe 917 if(empty($SESSION->cal_courses_shown)) {
918 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
919 }
89adb174 920 if(empty($SESSION->cal_users_shown)) {
921 // The empty() instead of !isset() here makes a whole world of difference,
922 // as it will automatically change to the user's id when the user first logs
923 // in. With !isset(), it would never do that.
924 $SESSION->cal_users_shown = isset($USER->id) ? $USER->id : false;
925 }
926 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
927 // Follow the white rabbit, for example if a teacher logs in as a student
928 $SESSION->cal_users_shown = $USER->id;
929 }
7423f116 930}
931
932function calendar_overlib_html() {
9c6bf80e 933 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
934 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
7423f116 935}
936
7423f116 937function calendar_set_referring_course($courseid) {
938 global $SESSION;
939 $SESSION->cal_course_referer = intval($courseid);
940}
941
43c3ffbe 942function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
7423f116 943 global $SESSION, $USER;
944
43c3ffbe 945 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
51f8a12f 946 // the code to function incorrectly UNLESS we convert it to an integer. One case where
947 // PHP's loose type system works against us.
43c3ffbe 948 if(is_string($SESSION->cal_courses_shown)) {
949 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
51f8a12f 950 }
951
43c3ffbe 952 if($courseeventsfrom === NULL) {
953 $courseeventsfrom = $SESSION->cal_courses_shown;
7423f116 954 }
43c3ffbe 955 if($groupeventsfrom === NULL) {
956 $groupeventsfrom = $SESSION->cal_courses_shown;
7423f116 957 }
958
43c3ffbe 959 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
960 if(is_int($courseeventsfrom)) {
9064751b 961 $courses = array(SITEID, $courseeventsfrom);
7423f116 962 }
43c3ffbe 963 else if(is_array($courseeventsfrom)) {
964 $courses = array_keys($courseeventsfrom);
9064751b 965 $courses[] = SITEID;
7423f116 966 }
967 }
43c3ffbe 968 else if($SESSION->cal_show_course) {
969 if(is_int($courseeventsfrom)) {
970 $courses = array($courseeventsfrom);
7423f116 971 }
43c3ffbe 972 else if(is_array($courseeventsfrom)) {
973 $courses = array_keys($courseeventsfrom);
7423f116 974 }
e749554e 975 $courses = array_diff($courses, array(SITEID));
7423f116 976 }
977 else if($SESSION->cal_show_global) {
e749554e 978 $courses = array(SITEID);
7423f116 979 }
980 else {
981 $courses = false;
982 }
983
43c3ffbe 984 if($SESSION->cal_show_user || $ignorefilters) {
89adb174 985 // This doesn't work for arrays yet (maybe someday it will)
986 $user = $SESSION->cal_users_shown;
7423f116 987 }
988 else {
989 $user = false;
990 }
43c3ffbe 991 if($SESSION->cal_show_groups || $ignorefilters) {
992 if(is_int($groupeventsfrom)) {
993 $groupcourses = array($groupeventsfrom);
7423f116 994 }
43c3ffbe 995 else if(is_array($groupeventsfrom)) {
996 $groupcourses = array_keys($groupeventsfrom);
997 }
998 $grouparray = array();
999
1000 // We already have the courses to examine in $courses
1001 // For each course...
1002 foreach($groupcourses as $courseid) {
1003 // If the user is an editing teacher in there,
9c81fc35 1004 if(!empty($USER->id) && isteacheredit($courseid, $USER->id)) {
054193be 1005 // Show events from all groups
1006 if(($grouprecords = get_groups($courseid)) !== false) {
1007 $grouparray = array_merge($grouparray, array_keys($grouprecords));
7423f116 1008 }
1009 }
43c3ffbe 1010 // Otherwise show events from the group he is a member of
1011 else if(isset($USER->groupmember[$courseid])) {
1012 $grouparray[] = $USER->groupmember[$courseid];
6c9584d1 1013 }
7423f116 1014 }
43c3ffbe 1015 if(empty($grouparray)) {
1016 $group = false;
7423f116 1017 }
1018 else {
43c3ffbe 1019 $group = $grouparray;
7423f116 1020 }
1021 }
1022 else {
1023 $group = false;
1024 }
1025}
1026
1027function calendar_edit_event_allowed($event) {
1028 global $USER;
1029
1066e0dc 1030 if(empty($USER->id) || isguest($USER->id)) {
f52f7413 1031 return false;
1032 }
1033
421b0337 1034 if (isadmin($USER->id)) return true; // Admins are allowed anything
7423f116 1035
c3d3b6d4 1036 if ($event->courseid != 0 && $event->courseid != SITEID) {
7423f116 1037 // Course event, only editing teachers may... edit :P
1038 if(isteacheredit($event->courseid)) {
1039 return true;
1040 }
421b0337 1041
1042 } else if($event->courseid == 0 && $event->groupid != 0) {
7423f116 1043 // Group event
1044 $group = get_record('groups', 'id', $event->groupid);
1045 if($group === false) return false;
1046 if(isteacheredit($group->courseid)) {
1047 return true;
1048 }
421b0337 1049
1050 } else if($event->courseid == 0 && $event->groupid == 0 && $event->userid == $USER->id) {
7423f116 1051 // User event, owned by this user
1052 return true;
1053 }
1054
1055 return false;
1056}
1057
8c54cec6 1058function calendar_get_default_courses($ignoreref = false) {
9ff136e5 1059 global $USER, $CFG, $SESSION;
1060
8c54cec6 1061 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
4c7d1137 1062 return array($SESSION->cal_course_referer => 1);
9ff136e5 1063 }
7423f116 1064
1066e0dc 1065 if(empty($USER->id)) {
2ef75eee 1066 return array();
1067 }
1068
7423f116 1069 $courses = array();
9c81fc35 1070 if(!empty($USER->id) && isadmin($USER->id)) {
86f092d2 1071 if(!empty($CFG->calendar_adminseesall)) {
1072 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1073 return $courses;
1074 }
95a89225 1075 }
3696526b 1076 if(isset($USER->student) && is_array($USER->student)) {
4c7d1137 1077 $courses = $USER->student;
7423f116 1078 }
3696526b 1079 if(isset($USER->teacher) && is_array($USER->teacher)) {
4c7d1137 1080 $courses = $USER->teacher;
7423f116 1081 }
1082 return $courses;
1083}
1084
1e1ff33b 1085function calendar_preferences_button() {
1086 global $CFG, $USER;
7423f116 1087
1088 // Guests have no preferences
f52f7413 1089 if (empty($USER->id) || isguest()) {
7423f116 1090 return '';
1091 }
1092
1e1ff33b 1093 return "<form target=\"$CFG->framename\" method=\"get\" ".
1094 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1095 "<input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></form>";
7423f116 1096}
1097
8f896582 1098function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1099 $startdate = usergetdate($event->timestart);
1100 $enddate = usergetdate($event->timestart + $event->timeduration);
1101 $usermidnightstart = usergetmidnight($event->timestart);
1102
1103 if($event->timeduration) {
1104 // To avoid doing the math if one IF is enough :)
1105 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1106 }
1107 else {
1108 $usermidnightend = $usermidnightstart;
1109 }
1110
1111 // OK, now to get a meaningful display...
1112 // First of all we have to construct a human-readable date/time representation
1113
1114 if($event->timestart + $event->timeduration < $now) {
1115 // It has expired, so we don't care about duration
1116 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1117 $time = calendar_time_representation($event->timestart + $event->timeduration);
1118
1119 // This var always has the printable time representation
1120 $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>';
1121
1122 }
1123 else if($event->timeduration) {
1124 // It has a duration
1125 if($usermidnightstart == $usermidnightend) {
1126 // But it's all on the same day
1127 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1128 $timestart = calendar_time_representation($event->timestart);
1129 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1130
1131 // Set printable representation
1132 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
7d50b363 1133 ' ('.$timestart.' <strong>&raquo;</strong> '.$timeend.')';
8f896582 1134 }
1135 else {
1136 // It spans two or more days
1137 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1138 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1139 $timestart = calendar_time_representation($event->timestart);
1140 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1141
1142 // Set printable representation
1143 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
7d50b363 1144 ' ('.$timestart.') <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
8f896582 1145 ' ('.$timeend.')';
1146 }
1147 }
1148 else {
1149 // It's an "instantaneous" event
1150 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1151 $time = calendar_time_representation($event->timestart);
1152
1153 // Set printable representation
1154 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1155 }
09d36284 1156
8f896582 1157 return $eventtime;
1158}
09d36284 1159
86f092d2 1160function calendar_human_readable_dst($preset) {
1161 $weekdays = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
1162
1163 $options = new stdClass;
1164 $options->activate_index = ($preset->activate_index == -1) ? get_string('last', 'calendar') : get_string('nth', 'calendar', $preset->activate_index);
1165 $options->activate_weekday = ($preset->activate_day < 0) ? get_string('day', 'calendar') : get_string($weekdays[$preset->activate_day], 'calendar');
1166 $options->activate_month = date('F', mktime(0, 0, 0, $preset->activate_month, 1, 2000));
1167 $options->offset = abs($preset->apply_offset);
1168 $options->direction = $preset->apply_offset > 0 ? get_string('timeforward', 'calendar') : get_string('timerewind', 'calendar');
1169 $options->deactivate_index = ($preset->deactivate_index == -1) ? get_string('last', 'calendar') : get_string('nth', 'calendar', $preset->deactivate_index);
1170 $options->deactivate_weekday = ($preset->deactivate_day < 0) ? get_string('day', 'calendar') : get_string($weekdays[$preset->deactivate_day], 'calendar');
1171 $options->deactivate_month = date('F', mktime(0, 0, 0, $preset->deactivate_month, 1, 2000));
1172
1173 return get_string('dsthumanreadable', 'calendar', $options);
1174 //print_string('dstonthe', 'calendar')
1175 //return 'ID '.$preset->id.': DST is activated on the X of X.';
1176}
1177
1178// "Find the ($index as int, 1st, 2nd, etc, -1 = last) ($weekday as int, sunday = 0) in ($month) of ($year)"
1179function calendar_find_day_in_month($index, $weekday, $month, $year) {
1180 if($weekday == -1) {
1181 // Any day of the week will do
1182 if($index == -1) {
1183 // Last day of that month
1184 $targetday = calendar_days_in_month($month, $year);
1185 }
1186 else {
1187 // Not last day; a straight index value
1188 $targetday = $index;
1189 }
1190 }
1191 else {
1192 // We need to calculate when exactly that weekday is
1193 // Fist of all, what day of the week is the first of that month?
1194
1195 // Convert to timestamp and back to readable representation using the server's timezone;
1196 // this should be correct regardless of what the user's timezone is.
1197 $firstmonthweekday = strftime('%w', mktime(0, 0, 0, $month, 1, $year));
1198//PJ print_object('The first of '.$month.'/'.$year.' is '.$firstmonthweekday);
1199 $daysinmonth = calendar_days_in_month($month, $year);
1200
1201 // This is the first such-named weekday of the month
1202 $targetday = 1 + $weekday - $firstmonthweekday;
1203 if($targetday <= 0) {
1204 $targetday += 7;
1205 }
1206//PJ print_object('The FIRST SPECIFIC '.$weekday.' of '.$month.'/'.$year.' is on '.$targetday);
1207
1208 if($index == -1) {
1209 // To find the LAST such weekday, just keep adding 7 days at a time
1210 while($targetday + 7 <= $daysinmonth) {
1211 $targetday += 7;
1212 }
1213//PJ print_object('The LAST SPECIFIC '.$weekday.' of '.$month.'/'.$year.' is on '.$targetday);
1214 }
1215 else {
1216 // For a specific week, add as many weeks as required
1217 $targetday += $index > 1 ? ($index - 1) * 7 : 0;
1218 }
1219 }
1220
1221 return $targetday;
1222}
1223
1224function calendar_dst_update_preset($dstpreset) {
86f092d2 1225
1226 // What's the date according to our user right now?
054193be 1227 $now = time();
86f092d2 1228 $date = usergetdate($now);
1229
054193be 1230 $changes = calendar_dst_changes_for_year($date['year'], $dstpreset);
86f092d2 1231
1232 // Great... let's see where exactly we are now.
054193be 1233 if($now < $changes['activate']) {
86f092d2 1234 print_object("<<");
1235 // DST has not been turned on this year
054193be 1236 $dstpreset->next_change = $changes['activate'];
86f092d2 1237 // For the last change, we need to fetch the previous year's DST deactivation timestamp
054193be 1238 $prevchanges = calendar_dst_changes_for_year($date['year'] - 1, $dstpreset);
1239 $dstpreset->last_change = $prevchanges['deactivate'];
1240 $dstpreset->current_offset = 0;
86f092d2 1241 }
054193be 1242 else if($now < $changes['deactivate']) {
86f092d2 1243 print_object("<>");
1244 // DST is on for this year right now
054193be 1245 $dstpreset->last_change = $changes['activate'];
1246 $dstpreset->next_change = $changes['deactivate'];
1247 $dstpreset->current_offset = $dstpreset->apply_offset;
86f092d2 1248 }
1249 else {
1250 print_object(">>");
1251 // DST has already been turned off; we are nearing the end of the year
054193be 1252 $dstpreset->last_change = $changes['deactivate'];
86f092d2 1253 // For the next change, we need to fetch next year's DST activation timestamp
054193be 1254 $nextchanges = calendar_dst_changes_for_year($date['year'] + 1, $dstpreset);
1255 $dstpreset->next_change = $nextchanges['activate'];
1256 $dstpreset->current_offset = 0;
86f092d2 1257 }
1258
1259 return $dstpreset;
1260}
1261
054193be 1262function calendar_dst_changes_for_year($year, $dstpreset) {
1263 $monthdayactivate = calendar_find_day_in_month($dstpreset->activate_index, $dstpreset->activate_day, $dstpreset->activate_month, $year);
1264 $monthdaydeactivate = calendar_find_day_in_month($dstpreset->deactivate_index, $dstpreset->deactivate_day, $dstpreset->deactivate_month, $year);
1265
1266 list($activate_hour, $activate_minute) = explode(':', $dstpreset->activate_time);
1267 list($deactivate_hour, $deactivate_minute) = explode(':', $dstpreset->deactivate_time);
1268
1269 $timezone = get_user_timezone(99);
1270 $timeactivate = make_timestamp($year, $dstpreset->activate_month, $monthdayactivate, $activate_hour, $activate_minute, 0, $timezone, false);
1271 $timedeactivate = make_timestamp($year, $dstpreset->deactivate_month, $monthdaydeactivate, $deactivate_hour, $deactivate_minute, 0, $timezone, false);
1272
1273 return array('activate' => $timeactivate, 0 => $timeactivate, 'deactivate' => $timedeactivate, 1 => $timedeactivate);
1274}
1275
86f092d2 1276function calendar_print_month_selector($name, $selected) {
1277
1278 $months = array();
1279
1280 for ($i=1; $i<=12; $i++) {
1281 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 1, 2000), '%B');
1282 }
1283
1284 choose_from_menu($months, $name, $selected, '');
1285}
1286
054193be 1287function calendar_get_filters_status() {
1288 global $SESSION;
1289
1290 $status = 0;
1291 if($SESSION->cal_show_global) {
1292 $status += 1;
1293 }
1294 if($SESSION->cal_show_course) {
1295 $status += 2;
1296 }
1297 if($SESSION->cal_show_groups) {
1298 $status += 4;
1299 }
1300 if($SESSION->cal_show_user) {
1301 $status += 8;
1302 }
1303 return $status;
1304}
1305
1306function calendar_set_filters_status($packed_bitfield) {
1307 global $SESSION, $USER;
1308
1309 if(!isset($USER) || empty($USER->id)) {
1310 return false;
1311 }
1312
1313 $SESSION->cal_show_global = ($packed_bitfield & 1);
1314 $SESSION->cal_show_course = ($packed_bitfield & 2);
1315 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1316 $SESSION->cal_show_user = ($packed_bitfield & 8);
1317
1318 return true;
1319}
1320
7423f116 1321?>