Bumping version for 1.8.9 release. Thinking we might have to go to x.x.10 for the...
[moodle.git] / calendar / lib.php
blobdd914188d13ca39b4fb0586f0a6e94d1c00e43ac
1 <?php // $Id$
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@teikav.edu.gr) //
13 // Jon Papaioannou (pj@moodle.org) //
14 // //
15 // Programming and development: //
16 // Jon Papaioannou (pj@moodle.org) //
17 // //
18 // For bugs, suggestions, etc contact: //
19 // Jon Papaioannou (pj@moodle.org) //
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 /////////////////////////////////////////////////////////////////////////////
41 // These are read by the administration component to provide default values
42 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 define('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
47 define('CALENDAR_DEFAULT_WEEKEND', 65);
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');
52 if(!is_numeric($firstday)) {
53 define ('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
55 else {
56 define ('CALENDAR_STARTING_WEEKDAY', intval($firstday) % 7);
58 define ('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
59 define ('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
60 define ('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
61 define ('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 define ('CALENDAR_TF_24', '%H:%M');
63 define ('CALENDAR_TF_12', '%I:%M %p');
65 $CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
69 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
70 global $CFG, $USER;
72 $display = &New stdClass;
73 $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
74 $display->maxwday = $display->minwday + 6;
76 $content = '';
78 if(!empty($cal_month) && !empty($cal_year)) {
79 $thisdate = usergetdate(time()); // Date and time the user sees at his location
80 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
81 // Navigated to this month
82 $date = $thisdate;
83 $display->thismonth = true;
85 else {
86 // Navigated to other month, let's do a nice trick and save us a lot of work...
87 if(!checkdate($cal_month, 1, $cal_year)) {
88 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
89 $display->thismonth = true;
91 else {
92 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
93 $display->thismonth = false;
97 else {
98 $date = usergetdate(time()); // Date and time the user sees at his location
99 $display->thismonth = true;
102 // Fill in the variables we 're going to use, nice and tidy
103 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
104 $display->maxdays = calendar_days_in_month($m, $y);
106 if (get_user_timezone_offset() < 99) {
107 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
108 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
109 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
110 } else {
111 // no timezone info specified
112 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
113 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
116 $startwday = dayofweek(1, $m, $y);
118 // Align the starting weekday to fall in our display range
119 // This is simple, not foolproof.
120 if($startwday < $display->minwday) {
121 $startwday += 7;
124 // TODO: THIS IS TEMPORARY CODE!
125 // [pj] I was just reading through this and realized that I when writing this code I was probably
126 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
127 // make_timestamp would accomplish the same thing. So here goes a test:
128 //$test_start = make_timestamp($y, $m, 1);
129 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
130 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
131 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
133 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
134 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
138 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
139 $whereclause = calendar_sql_where(
140 usertime($display->tstart) - dst_offset_on($display->tstart),
141 usertime($display->tend) - dst_offset_on($display->tend),
142 $users, $groups, $courses);
144 if($whereclause === false) {
145 $events = array();
147 else {
148 $events = get_records_select('event', $whereclause, 'timestart');
151 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
152 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
153 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
154 // arguments to this function.
156 $morehref = '';
157 if(!empty($courses)) {
158 $courses = array_diff($courses, array(SITEID));
159 if(count($courses) == 1) {
160 $morehref = '&amp;course='.reset($courses);
164 // We want to have easy access by day, since the display is on a per-day basis.
165 // Arguments passed by reference.
166 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
167 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday);
169 //Accessibility: added summary and <abbr> elements.
170 ///global $CALENDARDAYS; appears to be broken.
171 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
173 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
174 $summary = get_string('tabledata', 'access', $summary);
175 $content .= '<table class="minicalendar" summary="'.$summary.'">'; // Begin table
176 $content .= '<tr class="weekdays">'; // Header row: day names
178 // Print out the names of the weekdays
179 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
180 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
181 // This uses the % operator to get the correct weekday no matter what shift we have
182 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
183 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
184 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
187 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
189 // For the table display. $week is the row; $dayweek is the column.
190 $dayweek = $startwday;
192 // Paddding (the first week may have blank days in the beginning)
193 for($i = $display->minwday; $i < $startwday; ++$i) {
194 $content .= '<td class="day">&nbsp;</td>'."\n";
197 // Now display all the calendar
198 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
199 if($dayweek > $display->maxwday) {
200 // We need to change week (table row)
201 $content .= '</tr><tr>';
202 $dayweek = $display->minwday;
205 // Reset vars
206 $cell = '';
207 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
208 // Weekend. This is true no matter what the exact range is.
209 $class = 'weekend day';
211 else {
212 // Normal working day.
213 $class = 'day';
216 // Special visual fx if an event is defined
217 if(isset($eventsbyday[$day])) {
218 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
220 // OverLib popup
221 $popupcontent = '';
222 foreach($eventsbyday[$day] as $eventid) {
223 if (!isset($events[$eventid])) {
224 continue;
226 $event = $events[$eventid];
227 if(!empty($event->modulename)) {
228 $popupicon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
229 $popupalt = $event->modulename;
231 } else if ($event->courseid == SITEID) { // Site event
232 $popupicon = $CFG->pixpath.'/c/site.gif';
233 $popupalt = '';
234 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
235 $popupicon = $CFG->pixpath.'/c/course.gif';
236 $popupalt = '';
237 } else if ($event->groupid) { // Group event
238 $popupicon = $CFG->pixpath.'/c/group.gif';
239 $popupalt = '';
240 } else if ($event->userid) { // User event
241 $popupicon = $CFG->pixpath.'/c/user.gif';
242 $popupalt = '';
244 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
247 //Accessibility: functionality moved to calendar_get_popup.
248 if($display->thismonth && $day == $d) {
249 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
250 } else {
251 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
254 // Class and cell content
255 if(isset($typesbyday[$day]['startglobal'])) {
256 $class .= ' event_global';
258 else if(isset($typesbyday[$day]['startcourse'])) {
259 $class .= ' event_course';
261 else if(isset($typesbyday[$day]['startgroup'])) {
262 $class .= ' event_group';
264 else if(isset($typesbyday[$day]['startuser'])) {
265 $class .= ' event_user';
267 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
269 else {
270 $cell = $day;
273 if(isset($typesbyday[$day]['durationglobal'])) {
274 $class .= ' duration_global';
276 else if(isset($typesbyday[$day]['durationcourse'])) {
277 $class .= ' duration_course';
279 else if(isset($typesbyday[$day]['durationgroup'])) {
280 $class .= ' duration_group';
282 else if(isset($typesbyday[$day]['durationuser'])) {
283 $class .= ' duration_user';
286 // Special visual fx for today
287 //Accessibility: hidden text for today, and popup.
288 if($display->thismonth && $day == $d) {
289 $class .= ' today';
290 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
292 if(! isset($eventsbyday[$day])) {
293 $class .= ' eventnone';
294 $popup = calendar_get_popup(true, false);
295 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
297 $cell = get_accesshide($today.' ').$cell;
300 // Just display it
301 if(!empty($class)) {
302 $class = ' class="'.$class.'"';
304 $content .= '<td'.$class.'>'.$cell."</td>\n";
307 // Paddding (the last week may have blank days at the end)
308 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
309 $content .= '<td class="day">&nbsp;</td>';
311 $content .= '</tr>'; // Last row ends
313 $content .= '</table>'; // Tabular display of days ends
315 return $content;
319 * calendar_get_popup, called at multiple points in from calendar_get_mini.
320 * Copied and modified from calendar_get_mini.
321 * @uses OverLib popup.
322 * @param $is_today bool, false except when called on the current day.
323 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
324 * @param $popupcontent string.
325 * @return $popup string, contains onmousover and onmouseout events.
327 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
328 $popupcaption = '';
329 if($is_today) {
330 $popupcaption = get_string('today', 'calendar').' ';
332 if (false === $event_timestart) {
333 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
334 $popupcontent = get_string('eventnone', 'calendar');
336 } else {
337 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
339 $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
340 $popupcaption = str_replace("'", "\'", htmlspecialchars($popupcaption));
341 $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
342 return $popup;
345 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
346 global $CFG;
348 $display = &new stdClass;
349 $display->range = $daysinfuture; // How many days in the future we 'll look
350 $display->maxevents = $maxevents;
352 $output = array();
354 // Prepare "course caching", since it may save us a lot of queries
355 $coursecache = array();
357 $processed = 0;
358 $now = time(); // We 'll need this later
359 $usermidnighttoday = usergetmidnight($now);
361 if ($fromtime) {
362 $display->tstart = $fromtime;
363 } else {
364 $display->tstart = $usermidnighttoday;
367 // This works correctly with respect to the user's DST, but it is accurate
368 // only because $fromtime is always the exact midnight of some day!
369 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
371 // Get the events matching our criteria
372 $whereclause = calendar_sql_where($display->tstart, $display->tend, $users, $groups, $courses);
373 if ($whereclause === false) {
374 $events = false;
375 } else {
376 $events = get_records_select('event', $whereclause, 'timestart');
379 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
380 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
381 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
382 // arguments to this function.
384 $morehref = '';
385 if(!empty($courses)) {
386 $courses = array_diff($courses, array(SITEID));
387 if(count($courses) == 1) {
388 $morehref = '&amp;course='.reset($courses);
392 if($events !== false) {
394 foreach($events as $event) {
396 if($processed >= $display->maxevents) {
397 break;
400 $event->time = calendar_format_event_time($event, $now, $morehref);
401 $output[] = $event;
402 ++$processed;
405 return $output;
408 function calendar_add_event_metadata($event) {
409 global $CFG;
411 //Support multilang in event->name
412 $event->name = format_string($event->name,true);
414 if(!empty($event->modulename)) { // Activity event
415 // The module name is set. I will assume that it has to be displayed, and
416 // also that it is an automatically-generated event. And of course that the
417 // fields for get_coursemodule_from_instance are set correctly.
418 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
420 if ($module === false) {
421 return;
424 $modulename = get_string('modulename', $event->modulename);
425 $eventtype = get_string($event->eventtype, $event->modulename);
426 $icon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
428 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
429 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
430 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
431 $event->cmid = $module->id;
434 } else if($event->courseid == SITEID) { // Site event
435 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/site.gif" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
436 $event->cssclass = 'event_global';
437 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
438 calendar_get_course_cached($coursecache, $event->courseid);
439 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/course.gif" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
440 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
441 $event->cssclass = 'event_course';
442 } else if ($event->groupid) { // Group event
443 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/group.gif" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
444 $event->cssclass = 'event_group';
445 } else if($event->userid) { // User event
446 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/user.gif" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
447 $event->cssclass = 'event_user';
449 return $event;
452 function calendar_print_event($event) {
453 global $CFG, $USER;
455 static $strftimetime;
457 $event = calendar_add_event_metadata($event);
458 echo '<a name="event_'.$event->id.'"></a><table class="event" cellspacing="0">';
459 echo '<tr><td class="picture">';
460 if (!empty($event->icon)) {
461 echo $event->icon;
462 } else {
463 print_spacer(16,16);
465 echo '</td>';
466 echo '<td class="topic">';
468 if (!empty($event->referer)) {
469 echo '<div class="referer">'.$event->referer.'</div>';
470 } else {
471 echo '<div class="name">'.$event->name."</div>";
473 if (!empty($event->courselink)) {
474 echo '<div class="course">'.$event->courselink.' </div>';
476 if (!empty($event->time)) {
477 echo '<span class="date">'.$event->time.'</span>';
478 } else {
479 echo '<span class="date">'.calendar_time_representation($event->timestart).'</span>';
482 echo '</td></tr>';
483 echo '<tr><td class="side">&nbsp;</td>';
484 echo '<td class="description '.$event->cssclass.'">';
485 echo format_text($event->description, FORMAT_HTML);
486 if (calendar_edit_event_allowed($event)) {
487 echo '<div class="commands">';
489 $calendarcourseid = '';
490 if (!empty($event->calendarcourseid)) {
491 $calendarcourseid = '&amp;course='.$event->calendarcourseid;
494 if (empty($event->cmid)) {
495 $editlink = CALENDAR_URL.'event.php?action=edit&amp;id='.$event->id.$calendarcourseid;
496 $deletelink = CALENDAR_URL.'event.php?action=delete&amp;id='.$event->id.$calendarcourseid;
497 } else {
498 $editlink = $CFG->wwwroot.'/course/mod.php?update='.$event->cmid.'&amp;return=true&amp;sesskey='.$USER->sesskey;
499 $deletelink = $CFG->wwwroot.'/course/mod.php?delete='.$event->cmid.'&amp;sesskey='.$USER->sesskey;;
501 echo ' <a href="'.$editlink.'"><img
502 src="'.$CFG->pixpath.'/t/edit.gif" alt="'.get_string('tt_editevent', 'calendar').'"
503 title="'.get_string('tt_editevent', 'calendar').'" /></a>';
504 echo ' <a href="'.$deletelink.'"><img
505 src="'.$CFG->pixpath.'/t/delete.gif" alt="'.get_string('tt_deleteevent', 'calendar').'"
506 title="'.get_string('tt_deleteevent', 'calendar').'" /></a>';
507 echo '</div>';
509 echo '</td></tr></table>';
513 function calendar_sql_where($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
514 $whereclause = '';
515 // Quick test
516 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
517 return false;
520 if(is_array($users) && !empty($users)) {
521 // Events from a number of users
522 if(!empty($whereclause)) $whereclause .= ' OR';
523 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
525 else if(is_numeric($users)) {
526 // Events from one user
527 if(!empty($whereclause)) $whereclause .= ' OR';
528 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
530 else if($users === true) {
531 // Events from ALL users
532 if(!empty($whereclause)) $whereclause .= ' OR';
533 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
535 else if($users === false) {
536 // No user at all, do nothing
539 if(is_array($groups) && !empty($groups)) {
540 // Events from a number of groups
541 if(!empty($whereclause)) $whereclause .= ' OR';
542 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
544 else if(is_numeric($groups)) {
545 // Events from one group
546 if(!empty($whereclause)) $whereclause .= ' OR ';
547 $whereclause .= ' groupid = '.$groups;
549 else if($groups === true) {
550 // Events from ALL groups
551 if(!empty($whereclause)) $whereclause .= ' OR ';
552 $whereclause .= ' groupid != 0';
554 // boolean false (no groups at all): we don't need to do anything
556 if(is_array($courses)) {
557 // A number of courses (maybe none at all!)
558 if(!empty($courses)) {
559 if(!empty($whereclause)) {
560 $whereclause .= ' OR';
562 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
564 else {
565 // This means NO courses, not that we don't care!
566 // No need to do anything
569 else if(is_numeric($courses)) {
570 // One course
571 if(!empty($whereclause)) $whereclause .= ' OR';
572 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
574 else if($courses === true) {
575 // Events from ALL courses
576 if(!empty($whereclause)) $whereclause .= ' OR';
577 $whereclause .= ' (groupid = 0 AND courseid != 0)';
580 // Security check: if, by now, we have NOTHING in $whereclause, then it means
581 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
582 // events no matter what. Allowing the code to proceed might return a completely
583 // valid query with only time constraints, thus selecting ALL events in that time frame!
584 if(empty($whereclause)) {
585 return false;
588 if($withduration) {
589 $timeclause = 'timestart + timeduration >= '.$tstart.' AND timestart <= '.$tend;
591 else {
592 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
594 if(!empty($whereclause)) {
595 // We have additional constraints
596 $whereclause = $timeclause.' AND ('.$whereclause.')';
598 else {
599 // Just basic time filtering
600 $whereclause = $timeclause;
603 if ($ignorehidden) {
604 $whereclause .= ' AND visible = 1';
607 return $whereclause;
610 function calendar_top_controls($type, $data) {
611 global $CFG, $CALENDARDAYS, $THEME;
612 $content = '';
613 if(!isset($data['d'])) {
614 $data['d'] = 1;
617 // Ensure course id passed if relevant
618 // Required due to changes in view/lib.php mainly (calendar_session_vars())
619 $courseid = '';
620 if (!empty($data['id'])) {
621 $courseid = '&amp;course='.$data['id'];
624 if(!checkdate($data['m'], $data['d'], $data['y'])) {
625 $time = time();
627 else {
628 $time = make_timestamp($data['y'], $data['m'], $data['d']);
630 $date = usergetdate($time);
632 $data['m'] = $date['mon'];
633 $data['y'] = $date['year'];
635 //Accessibility: calendar block controls, replaced <table> with <div>.
636 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
637 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
639 switch($type) {
640 case 'frontpage':
641 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
642 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
643 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
644 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
645 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
646 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
647 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
648 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
649 break;
650 case 'course':
651 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
652 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
653 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
654 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
655 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
656 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
657 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
658 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
659 break;
660 case 'upcoming':
661 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming"'.$courseid.'>'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
662 break;
663 case 'display':
664 $content .= '<div style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
665 break;
666 case 'month':
667 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
668 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
669 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
670 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
671 $content .= "\n".'<div class="calendar-controls">';
672 $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
673 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimemonthyear'))."</span>\n";
674 $content .= '<span class="hide"> | </span>'.calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
675 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
676 break;
677 case 'day':
678 $data['d'] = $date['mday']; // Just for convenience
679 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
680 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
681 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
682 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
683 $content .= "\n".'<div class="calendar-controls">';
684 $content .= calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
686 // Get the format string
687 $text = get_string('strftimedaydate');
689 // Regexp hackery to make a link out of the month/year part
690 $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);
691 $text = ereg_replace('(F.+Y|Y.+F|Y.+m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
693 // Replace with actual values and lose any day leading zero
694 $text = userdate($time, $text);
695 // Print the actual thing
696 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
698 $content .= '<span class="hide"> | </span>'. calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
699 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
700 break;
702 return $content;
705 function calendar_filter_controls($type, $vars = NULL, $course = NULL) {
706 global $CFG, $SESSION, $USER;
708 $groupevents = true;
709 $getvars = '';
711 $id = optional_param( 'id',0,PARAM_INT );
713 switch($type) {
714 case 'event':
715 case 'upcoming':
716 case 'day':
717 case 'month':
718 $getvars = '&amp;from='.$type;
719 break;
720 case 'course':
721 if ($id > 0) {
722 $getvars = '&amp;from=course&amp;id='.$id;
723 } else {
724 $getvars = '&amp;from=course';
726 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
727 $groupevents = false;
729 break;
732 if (!empty($vars)) {
733 $getvars .= '&amp;'.$vars;
736 $content = '<table>';
738 $content .= '<tr>';
739 if($SESSION->cal_show_global) {
740 $content .= '<td class="event_global" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
741 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
743 else {
744 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
745 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
747 if($SESSION->cal_show_course) {
748 $content .= '<td class="event_course" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
749 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
751 else {
752 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
753 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
756 if(!empty($USER->id) && !isguest()) {
757 $content .= "</tr>\n<tr>";
759 if($groupevents) {
760 // This course MIGHT have group events defined, so show the filter
761 if($SESSION->cal_show_groups) {
762 $content .= '<td class="event_group" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
763 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
764 } else {
765 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
766 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
768 if ($SESSION->cal_show_user) {
769 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
770 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
771 } else {
772 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
773 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
776 } else {
777 // This course CANNOT have group events, so lose the filter
778 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
780 if($SESSION->cal_show_user) {
781 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
782 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
783 } else {
784 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
785 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
789 $content .= "</tr>\n</table>\n";
791 return $content;
794 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
796 static $shortformat;
797 if(empty($shortformat)) {
798 $shortformat = get_string('strftimedayshort');
801 if($now === false) {
802 $now = time();
805 // To have it in one place, if a change is needed
806 $formal = userdate($tstamp, $shortformat);
808 $datestamp = usergetdate($tstamp);
809 $datenow = usergetdate($now);
811 if($usecommonwords == false) {
812 // We don't want words, just a date
813 return $formal;
815 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
816 // Today
817 return get_string('today', 'calendar');
819 else if(
820 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
821 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
823 // Yesterday
824 return get_string('yesterday', 'calendar');
826 else if(
827 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
828 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
830 // Tomorrow
831 return get_string('tomorrow', 'calendar');
833 else {
834 return $formal;
838 function calendar_time_representation($time) {
839 static $langtimeformat = NULL;
840 if($langtimeformat === NULL) {
841 $langtimeformat = get_string('strftimetime');
843 $timeformat = get_user_preferences('calendar_timeformat');
844 if(empty($timeformat)){
845 $timeformat = get_config(NULL,'calendar_site_timeformat');
847 // The ? is needed because the preference might be present, but empty
848 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
851 function calendar_get_link_href($linkbase, $d, $m, $y) {
852 if(empty($linkbase)) return '';
853 $paramstr = '';
854 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
855 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
856 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
857 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
858 return $linkbase.$paramstr;
861 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
862 $href = calendar_get_link_href($linkbase, $d, $m, $y);
863 if(empty($href)) return $text;
864 return '<a href="'.$href.'">'.$text.'</a>';
868 * Build and return a previous month HTML link, with an arrow.
869 * @param string $text The text label.
870 * @param string $linkbase The URL stub.
871 * @param int $d $m $y Day of month, month and year numbers.
872 * @param bool $accesshide Default visible, or hide from all except screenreaders.
873 * @return string HTML string.
875 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
876 $href = calendar_get_link_href($linkbase, $d, $m, $y);
877 if(empty($href)) return $text;
878 return link_arrow_left($text, $href, $accesshide, 'previous');
882 * Build and return a next month HTML link, with an arrow.
883 * @param string $text The text label.
884 * @param string $linkbase The URL stub.
885 * @param int $d $m $y Day of month, month and year numbers.
886 * @param bool $accesshide Default visible, or hide from all except screenreaders.
887 * @return string HTML string.
889 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
890 $href = calendar_get_link_href($linkbase, $d, $m, $y);
891 if(empty($href)) return $text;
892 return link_arrow_right($text, $href, $accesshide, 'next');
895 function calendar_wday_name($englishname) {
896 return get_string(strtolower($englishname), 'calendar');
899 function calendar_days_in_month($month, $year) {
900 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
903 function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
904 $content = '';
905 $lines = count($events);
906 if (!$lines) {
907 return $content;
910 for ($i = 0; $i < $lines; ++$i) {
911 if (!isset($events[$i]->time)) { // Just for robustness
912 continue;
914 $events[$i] = calendar_add_event_metadata($events[$i]);
915 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
916 if (!empty($events[$i]->referer)) {
917 // That's an activity event, so let's provide the hyperlink
918 $content .= $events[$i]->referer;
919 } else {
920 if(!empty($linkhref)) {
921 $ed = usergetdate($events[$i]->timestart);
922 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
923 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
925 else {
926 $content .= $events[$i]->name;
929 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
930 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
931 if ($i < $lines - 1) $content .= '<hr />';
934 return $content;
937 function calendar_add_month($month, $year) {
938 if($month == 12) {
939 return array(1, $year + 1);
941 else {
942 return array($month + 1, $year);
946 function calendar_sub_month($month, $year) {
947 if($month == 1) {
948 return array(12, $year - 1);
950 else {
951 return array($month - 1, $year);
955 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday) {
956 $eventsbyday = array();
957 $typesbyday = array();
958 $durationbyday = array();
960 if($events === false) {
961 return;
964 foreach($events as $event) {
966 $startdate = usergetdate($event->timestart);
967 $enddate = usergetdate($event->timestart + $event->timeduration);
969 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
970 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
971 // Out of bounds
972 continue;
975 $eventdaystart = intval($startdate['mday']);
977 if($startdate['mon'] == $month && $startdate['year'] == $year) {
978 // Give the event to its day
979 $eventsbyday[$eventdaystart][] = $event->id;
981 // Mark the day as having such an event
982 if($event->courseid == SITEID && $event->groupid == 0) {
983 $typesbyday[$eventdaystart]['startglobal'] = true;
985 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
986 $typesbyday[$eventdaystart]['startcourse'] = true;
988 else if($event->groupid) {
989 $typesbyday[$eventdaystart]['startgroup'] = true;
991 else if($event->userid) {
992 $typesbyday[$eventdaystart]['startuser'] = true;
996 if($event->timeduration == 0) {
997 // Proceed with the next
998 continue;
1001 // The event starts on $month $year or before. So...
1002 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1004 // Also, it ends on $month $year or later...
1005 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1007 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1008 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1009 $durationbyday[$i][] = $event->id;
1010 if($event->courseid == SITEID && $event->groupid == 0) {
1011 $typesbyday[$i]['durationglobal'] = true;
1013 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1014 $typesbyday[$i]['durationcourse'] = true;
1016 else if($event->groupid) {
1017 $typesbyday[$i]['durationgroup'] = true;
1019 else if($event->userid) {
1020 $typesbyday[$i]['durationuser'] = true;
1025 return;
1028 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1029 $module = get_coursemodule_from_instance($modulename, $instance);
1031 if($module === false) return false;
1032 if(!calendar_get_course_cached($coursecache, $module->course)) {
1033 return false;
1035 return $module;
1038 function calendar_get_course_cached(&$coursecache, $courseid) {
1039 if(!isset($coursecache[$courseid])) {
1040 $coursecache[$courseid] = get_record('course', 'id', $courseid);
1042 return $coursecache[$courseid];
1045 function calendar_session_vars() {
1046 global $SESSION, $USER;
1048 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
1049 // We just logged in as someone else, update the filtering
1050 unset($SESSION->cal_users_shown);
1051 unset($SESSION->cal_courses_shown);
1052 $SESSION->cal_loggedinas = true;
1053 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1054 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1057 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
1058 // We just logged back to our real self, update again
1059 unset($SESSION->cal_users_shown);
1060 unset($SESSION->cal_courses_shown);
1061 unset($SESSION->cal_loggedinas);
1062 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1063 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1067 if(!isset($SESSION->cal_course_referer)) {
1068 $SESSION->cal_course_referer = 0;
1070 if(!isset($SESSION->cal_show_global)) {
1071 $SESSION->cal_show_global = true;
1073 if(!isset($SESSION->cal_show_groups)) {
1074 $SESSION->cal_show_groups = true;
1076 if(!isset($SESSION->cal_show_course)) {
1077 $SESSION->cal_show_course = true;
1079 if(!isset($SESSION->cal_show_user)) {
1080 $SESSION->cal_show_user = true;
1082 // if(empty($SESSION->cal_courses_shown)) {
1083 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1085 if(empty($SESSION->cal_users_shown)) {
1086 // The empty() instead of !isset() here makes a whole world of difference,
1087 // as it will automatically change to the user's id when the user first logs
1088 // in. With !isset(), it would never do that.
1089 $SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false;
1091 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
1092 // Follow the white rabbit, for example if a teacher logs in as a student
1093 $SESSION->cal_users_shown = $USER->id;
1097 function calendar_overlib_html() {
1098 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
1099 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
1102 function calendar_set_referring_course($courseid) {
1103 global $SESSION;
1104 $SESSION->cal_course_referer = intval($courseid);
1107 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1108 global $SESSION, $USER, $CFG;
1110 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1111 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1112 // PHP's loose type system works against us.
1113 if(is_string($SESSION->cal_courses_shown)) {
1114 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1117 if($courseeventsfrom === NULL) {
1118 $courseeventsfrom = $SESSION->cal_courses_shown;
1120 if($groupeventsfrom === NULL) {
1121 $groupeventsfrom = $SESSION->cal_courses_shown;
1124 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1125 if(is_int($courseeventsfrom)) {
1126 $courses = array(SITEID, $courseeventsfrom);
1128 else if(is_array($courseeventsfrom)) {
1129 $courses = array_keys($courseeventsfrom);
1130 $courses[] = SITEID;
1133 else if($SESSION->cal_show_course) {
1134 if(is_int($courseeventsfrom)) {
1135 $courses = array($courseeventsfrom);
1137 else if(is_array($courseeventsfrom)) {
1138 $courses = array_keys($courseeventsfrom);
1140 $courses = array_diff($courses, array(SITEID));
1142 else if($SESSION->cal_show_global) {
1143 $courses = array(SITEID);
1145 else {
1146 $courses = false;
1148 //BUG 6130 clean $courses array as SESSION has bad entries.
1149 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1150 if (is_array($courses)) {
1151 foreach ($courses as $index => $value) {
1152 if (empty($value)) unset($courses[$index]);
1156 if($SESSION->cal_show_user || $ignorefilters) {
1157 // This doesn't work for arrays yet (maybe someday it will)
1158 $user = $SESSION->cal_users_shown;
1160 else {
1161 $user = false;
1163 if($SESSION->cal_show_groups || $ignorefilters) {
1164 if(is_int($groupeventsfrom)) {
1165 $groupcourses = array($groupeventsfrom);
1167 else if(is_array($groupeventsfrom)) {
1168 $groupcourses = array_keys($groupeventsfrom);
1171 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1172 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($CFG->calendar_adminseesall)) {
1173 $group = true;
1175 else {
1176 $grouparray = array();
1178 // We already have the courses to examine in $courses
1179 // For each course...
1181 foreach($groupcourses as $courseid) {
1183 // If the user is an editing teacher in there,
1184 if(!empty($USER->id) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
1185 // If this course has groups, show events from all of them
1186 if(is_int($groupeventsfrom)) {
1187 $courserecord = get_record('course', 'id', $courseid);
1188 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1189 $groupids[] = $courseid;
1192 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
1193 $groupids[] = $courseid;
1197 // Otherwise (not editing teacher) show events from the group he is a member of
1198 else if(isset($USER->groupmember[$courseid])) {
1199 //changed to 2D array
1200 foreach ($USER->groupmember[$courseid] as $groupid){
1201 $rec = get_record('groups_courses_groups', 'courseid', $courseid, 'groupid', $groupid);
1202 //$grouparray[] = $groupid;
1203 $grouparray[] = $rec->id;
1207 if (!empty($groupids)) {
1208 $sql = "SELECT groupid, groupid
1209 FROM {$CFG->prefix}groups_courses_groups
1210 WHERE courseid IN (".implode(',', $groupids).')';
1212 if ($grouprecords= get_records_sql($sql)) {
1213 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1217 if(empty($grouparray)) {
1218 $group = false;
1220 else {
1221 $group = $grouparray;
1226 else {
1227 $group = false;
1231 function calendar_edit_event_allowed($event) {
1233 global $USER;
1235 // can not be using guest account
1236 if ($USER->username == "guest") {
1237 return false;
1240 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1241 // if user has manageentries at site level, return true
1242 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1243 return true;
1246 // if groupid is set, it's definitely a group event
1247 if ($event->groupid) {
1248 //TODO:check.
1249 if (! groups_group_exists($event->groupid)) {
1250 return false;
1253 // this is ok because if you have this capability at course level, you should be able
1254 // to edit group calendar too
1255 // there is no need to check membership, because if you have this capability
1256 // you will have a role in this group context
1257 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
1258 } else if ($event->courseid) {
1259 // if groupid is not set, but course is set,
1260 // it's definiely a course event
1261 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1262 } else if ($event->userid && $event->userid == $USER->id) {
1263 // if course is not set, but userid id set, it's a user event
1264 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1266 return false;
1269 function calendar_get_default_courses($ignoreref = false) {
1270 global $USER, $CFG, $SESSION;
1272 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1273 return array($SESSION->cal_course_referer => 1);
1276 if(empty($USER->id)) {
1277 return array();
1280 $courses = array();
1281 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1282 if (!empty($CFG->calendar_adminseesall)) {
1283 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1284 return $courses;
1288 if (isset($CFG->adminseesall)) {
1289 $courses = get_my_courses($USER->id, null, null, $CFG->adminseesall);
1291 else {
1292 $courses = get_my_courses($USER->id, null, null, false);
1295 return $courses;
1298 function calendar_preferences_button() {
1299 global $CFG, $USER;
1301 // Guests have no preferences
1302 if (empty($USER->id) || isguest()) {
1303 return '';
1306 return "<form $CFG->frametarget method=\"get\" ".
1307 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1308 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1311 function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1312 $startdate = usergetdate($event->timestart);
1313 $enddate = usergetdate($event->timestart + $event->timeduration);
1314 $usermidnightstart = usergetmidnight($event->timestart);
1316 if($event->timeduration) {
1317 // To avoid doing the math if one IF is enough :)
1318 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1320 else {
1321 $usermidnightend = $usermidnightstart;
1324 // OK, now to get a meaningful display...
1325 // First of all we have to construct a human-readable date/time representation
1327 if($event->timestart + $event->timeduration < $now) {
1328 // It has expired, so we don't care about duration
1329 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1330 $time = calendar_time_representation($event->timestart + $event->timeduration);
1332 // This var always has the printable time representation
1333 $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>';
1336 else if($event->timeduration) {
1337 // It has a duration
1338 if($usermidnightstart == $usermidnightend) {
1339 // But it's all on the same day
1340 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1341 $timestart = calendar_time_representation($event->timestart);
1342 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1344 // Set printable representation
1345 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1346 ' ('.$timestart.' <strong>&raquo;</strong> '.$timeend.')';
1348 else {
1349 // It spans two or more days
1350 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1351 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1352 $timestart = calendar_time_representation($event->timestart);
1353 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1355 // Set printable representation
1356 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
1357 ' ('.$timestart.') <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1358 ' ('.$timeend.')';
1361 else {
1362 // It's an "instantaneous" event
1363 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1364 $time = calendar_time_representation($event->timestart);
1366 // Set printable representation
1367 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1370 return $eventtime;
1373 function calendar_print_month_selector($name, $selected) {
1375 $months = array();
1377 for ($i=1; $i<=12; $i++) {
1378 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1381 choose_from_menu($months, $name, $selected, '');
1384 function calendar_get_filters_status() {
1385 global $SESSION;
1387 $status = 0;
1388 if($SESSION->cal_show_global) {
1389 $status += 1;
1391 if($SESSION->cal_show_course) {
1392 $status += 2;
1394 if($SESSION->cal_show_groups) {
1395 $status += 4;
1397 if($SESSION->cal_show_user) {
1398 $status += 8;
1400 return $status;
1403 function calendar_set_filters_status($packed_bitfield) {
1404 global $SESSION, $USER;
1406 if(!isset($USER) || empty($USER->id)) {
1407 return false;
1410 $SESSION->cal_show_global = ($packed_bitfield & 1);
1411 $SESSION->cal_show_course = ($packed_bitfield & 2);
1412 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1413 $SESSION->cal_show_user = ($packed_bitfield & 8);
1415 return true;
1418 function calendar_get_allowed_types(&$allowed) {
1419 global $USER, $CFG, $SESSION;
1420 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1421 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1422 $allowed->groups = false; // This may change just below
1423 $allowed->courses = false; // This may change just below
1424 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1426 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer))) {
1427 $course = get_record('course', 'id', $SESSION->cal_course_referer);
1429 $allowed->courses = array($course->id => 1);
1431 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1432 $allowed->groups = get_groups($SESSION->cal_course_referer);
1438 * see if user can add calendar entries at all
1439 * used to print the "New Event" button
1440 * @return bool
1442 function calendar_user_can_add_event() {
1443 calendar_get_allowed_types($allowed);
1444 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);