MDL-8857
[moodle-linuxchix.git] / calendar / lib.php
blobaf5e5c50ed4d616eb200a159f3984d6d31506b97
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');
67 // Initialize the session variables here to be sure
68 calendar_session_vars();
70 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
71 global $CFG, $USER;
73 $display = &New stdClass;
74 $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
75 $display->maxwday = $display->minwday + 6;
77 $content = '';
79 if(!empty($cal_month) && !empty($cal_year)) {
80 $thisdate = usergetdate(time()); // Date and time the user sees at his location
81 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
82 // Navigated to this month
83 $date = $thisdate;
84 $display->thismonth = true;
86 else {
87 // Navigated to other month, let's do a nice trick and save us a lot of work...
88 if(!checkdate($cal_month, 1, $cal_year)) {
89 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
90 $display->thismonth = true;
92 else {
93 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
94 $display->thismonth = false;
98 else {
99 $date = usergetdate(time()); // Date and time the user sees at his location
100 $display->thismonth = true;
103 // Fill in the variables we 're going to use, nice and tidy
104 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
105 $display->maxdays = calendar_days_in_month($m, $y);
107 if (get_user_timezone_offset() < 99) {
108 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
109 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
110 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
111 } else {
112 // no timezone info specified
113 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
114 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
117 $startwday = dayofweek(1, $m, $y);
119 // Align the starting weekday to fall in our display range
120 // This is simple, not foolproof.
121 if($startwday < $display->minwday) {
122 $startwday += 7;
125 // TODO: THIS IS TEMPORARY CODE!
126 // [pj] I was just reading through this and realized that I when writing this code I was probably
127 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
128 // make_timestamp would accomplish the same thing. So here goes a test:
129 //$test_start = make_timestamp($y, $m, 1);
130 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
131 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
132 //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);
134 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
135 //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);
139 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
140 $whereclause = calendar_sql_where(
141 usertime($display->tstart) - dst_offset_on($display->tstart),
142 usertime($display->tend) - dst_offset_on($display->tend),
143 $users, $groups, $courses);
145 if($whereclause === false) {
146 $events = array();
148 else {
149 $events = get_records_select('event', $whereclause, 'timestart');
152 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
153 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
154 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
155 // arguments to this function.
157 $morehref = '';
158 if(!empty($courses)) {
159 $courses = array_diff($courses, array(SITEID));
160 if(count($courses) == 1) {
161 $morehref = '&amp;course='.reset($courses);
165 // We want to have easy access by day, since the display is on a per-day basis.
166 // Arguments passed by reference.
167 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
168 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday);
170 //Accessibility: added summary and <abbr> elements.
171 ///global $CALENDARDAYS; appears to be broken.
172 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
174 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
175 $summary = get_string('tabledata', 'access', $summary);
176 $content .= '<table class="minicalendar" summary="'.$summary.'">'; // Begin table
177 $content .= '<tr class="weekdays">'; // Header row: day names
179 // Print out the names of the weekdays
180 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
181 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
182 // This uses the % operator to get the correct weekday no matter what shift we have
183 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
184 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
185 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
188 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
190 // For the table display. $week is the row; $dayweek is the column.
191 $dayweek = $startwday;
193 // Paddding (the first week may have blank days in the beginning)
194 for($i = $display->minwday; $i < $startwday; ++$i) {
195 $content .= '<td>&nbsp;</td>'."\n";
198 // Now display all the calendar
199 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
200 if($dayweek > $display->maxwday) {
201 // We need to change week (table row)
202 $content .= '</tr><tr>';
203 $dayweek = $display->minwday;
206 // Reset vars
207 $cell = '';
208 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
209 // Weekend. This is true no matter what the exact range is.
210 $class = 'weekend day';
212 else {
213 // Normal working day.
214 $class = 'day';
217 // Special visual fx if an event is defined
218 if(isset($eventsbyday[$day])) {
219 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
221 // OverLib popup
222 $popupcontent = '';
223 foreach($eventsbyday[$day] as $eventid) {
224 if (!isset($events[$eventid])) {
225 continue;
227 $event = $events[$eventid];
228 if(!empty($event->modulename)) {
229 $popupicon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
230 $popupalt = $event->modulename;
232 } else if ($event->courseid == SITEID) { // Site event
233 $popupicon = $CFG->pixpath.'/c/site.gif';
234 $popupalt = '';
235 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
236 $popupicon = $CFG->pixpath.'/c/course.gif';
237 $popupalt = '';
238 } else if ($event->groupid) { // Group event
239 $popupicon = $CFG->pixpath.'/c/group.gif';
240 $popupalt = '';
241 } else if ($event->userid) { // User event
242 $popupicon = $CFG->pixpath.'/c/user.gif';
243 $popupalt = '';
245 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
248 //Accessibility: functionality moved to calendar_get_popup.
249 if($display->thismonth && $day == $d) {
250 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
251 } else {
252 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
255 // Class and cell content
256 if(isset($typesbyday[$day]['startglobal'])) {
257 $class .= ' event_global';
259 else if(isset($typesbyday[$day]['startcourse'])) {
260 $class .= ' event_course';
262 else if(isset($typesbyday[$day]['startgroup'])) {
263 $class .= ' event_group';
265 else if(isset($typesbyday[$day]['startuser'])) {
266 $class .= ' event_user';
268 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
270 else {
271 $cell = $day;
274 if(isset($typesbyday[$day]['durationglobal'])) {
275 $class .= ' duration_global';
277 else if(isset($typesbyday[$day]['durationcourse'])) {
278 $class .= ' duration_course';
280 else if(isset($typesbyday[$day]['durationgroup'])) {
281 $class .= ' duration_group';
283 else if(isset($typesbyday[$day]['durationuser'])) {
284 $class .= ' duration_user';
287 // Special visual fx for today
288 //Accessibility: hidden text for today, and popup.
289 if($display->thismonth && $day == $d) {
290 $class .= ' today';
291 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
293 if(! isset($eventsbyday[$day])) {
294 $class .= ' eventnone';
295 $popup = calendar_get_popup(true, false);
296 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
298 $cell = '<span class="accesshide">'.$today.' </span>'.$cell;
301 // Just display it
302 if(!empty($class)) {
303 $class = ' class="'.$class.'"';
305 $content .= '<td'.$class.'>'.$cell."</td>\n";
308 // Paddding (the last week may have blank days at the end)
309 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
310 $content .= '<td>&nbsp;</td>';
312 $content .= '</tr>'; // Last row ends
314 $content .= '</table>'; // Tabular display of days ends
316 return $content;
320 * calendar_get_popup, called at multiple points in from calendar_get_mini.
321 * Copied and modified from calendar_get_mini.
322 * @uses OverLib popup.
323 * @param $is_today bool, false except when called on the current day.
324 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
325 * @param $popupcontent string.
326 * @return $popup string, contains onmousover and onmouseout events.
328 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
329 $popupcaption = '';
330 if($is_today) {
331 $popupcaption = get_string('today', 'calendar').' ';
333 if (false === $event_timestart) {
334 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
335 $popupcontent = get_string('eventnone', 'calendar');
337 } else {
338 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
340 $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
341 $popupcaption = str_replace("'", "\'", htmlspecialchars($popupcaption));
342 $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
343 return $popup;
346 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
347 global $CFG;
349 $display = &new stdClass;
350 $display->range = $daysinfuture; // How many days in the future we 'll look
351 $display->maxevents = $maxevents;
353 $output = array();
355 // Prepare "course caching", since it may save us a lot of queries
356 $coursecache = array();
358 $processed = 0;
359 $now = time(); // We 'll need this later
360 $usermidnighttoday = usergetmidnight($now);
362 if ($fromtime) {
363 $display->tstart = $fromtime;
364 } else {
365 $display->tstart = $usermidnighttoday;
368 // This works correctly with respect to the user's DST, but it is accurate
369 // only because $fromtime is always the exact midnight of some day!
370 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
372 // Get the events matching our criteria
373 $whereclause = calendar_sql_where($display->tstart, $display->tend, $users, $groups, $courses);
374 if ($whereclause === false) {
375 $events = false;
376 } else {
377 $events = get_records_select('event', $whereclause, 'timestart');
380 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
381 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
382 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
383 // arguments to this function.
385 $morehref = '';
386 if(!empty($courses)) {
387 $courses = array_diff($courses, array(SITEID));
388 if(count($courses) == 1) {
389 $morehref = '&amp;course='.reset($courses);
393 if($events !== false) {
395 foreach($events as $event) {
397 if($processed >= $display->maxevents) {
398 break;
401 $event->time = calendar_format_event_time($event, $now, $morehref);
402 $output[] = $event;
403 ++$processed;
406 return $output;
409 function calendar_add_event_metadata($event) {
410 global $CFG;
412 //Support multilang in event->name
413 $event->name = format_string($event->name,true);
415 if(!empty($event->modulename)) { // Activity event
416 // The module name is set. I will assume that it has to be displayed, and
417 // also that it is an automatically-generated event. And of course that the
418 // fields for get_coursemodule_from_instance are set correctly.
419 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
421 if ($module === false) {
422 return;
425 $modulename = get_string('modulename', $event->modulename);
426 $eventtype = get_string($event->eventtype, $event->modulename);
427 $icon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
429 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
430 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
431 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
432 $event->cmid = $module->id;
435 } else if($event->courseid == SITEID) { // Site event
436 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/site.gif" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
437 $event->cssclass = 'event_global';
438 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
439 calendar_get_course_cached($coursecache, $event->courseid);
440 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/course.gif" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
441 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
442 $event->cssclass = 'event_course';
443 } else if ($event->groupid) { // Group event
444 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/group.gif" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
445 $event->cssclass = 'event_group';
446 } else if($event->userid) { // User event
447 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/user.gif" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
448 $event->cssclass = 'event_user';
450 return $event;
453 function calendar_print_event($event) {
454 global $CFG, $USER;
456 static $strftimetime;
458 $event = calendar_add_event_metadata($event);
459 echo '<a name="event_'.$event->id.'"></a><table class="event" cellspacing="0">';
460 echo '<tr><td class="picture">';
461 if (!empty($event->icon)) {
462 echo $event->icon;
463 } else {
464 print_spacer(16,16);
466 echo '</td>';
467 echo '<td class="topic">';
469 if (!empty($event->referer)) {
470 echo '<div class="referer">'.$event->referer.'</div>';
471 } else {
472 echo '<div class="name">'.$event->name."</div>";
474 if (!empty($event->courselink)) {
475 echo '<div class="course">'.$event->courselink.' </div>';
477 if (!empty($event->time)) {
478 echo '<span class="date">'.$event->time.'</span>';
479 } else {
480 echo '<span class="date">'.calendar_time_representation($event->timestart).'</span>';
483 echo '</td></tr>';
484 echo '<tr><td class="side">&nbsp;</td>';
485 echo '<td class="description '.$event->cssclass.'">';
486 echo format_text($event->description, FORMAT_HTML);
487 if (calendar_edit_event_allowed($event)) {
488 echo '<div class="commands">';
489 if (empty($event->cmid)) {
490 $editlink = CALENDAR_URL.'event.php?action=edit&amp;id='.$event->id;
491 $deletelink = CALENDAR_URL.'event.php?action=delete&amp;id='.$event->id;
492 } else {
493 $editlink = $CFG->wwwroot.'/course/mod.php?update='.$event->cmid.'&amp;return=true&amp;sesskey='.$USER->sesskey;
494 $deletelink = $CFG->wwwroot.'/course/mod.php?delete='.$event->cmid.'&amp;sesskey='.$USER->sesskey;;
496 echo ' <a href="'.$editlink.'"><img
497 src="'.$CFG->pixpath.'/t/edit.gif" alt="'.get_string('tt_editevent', 'calendar').'"
498 title="'.get_string('tt_editevent', 'calendar').'" /></a>';
499 echo ' <a href="'.$deletelink.'"><img
500 src="'.$CFG->pixpath.'/t/delete.gif" alt="'.get_string('tt_deleteevent', 'calendar').'"
501 title="'.get_string('tt_deleteevent', 'calendar').'" /></a>';
502 echo '</div>';
504 echo '</td></tr></table>';
508 function calendar_sql_where($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
509 $whereclause = '';
510 // Quick test
511 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
512 return false;
515 if(is_array($users) && !empty($users)) {
516 // Events from a number of users
517 if(!empty($whereclause)) $whereclause .= ' OR';
518 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
520 else if(is_numeric($users)) {
521 // Events from one user
522 if(!empty($whereclause)) $whereclause .= ' OR';
523 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
525 else if($users === true) {
526 // Events from ALL users
527 if(!empty($whereclause)) $whereclause .= ' OR';
528 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
530 else if($users === false) {
531 // No user at all, do nothing
534 if(is_array($groups) && !empty($groups)) {
535 // Events from a number of groups
536 if(!empty($whereclause)) $whereclause .= ' OR';
537 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
539 else if(is_numeric($groups)) {
540 // Events from one group
541 if(!empty($whereclause)) $whereclause .= ' OR ';
542 $whereclause .= ' groupid = '.$groups;
544 else if($groups === true) {
545 // Events from ALL groups
546 if(!empty($whereclause)) $whereclause .= ' OR ';
547 $whereclause .= ' groupid != 0';
549 // boolean false (no groups at all): we don't need to do anything
551 if(is_array($courses)) {
552 // A number of courses (maybe none at all!)
553 if(!empty($courses)) {
554 if(!empty($whereclause)) {
555 $whereclause .= ' OR';
557 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
559 else {
560 // This means NO courses, not that we don't care!
561 // No need to do anything
564 else if(is_numeric($courses)) {
565 // One course
566 if(!empty($whereclause)) $whereclause .= ' OR';
567 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
569 else if($courses === true) {
570 // Events from ALL courses
571 if(!empty($whereclause)) $whereclause .= ' OR';
572 $whereclause .= ' (groupid = 0 AND courseid != 0)';
575 // Security check: if, by now, we have NOTHING in $whereclause, then it means
576 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
577 // events no matter what. Allowing the code to proceed might return a completely
578 // valid query with only time constraints, thus selecting ALL events in that time frame!
579 if(empty($whereclause)) {
580 return false;
583 if($withduration) {
584 $timeclause = 'timestart + timeduration >= '.$tstart.' AND timestart <= '.$tend;
586 else {
587 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
589 if(!empty($whereclause)) {
590 // We have additional constraints
591 $whereclause = $timeclause.' AND ('.$whereclause.')';
593 else {
594 // Just basic time filtering
595 $whereclause = $timeclause;
598 if ($ignorehidden) {
599 $whereclause .= ' AND visible = 1';
602 return $whereclause;
605 function calendar_top_controls($type, $data) {
606 global $CFG, $CALENDARDAYS, $THEME;
607 $content = '';
608 if(!isset($data['d'])) {
609 $data['d'] = 1;
612 if(!checkdate($data['m'], $data['d'], $data['y'])) {
613 $time = time();
615 else {
616 $time = make_timestamp($data['y'], $data['m'], $data['d']);
618 $date = usergetdate($time);
620 $data['m'] = $date['mon'];
621 $data['y'] = $date['year'];
623 //Accessibility: calendar block controls, replaced <table> with <div>.
624 check_theme_arrows();
625 $nexttext = $THEME->rarrow .'<span class="accesshide">'.get_string('monthnext','access').'</span>';
626 $prevtext = $THEME->larrow .'<span class="accesshide">'.get_string('monthprev','access').'</span>';
628 switch($type) {
629 case 'frontpage':
630 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
631 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
632 $nextlink = calendar_get_link_tag($nexttext, 'index.php?', 0, $nextmonth, $nextyear);
633 $prevlink = calendar_get_link_tag($prevtext, 'index.php?', 0, $prevmonth, $prevyear);
634 $content .= '<div class="calendar-controls">';
635 $content .= '<span class="previous" title="'.get_string('monthprev','access').'">'.$prevlink."</span>\n";
636 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
637 $content .= '<span class="hide"> | </span><span class="next" title="'.get_string('monthnext','access').'">'.$nextlink."</span>\n";
638 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
639 break;
640 case 'course':
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_tag($nexttext, 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear);
644 $prevlink = calendar_get_link_tag($prevtext, 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear);
645 $content .= '<div class="calendar-controls">';
646 $content .= '<span class="previous" title="'.get_string('monthprev','access').'">'.$prevlink."</span>\n";
647 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;course='.$data['id'].'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
648 $content .= '<span class="hide"> | </span><span class="next" title="'.get_string('monthnext','access').'">'.$nextlink."</span>\n";
649 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
650 break;
651 case 'upcoming':
652 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
653 break;
654 case 'display':
655 $content .= '<div style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
656 break;
657 case 'month':
658 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
659 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
660 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
661 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
662 $content .= '<div class="calendar-controls">';
663 $content .= '<span class="previous"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $prevmonth, $prevyear)."\"> $THEME->larrow ".userdate($prevdate, get_string('strftimemonthyear')).'</a></span>';
664 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimemonthyear'))."</span>\n";
665 $content .= '<span class="hide"> | </span><span class="next"><a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $nextmonth, $nextyear).'">'.userdate($nextdate, get_string('strftimemonthyear'))." $THEME->rarrow</a></span>\n";
666 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
667 break;
668 case 'day':
669 $data['d'] = $date['mday']; // Just for convenience
670 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
671 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
672 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
673 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
674 $content .= '<div class="calendar-controls">';
675 $content .= '<span class="previous"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year'])."\">$THEME->larrow ".$prevname."</a></span>\n";
677 // Get the format string
678 $text = get_string('strftimedaydate');
680 // Regexp hackery to make a link out of the month/year part
681 $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);
682 $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);
684 // Replace with actual values and lose any day leading zero
685 $text = userdate($time, $text);
686 // Print the actual thing
687 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
689 $content .= '<span class="hide"> | </span><span class="next"><a href="'.calendar_get_link_href('view.php?view=day&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']).'">'.$nextname." $THEME->rarrow</a></span>\n";
690 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
691 break;
693 return $content;
696 function calendar_filter_controls($type, $vars = NULL, $course = NULL) {
697 global $CFG, $SESSION, $USER;
699 $groupevents = true;
700 $getvars = '';
702 $id = optional_param( 'id',0,PARAM_INT );
704 switch($type) {
705 case 'event':
706 case 'upcoming':
707 case 'day':
708 case 'month':
709 $getvars = '&amp;from='.$type;
710 break;
711 case 'course':
712 if ($id > 0) {
713 $getvars = '&amp;from=course&amp;id='.$id;
714 } else {
715 $getvars = '&amp;from=course';
717 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
718 $groupevents = false;
720 break;
723 if (!empty($vars)) {
724 $getvars .= '&amp;'.$vars;
727 $content = '<table>';
729 $content .= '<tr>';
730 if($SESSION->cal_show_global) {
731 $content .= '<td class="event_global" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
732 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
734 else {
735 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
736 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('globalevents', 'calendar').'</a></td>'."\n";
738 if($SESSION->cal_show_course) {
739 $content .= '<td class="event_course" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
740 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
742 else {
743 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
744 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('courseevents', 'calendar').'</a></td>'."\n";
747 if(!empty($USER->id) && !isguest()) {
748 $content .= "</tr>\n<tr>";
750 if($groupevents) {
751 // This course MIGHT have group events defined, so show the filter
752 if($SESSION->cal_show_groups) {
753 $content .= '<td class="event_group" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
754 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
755 } else {
756 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
757 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('groupevents', 'calendar').'</a></td>'."\n";
759 if ($SESSION->cal_show_user) {
760 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
761 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
762 } else {
763 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
764 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
767 } else {
768 // This course CANNOT have group events, so lose the filter
769 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
771 if($SESSION->cal_show_user) {
772 $content .= '<td class="event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" /></td>';
773 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
774 } else {
775 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" /></td>';
776 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('userevents', 'calendar').'</a></td>'."\n";
780 $content .= "</tr>\n</table>\n";
782 return $content;
785 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
787 static $shortformat;
788 if(empty($shortformat)) {
789 $shortformat = get_string('strftimedayshort');
792 if($now === false) {
793 $now = time();
796 // To have it in one place, if a change is needed
797 $formal = userdate($tstamp, $shortformat);
799 $datestamp = usergetdate($tstamp);
800 $datenow = usergetdate($now);
802 if($usecommonwords == false) {
803 // We don't want words, just a date
804 return $formal;
806 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
807 // Today
808 return get_string('today', 'calendar');
810 else if(
811 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
812 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
814 // Yesterday
815 return get_string('yesterday', 'calendar');
817 else if(
818 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
819 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
821 // Tomorrow
822 return get_string('tomorrow', 'calendar');
824 else {
825 return $formal;
829 function calendar_time_representation($time) {
830 static $langtimeformat = NULL;
831 if($langtimeformat === NULL) {
832 $langtimeformat = get_string('strftimetime');
834 $timeformat = get_user_preferences('calendar_timeformat');
835 if(empty($timeformat)){
836 $timeformat = get_config(NULL,'calendar_site_timeformat');
838 // The ? is needed because the preference might be present, but empty
839 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
842 function calendar_get_link_href($linkbase, $d, $m, $y) {
843 if(empty($linkbase)) return '';
844 $paramstr = '';
845 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
846 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
847 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
848 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
849 return $linkbase.$paramstr;
852 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
853 $href = calendar_get_link_href($linkbase, $d, $m, $y);
854 if(empty($href)) return $text;
855 return '<a href="'.$href.'">'.$text.'</a>';
858 function calendar_wday_name($englishname) {
859 return get_string(strtolower($englishname), 'calendar');
862 function calendar_days_in_month($month, $year) {
863 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
866 function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
867 $content = '';
868 $lines = count($events);
869 if (!$lines) {
870 return $content;
873 for ($i = 0; $i < $lines; ++$i) {
874 if (!isset($events[$i]->time)) { // Just for robustness
875 continue;
877 $events[$i] = calendar_add_event_metadata($events[$i]);
878 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
879 if (!empty($events[$i]->referer)) {
880 // That's an activity event, so let's provide the hyperlink
881 $content .= $events[$i]->referer;
882 } else {
883 if(!empty($linkhref)) {
884 $ed = usergetdate($events[$i]->timestart);
885 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
886 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
888 else {
889 $content .= $events[$i]->name;
892 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
893 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
894 if ($i < $lines - 1) $content .= '<hr />';
897 return $content;
900 function calendar_add_month($month, $year) {
901 if($month == 12) {
902 return array(1, $year + 1);
904 else {
905 return array($month + 1, $year);
909 function calendar_sub_month($month, $year) {
910 if($month == 1) {
911 return array(12, $year - 1);
913 else {
914 return array($month - 1, $year);
918 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday) {
919 $eventsbyday = array();
920 $typesbyday = array();
921 $durationbyday = array();
923 if($events === false) {
924 return;
927 foreach($events as $event) {
929 $startdate = usergetdate($event->timestart);
930 $enddate = usergetdate($event->timestart + $event->timeduration);
932 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
933 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
934 // Out of bounds
935 continue;
938 $eventdaystart = intval($startdate['mday']);
940 if($startdate['mon'] == $month && $startdate['year'] == $year) {
941 // Give the event to its day
942 $eventsbyday[$eventdaystart][] = $event->id;
944 // Mark the day as having such an event
945 if($event->courseid == SITEID && $event->groupid == 0) {
946 $typesbyday[$eventdaystart]['startglobal'] = true;
948 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
949 $typesbyday[$eventdaystart]['startcourse'] = true;
951 else if($event->groupid) {
952 $typesbyday[$eventdaystart]['startgroup'] = true;
954 else if($event->userid) {
955 $typesbyday[$eventdaystart]['startuser'] = true;
959 if($event->timeduration == 0) {
960 // Proceed with the next
961 continue;
964 // The event starts on $month $year or before. So...
965 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
967 // Also, it ends on $month $year or later...
968 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
970 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
971 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
972 $durationbyday[$i][] = $event->id;
973 if($event->courseid == SITEID && $event->groupid == 0) {
974 $typesbyday[$i]['durationglobal'] = true;
976 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
977 $typesbyday[$i]['durationcourse'] = true;
979 else if($event->groupid) {
980 $typesbyday[$i]['durationgroup'] = true;
982 else if($event->userid) {
983 $typesbyday[$i]['durationuser'] = true;
988 return;
991 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
992 $module = get_coursemodule_from_instance($modulename, $instance);
994 if($module === false) return false;
995 if(!calendar_get_course_cached($coursecache, $module->course)) {
996 return false;
998 return $module;
1001 function calendar_get_course_cached(&$coursecache, $courseid) {
1002 if(!isset($coursecache[$courseid])) {
1003 $coursecache[$courseid] = get_record('course', 'id', $courseid);
1005 return $coursecache[$courseid];
1008 function calendar_session_vars() {
1009 global $SESSION, $USER;
1011 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
1012 // We just logged in as someone else, update the filtering
1013 unset($SESSION->cal_users_shown);
1014 unset($SESSION->cal_courses_shown);
1015 $SESSION->cal_loggedinas = true;
1016 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1017 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1020 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
1021 // We just logged back to our real self, update again
1022 unset($SESSION->cal_users_shown);
1023 unset($SESSION->cal_courses_shown);
1024 unset($SESSION->cal_loggedinas);
1025 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1026 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1030 if(!isset($SESSION->cal_course_referer)) {
1031 $SESSION->cal_course_referer = 0;
1033 if(!isset($SESSION->cal_show_global)) {
1034 $SESSION->cal_show_global = true;
1036 if(!isset($SESSION->cal_show_groups)) {
1037 $SESSION->cal_show_groups = true;
1039 if(!isset($SESSION->cal_show_course)) {
1040 $SESSION->cal_show_course = true;
1042 if(!isset($SESSION->cal_show_user)) {
1043 $SESSION->cal_show_user = true;
1045 if(empty($SESSION->cal_courses_shown)) {
1046 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1048 if(empty($SESSION->cal_users_shown)) {
1049 // The empty() instead of !isset() here makes a whole world of difference,
1050 // as it will automatically change to the user's id when the user first logs
1051 // in. With !isset(), it would never do that.
1052 $SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false;
1054 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
1055 // Follow the white rabbit, for example if a teacher logs in as a student
1056 $SESSION->cal_users_shown = $USER->id;
1060 function calendar_overlib_html() {
1061 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
1062 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
1065 function calendar_set_referring_course($courseid) {
1066 global $SESSION;
1067 $SESSION->cal_course_referer = intval($courseid);
1070 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1071 global $SESSION, $USER, $CFG;
1073 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1074 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1075 // PHP's loose type system works against us.
1076 if(is_string($SESSION->cal_courses_shown)) {
1077 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1080 if($courseeventsfrom === NULL) {
1081 $courseeventsfrom = $SESSION->cal_courses_shown;
1083 if($groupeventsfrom === NULL) {
1084 $groupeventsfrom = $SESSION->cal_courses_shown;
1087 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1088 if(is_int($courseeventsfrom)) {
1089 $courses = array(SITEID, $courseeventsfrom);
1091 else if(is_array($courseeventsfrom)) {
1092 $courses = array_keys($courseeventsfrom);
1093 $courses[] = SITEID;
1096 else if($SESSION->cal_show_course) {
1097 if(is_int($courseeventsfrom)) {
1098 $courses = array($courseeventsfrom);
1100 else if(is_array($courseeventsfrom)) {
1101 $courses = array_keys($courseeventsfrom);
1103 $courses = array_diff($courses, array(SITEID));
1105 else if($SESSION->cal_show_global) {
1106 $courses = array(SITEID);
1108 else {
1109 $courses = false;
1111 //BUG 6130 clean $courses array as SESSION has bad entries.
1112 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1113 foreach ($courses as $index => $value) {
1114 if (empty($value)) unset($courses[$index]);
1117 if($SESSION->cal_show_user || $ignorefilters) {
1118 // This doesn't work for arrays yet (maybe someday it will)
1119 $user = $SESSION->cal_users_shown;
1121 else {
1122 $user = false;
1124 if($SESSION->cal_show_groups || $ignorefilters) {
1125 if(is_int($groupeventsfrom)) {
1126 $groupcourses = array($groupeventsfrom);
1128 else if(is_array($groupeventsfrom)) {
1129 $groupcourses = array_keys($groupeventsfrom);
1132 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1133 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($CFG->calendar_adminseesall)) {
1134 $group = true;
1136 else {
1137 $grouparray = array();
1138 $groupmodes = NULL;
1140 // We already have the courses to examine in $courses
1141 // For each course...
1142 foreach($groupcourses as $courseid) {
1144 // If the user is an editing teacher in there,
1145 if(!empty($USER->id) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) {
1147 // The first time we get in here, retrieve all groupmodes at once
1148 if($groupmodes === NULL) {
1149 $groupmodes = get_records_list('course', 'id', implode(',', $groupcourses), '', 'id, groupmode, groupmodeforce');
1152 // If this course has groups, show events from all of them
1153 if(isset($groupmodes[$courseid]) && ($groupmodes[$courseid]->groupmode != NOGROUPS || !$groupmodes[$courseid]->groupmodeforce) && ($grouprecords = get_groups($courseid)) !== false) {
1154 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1158 // Otherwise (not editing teacher) show events from the group he is a member of
1159 else if(isset($USER->groupmember[$courseid])) {
1160 //changed to 2D array
1161 foreach ($USER->groupmember[$courseid] as $groupid){
1162 $grouparray[] = $groupid;
1166 if(empty($grouparray)) {
1167 $group = false;
1169 else {
1170 $group = $grouparray;
1175 else {
1176 $group = false;
1180 function calendar_edit_event_allowed($event) {
1182 global $USER;
1184 // can not be using guest account
1185 if ($USER->username == "guest") {
1186 return false;
1189 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1190 // if user has manageentries at site level, return true
1191 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1192 return true;
1195 // editting userid account
1196 if ($event->userid) {
1197 if ($event->userid == $USER->id) {
1198 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1200 } else if ($event->groupid) {
1201 //TODO:check.
1202 if (! groups_group_exists($event->groupid)) {
1203 return false;
1206 // this is ok because if you have this capability at course level, you should be able
1207 // to edit group calendar too
1208 // there is no need to check membership, because if you have this capability
1209 // you will have a role in this group context
1210 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
1211 } else if ($event->courseid) {
1212 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1214 return false;
1217 function calendar_get_default_courses($ignoreref = false) {
1218 global $USER, $CFG, $SESSION;
1220 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1221 return array($SESSION->cal_course_referer => 1);
1224 if(empty($USER->id)) {
1225 return array();
1228 $courses = array();
1229 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1230 if (!empty($CFG->calendar_adminseesall)) {
1231 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1232 return $courses;
1236 // find all course this student can view
1237 if ($allcourses = get_my_courses($USER->id, 'visible DESC, sortorder ASC', '*', true)) {
1238 foreach ($allcourses as $courseid => $acourse) {
1239 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1240 // let's try to see if there is any direct assignments on this context
1241 // one can have multiple assignments
1242 // just use anyone that has something, or else use empty string
1243 // i am not even sure enrolment type is needed here, seems like only the array keys are needed
1244 // just keeping this code for safety
1245 if ($roleassign = get_records_sql("SELECT * FROM {$CFG->prefix}role_assignments
1246 WHERE contextid = $context->id
1247 AND userid = $USER->id")) {
1248 foreach ($roleassign as $rid => $rs) {
1249 if (!empty($rs->enrol)) {
1250 $courses[$courseid] = $rs->enrol;
1251 break;
1257 return $courses;
1260 function calendar_preferences_button() {
1261 global $CFG, $USER;
1263 // Guests have no preferences
1264 if (empty($USER->id) || isguest()) {
1265 return '';
1268 return "<form $CFG->frametarget method=\"get\" ".
1269 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1270 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1273 function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true) {
1274 $startdate = usergetdate($event->timestart);
1275 $enddate = usergetdate($event->timestart + $event->timeduration);
1276 $usermidnightstart = usergetmidnight($event->timestart);
1278 if($event->timeduration) {
1279 // To avoid doing the math if one IF is enough :)
1280 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1282 else {
1283 $usermidnightend = $usermidnightstart;
1286 // OK, now to get a meaningful display...
1287 // First of all we have to construct a human-readable date/time representation
1289 if($event->timestart + $event->timeduration < $now) {
1290 // It has expired, so we don't care about duration
1291 $day = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1292 $time = calendar_time_representation($event->timestart + $event->timeduration);
1294 // This var always has the printable time representation
1295 $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>';
1298 else if($event->timeduration) {
1299 // It has a duration
1300 if($usermidnightstart == $usermidnightend) {
1301 // But it's all on the same day
1302 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1303 $timestart = calendar_time_representation($event->timestart);
1304 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1306 // Set printable representation
1307 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1308 ' ('.$timestart.' <strong>&raquo;</strong> '.$timeend.')';
1310 else {
1311 // It spans two or more days
1312 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords);
1313 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords);
1314 $timestart = calendar_time_representation($event->timestart);
1315 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1317 // Set printable representation
1318 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
1319 ' ('.$timestart.') <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1320 ' ('.$timeend.')';
1323 else {
1324 // It's an "instantaneous" event
1325 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1326 $time = calendar_time_representation($event->timestart);
1328 // Set printable representation
1329 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).' ('.$time.')';
1332 return $eventtime;
1335 function calendar_print_month_selector($name, $selected) {
1337 $months = array();
1339 for ($i=1; $i<=12; $i++) {
1340 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 1, 2000), '%B');
1343 choose_from_menu($months, $name, $selected, '');
1346 function calendar_get_filters_status() {
1347 global $SESSION;
1349 $status = 0;
1350 if($SESSION->cal_show_global) {
1351 $status += 1;
1353 if($SESSION->cal_show_course) {
1354 $status += 2;
1356 if($SESSION->cal_show_groups) {
1357 $status += 4;
1359 if($SESSION->cal_show_user) {
1360 $status += 8;
1362 return $status;
1365 function calendar_set_filters_status($packed_bitfield) {
1366 global $SESSION, $USER;
1368 if(!isset($USER) || empty($USER->id)) {
1369 return false;
1372 $SESSION->cal_show_global = ($packed_bitfield & 1);
1373 $SESSION->cal_show_course = ($packed_bitfield & 2);
1374 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1375 $SESSION->cal_show_user = ($packed_bitfield & 8);
1377 return true;