weekly release 2.3dev (blame stronk7 for 0202 mistake)
[moodle.git] / calendar / lib.php
CommitLineData
93c91ee4 1<?php
7423f116 2
3/////////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Calendar extension //
8// //
9// Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10// //
11// Designed by: //
bdcb26b7 12// Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13// Jon Papaioannou (pj@moodle.org) //
7423f116 14// //
15// Programming and development: //
bdcb26b7 16// Jon Papaioannou (pj@moodle.org) //
7423f116 17// //
18// For bugs, suggestions, etc contact: //
bdcb26b7 19// Jon Papaioannou (pj@moodle.org) //
7423f116 20// //
21// The current module was developed at the University of Macedonia //
22// (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23// The aim of this project is to provide additional and improved //
24// functionality to the Asynchronous Distance Education service that the //
25// Greek School Network deploys. //
26// //
27// This program is free software; you can redistribute it and/or modify //
28// it under the terms of the GNU General Public License as published by //
29// the Free Software Foundation; either version 2 of the License, or //
30// (at your option) any later version. //
31// //
32// This program is distributed in the hope that it will be useful, //
33// but WITHOUT ANY WARRANTY; without even the implied warranty of //
34// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35// GNU General Public License for more details: //
36// //
37// http://www.gnu.org/copyleft/gpl.html //
38// //
39/////////////////////////////////////////////////////////////////////////////
40
bb4a2e85 41// These are read by the administration component to provide default values
42define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
45// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
46// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
47define('CALENDAR_DEFAULT_WEEKEND', 65);
76d9df3f
SH
48define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
49define('CALENDAR_TF_24', '%H:%M');
50define('CALENDAR_TF_12', '%I:%M %p');
bb4a2e85 51
797cedc7
SH
52define('CALENDAR_EVENT_GLOBAL', 1);
53define('CALENDAR_EVENT_COURSE', 2);
54define('CALENDAR_EVENT_GROUP', 4);
55define('CALENDAR_EVENT_USER', 8);
56
76d9df3f
SH
57/**
58 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
59 * @deprecated
60 */
61define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
7423f116 62
797cedc7
SH
63/**
64 * Return the days of the week
65 *
66 * @return array
67 */
68function calendar_get_days() {
69 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
70}
f2bffd9e 71
76d9df3f
SH
72/**
73 * Gets the first day of the week
74 *
75 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
76 *
77 * @return int
78 */
79function calendar_get_starting_weekday() {
80 global $CFG;
37d87d11 81
76d9df3f
SH
82 if (isset($CFG->calendar_startwday)) {
83 $firstday = $CFG->calendar_startwday;
84 } else {
0a933ae6 85 $firstday = get_string('firstdayofweek', 'langconfig');
76d9df3f
SH
86 }
87
88 if(!is_numeric($firstday)) {
89 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
90 } else {
91 return intval($firstday) % 7;
92 }
93}
bd119567 94
0f927f1e 95/**
14236cbd 96 * Generates the HTML for a miniature calendar
0f927f1e
SH
97 *
98 * @global core_renderer $OUTPUT
14236cbd
SH
99 * @param array $courses
100 * @param array $groups
101 * @param array $users
102 * @param int $cal_month
103 * @param int $cal_year
0f927f1e
SH
104 * @return string
105 */
7423f116 106function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
6b608f8f 107 global $CFG, $USER, $OUTPUT;
7423f116 108
dd97c328 109 $display = new stdClass;
76d9df3f 110 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
7423f116 111 $display->maxwday = $display->minwday + 6;
112
113 $content = '';
114
115 if(!empty($cal_month) && !empty($cal_year)) {
116 $thisdate = usergetdate(time()); // Date and time the user sees at his location
117 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
118 // Navigated to this month
119 $date = $thisdate;
120 $display->thismonth = true;
36dc3b71 121 } else {
7423f116 122 // Navigated to other month, let's do a nice trick and save us a lot of work...
123 if(!checkdate($cal_month, 1, $cal_year)) {
124 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
125 $display->thismonth = true;
36dc3b71 126 } else {
7423f116 127 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
128 $display->thismonth = false;
129 }
130 }
36dc3b71 131 } else {
7423f116 132 $date = usergetdate(time()); // Date and time the user sees at his location
133 $display->thismonth = true;
134 }
135
136 // Fill in the variables we 're going to use, nice and tidy
137 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
138 $display->maxdays = calendar_days_in_month($m, $y);
139
d6198903 140 if (get_user_timezone_offset() < 99) {
141 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
61240489 142 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
143 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
d6198903 144 } else {
145 // no timezone info specified
61240489 146 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
147 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
d6198903 148 }
7423f116 149
69244b91 150 $startwday = dayofweek(1, $m, $y);
7423f116 151
152 // Align the starting weekday to fall in our display range
153 // This is simple, not foolproof.
154 if($startwday < $display->minwday) {
155 $startwday += 7;
156 }
157
c0b507d1 158 // TODO: THIS IS TEMPORARY CODE!
159 // [pj] I was just reading through this and realized that I when writing this code I was probably
160 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
161 // make_timestamp would accomplish the same thing. So here goes a test:
1747ee05 162 //$test_start = make_timestamp($y, $m, 1);
163 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
164 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
165 //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);
166 //}
167 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
168 //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);
169 //}
c0b507d1 170
171
7423f116 172 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
8263f802 173 $events = calendar_get_events(
d3555a2f 174 usertime($display->tstart) - dst_offset_on($display->tstart),
175 usertime($display->tend) - dst_offset_on($display->tend),
176 $users, $groups, $courses);
7423f116 177
b4892fa2 178 // Set event course class for course events
179 if (!empty($events)) {
13534ef7 180 foreach ($events as $eventid => $event) {
13534ef7
ML
181 if (!empty($event->modulename)) {
182 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
183 if (!groups_course_module_visible($cm)) {
184 unset($events[$eventid]);
185 }
186 }
b4892fa2 187 }
188 }
6619eba4 189
c635dcda 190 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 191 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 192 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
193 // arguments to this function.
194
0f927f1e 195 $hrefparams = array();
7bd1677c 196 if(!empty($courses)) {
e749554e 197 $courses = array_diff($courses, array(SITEID));
7bd1677c 198 if(count($courses) == 1) {
0f927f1e 199 $hrefparams['course'] = reset($courses);
7bd1677c 200 }
c635dcda 201 }
202
7423f116 203 // We want to have easy access by day, since the display is on a per-day basis.
204 // Arguments passed by reference.
7b38bfa6 205 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
7c50db30 206 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
7423f116 207
f20c4d02 208 //Accessibility: added summary and <abbr> elements.
797cedc7 209 $days_title = calendar_get_days();
f20c4d02 210
2a06efcc 211 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
212 $summary = get_string('tabledata', 'access', $summary);
90723839 213 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
f136e4c5 214 $content .= '<tr class="weekdays">'; // Header row: day names
7423f116 215
216 // Print out the names of the weekdays
217 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
218 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
219 // This uses the % operator to get the correct weekday no matter what shift we have
220 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
f20c4d02 221 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
222 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
7423f116 223 }
224
f136e4c5 225 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
7423f116 226
227 // For the table display. $week is the row; $dayweek is the column.
7423f116 228 $dayweek = $startwday;
229
230 // Paddding (the first week may have blank days in the beginning)
231 for($i = $display->minwday; $i < $startwday; ++$i) {
3bfd8bc8 232 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
7423f116 233 }
234
797cedc7
SH
235 $weekend = CALENDAR_DEFAULT_WEEKEND;
236 if (isset($CFG->calendar_weekend)) {
237 $weekend = intval($CFG->calendar_weekend);
238 }
239
7423f116 240 // Now display all the calendar
241 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
242 if($dayweek > $display->maxwday) {
243 // We need to change week (table row)
d56d4e23 244 $content .= '</tr><tr>';
7423f116 245 $dayweek = $display->minwday;
7423f116 246 }
92668ad2 247
7423f116 248 // Reset vars
7423f116 249 $cell = '';
797cedc7 250 if ($weekend & (1 << ($dayweek % 7))) {
7423f116 251 // Weekend. This is true no matter what the exact range is.
e2aa618b 252 $class = 'weekend day';
90723839 253 } else {
7423f116 254 // Normal working day.
e2aa618b 255 $class = 'day';
7423f116 256 }
257
258 // Special visual fx if an event is defined
259 if(isset($eventsbyday[$day])) {
90723839 260 $class .= ' hasevent';
0f927f1e
SH
261 $hrefparams['view'] = 'day';
262 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
f434283f 263
7423f116 264 $popupcontent = '';
265 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 266 if (!isset($events[$eventid])) {
267 continue;
4e17c6f3 268 }
41d30a8e 269 $event = $events[$eventid];
0f927f1e
SH
270 $popupalt = '';
271 $component = 'moodle';
41d30a8e 272 if(!empty($event->modulename)) {
0f927f1e 273 $popupicon = 'icon';
41d30a8e 274 $popupalt = $event->modulename;
0f927f1e 275 $component = $event->modulename;
9064751b 276 } else if ($event->courseid == SITEID) { // Site event
0f927f1e 277 $popupicon = 'c/site';
c3d3b6d4 278 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
0f927f1e 279 $popupicon = 'c/course';
41d30a8e 280 } else if ($event->groupid) { // Group event
0f927f1e 281 $popupicon = 'c/group';
41d30a8e 282 } else if ($event->userid) { // User event
0f927f1e 283 $popupicon = 'c/user';
4e17c6f3 284 }
1d5bd3d2 285
0f927f1e 286 $dayhref->set_anchor('event_'.$event->id);
1d5bd3d2 287
0f927f1e 288 $popupcontent .= html_writer::start_tag('div');
adc3cfc7 289 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
0f927f1e
SH
290 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
291 $popupcontent .= html_writer::end_tag('div');
7423f116 292 }
e295df44 293
b5c42e70 294 //Accessibility: functionality moved to calendar_get_popup.
295 if($display->thismonth && $day == $d) {
450a0a7d 296 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
b5c42e70 297 } else {
450a0a7d 298 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
e295df44 299 }
f20c4d02 300
7423f116 301 // Class and cell content
302 if(isset($typesbyday[$day]['startglobal'])) {
90723839
SH
303 $class .= ' calendar_event_global';
304 } else if(isset($typesbyday[$day]['startcourse'])) {
305 $class .= ' calendar_event_course';
306 } else if(isset($typesbyday[$day]['startgroup'])) {
307 $class .= ' calendar_event_group';
308 } else if(isset($typesbyday[$day]['startuser'])) {
309 $class .= ' calendar_event_user';
7423f116 310 }
0f927f1e 311 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
90723839 312 } else {
05fcc5fd 313 $cell = $day;
7423f116 314 }
315
90723839
SH
316 $durationclass = false;
317 if (isset($typesbyday[$day]['durationglobal'])) {
318 $durationclass = ' duration_global';
319 } else if(isset($typesbyday[$day]['durationcourse'])) {
320 $durationclass = ' duration_course';
321 } else if(isset($typesbyday[$day]['durationgroup'])) {
322 $durationclass = ' duration_group';
323 } else if(isset($typesbyday[$day]['durationuser'])) {
324 $durationclass = ' duration_user';
7423f116 325 }
90723839
SH
326 if ($durationclass) {
327 $class .= ' duration '.$durationclass;
7423f116 328 }
329
b4892fa2 330 // If event has a class set then add it to the table day <td> tag
331 // Note: only one colour for minicalendar
332 if(isset($eventsbyday[$day])) {
333 foreach($eventsbyday[$day] as $eventid) {
334 if (!isset($events[$eventid])) {
335 continue;
336 }
337 $event = $events[$eventid];
338 if (!empty($event->class)) {
339 $class .= ' '.$event->class;
340 }
341 break;
342 }
343 }
344
7423f116 345 // Special visual fx for today
450a0a7d 346 //Accessibility: hidden text for today, and popup.
7423f116 347 if($display->thismonth && $day == $d) {
edbe6c1b 348 $class .= ' today';
b5c42e70 349 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
e295df44 350
b5c42e70 351 if(! isset($eventsbyday[$day])) {
450a0a7d 352 $class .= ' eventnone';
353 $popup = calendar_get_popup(true, false);
354 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
b5c42e70 355 }
f79f2494 356 $cell = get_accesshide($today.' ').$cell;
7423f116 357 }
358
359 // Just display it
92668ad2 360 if(!empty($class)) {
d56d4e23 361 $class = ' class="'.$class.'"';
92668ad2 362 }
363 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 364 }
365
366 // Paddding (the last week may have blank days at the end)
367 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
3bfd8bc8 368 $content .= '<td class="dayblank">&nbsp;</td>';
7423f116 369 }
370 $content .= '</tr>'; // Last row ends
371
f136e4c5 372 $content .= '</table>'; // Tabular display of days ends
7423f116 373
374 return $content;
375}
376
b5c42e70 377/**
378 * calendar_get_popup, called at multiple points in from calendar_get_mini.
379 * Copied and modified from calendar_get_mini.
33e48a1a 380 * @global moodle_page $PAGE
b5c42e70 381 * @param $is_today bool, false except when called on the current day.
382 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
383 * @param $popupcontent string.
e295df44 384 * @return $popup string, contains onmousover and onmouseout events.
b5c42e70 385 */
386function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
458eb0d1 387 global $PAGE;
388 static $popupcount;
389 if ($popupcount === null) {
390 $popupcount = 1;
391 }
b5c42e70 392 $popupcaption = '';
393 if($is_today) {
394 $popupcaption = get_string('today', 'calendar').' ';
395 }
396 if (false === $event_timestart) {
397 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
398 $popupcontent = get_string('eventnone', 'calendar');
450a0a7d 399
b5c42e70 400 } else {
401 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
402 }
458eb0d1 403 $id = 'calendar_tooltip_'.$popupcount;
33e48a1a 404 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
bdbae764 405
458eb0d1 406 $popupcount++;
407 return 'id="'.$id.'"';
b5c42e70 408}
409
9958a08c 410function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
62d11d77 411 global $CFG, $COURSE, $DB;
7423f116 412
dd97c328 413 $display = new stdClass;
7423f116 414 $display->range = $daysinfuture; // How many days in the future we 'll look
415 $display->maxevents = $maxevents;
416
417 $output = array();
418
419 // Prepare "course caching", since it may save us a lot of queries
420 $coursecache = array();
421
422 $processed = 0;
423 $now = time(); // We 'll need this later
9d567178 424 $usermidnighttoday = usergetmidnight($now);
7423f116 425
9958a08c 426 if ($fromtime) {
427 $display->tstart = $fromtime;
428 } else {
9d567178 429 $display->tstart = $usermidnighttoday;
9958a08c 430 }
7423f116 431
1f473774 432 // This works correctly with respect to the user's DST, but it is accurate
433 // only because $fromtime is always the exact midnight of some day!
434 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
7423f116 435
436 // Get the events matching our criteria
8263f802 437 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
7423f116 438
c635dcda 439 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 440 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 441 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
442 // arguments to this function.
443
0f927f1e 444 $hrefparams = array();
7bd1677c 445 if(!empty($courses)) {
e749554e 446 $courses = array_diff($courses, array(SITEID));
7bd1677c 447 if(count($courses) == 1) {
0f927f1e 448 $hrefparams['course'] = reset($courses);
7bd1677c 449 }
c635dcda 450 }
451
dd97c328 452 if ($events !== false) {
453
454 $modinfo =& get_fast_modinfo($COURSE);
fa22fd5f 455
7423f116 456 foreach($events as $event) {
dc6cb74e 457
dd97c328 458
459 if (!empty($event->modulename)) {
460 if ($event->courseid == $COURSE->id) {
461 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
462 $cm = $modinfo->instances[$event->modulename][$event->instance];
463 if (!$cm->uservisible) {
464 continue;
465 }
466 }
467 } else {
468 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
dc6cb74e 469 continue;
470 }
dd97c328 471 if (!coursemodule_visible_for_user($cm)) {
dc6cb74e 472 continue;
473 }
dd97c328 474 }
475 if ($event->modulename == 'assignment'){
f4700b91
RW
476 // create calendar_event to test edit_event capability
477 // this new event will also prevent double creation of calendar_event object
478 $checkevent = new calendar_event($event);
dd97c328 479 // TODO: rewrite this hack somehow
f4700b91 480 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
62d11d77 481 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
f581f8d6 482 // print_error("invalidid", 'assignment');
dd97c328 483 continue;
484 }
485 // assign assignment to assignment object to use hidden_is_hidden method
486 require_once($CFG->dirroot.'/mod/assignment/lib.php');
487
488 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
489 continue;
490 }
491 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
492
493 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
494 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
495
496 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
497 $event->description = get_string('notavailableyet', 'assignment');
498 }
dc6cb74e 499 }
500 }
501 }
9d567178 502
dd97c328 503 if ($processed >= $display->maxevents) {
9d567178 504 break;
505 }
7423f116 506
0f927f1e 507 $event->time = calendar_format_event_time($event, $now, $hrefparams);
3c134875 508 $output[] = $event;
509 ++$processed;
510 }
511 }
512 return $output;
513}
7423f116 514
9df8ff44 515function calendar_add_event_metadata($event) {
6b608f8f 516 global $CFG, $OUTPUT;
fb73f3b3 517
e295df44 518 //Support multilang in event->name
fb73f3b3 519 $event->name = format_string($event->name,true);
e295df44 520
3c134875 521 if(!empty($event->modulename)) { // Activity event
522 // The module name is set. I will assume that it has to be displayed, and
523 // also that it is an automatically-generated event. And of course that the
524 // fields for get_coursemodule_from_instance are set correctly.
525 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 526
3c134875 527 if ($module === false) {
528 return;
529 }
9958a08c 530
3c134875 531 $modulename = get_string('modulename', $event->modulename);
a48bf079
DM
532 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
533 // will be used as alt text if the event icon
534 $eventtype = get_string($event->eventtype, $event->modulename);
535 } else {
536 $eventtype = '';
537 }
b5d0cafc 538 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
9958a08c 539
91d284c1
SH
540 $context = get_context_instance(CONTEXT_COURSE, $module->course);
541 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
542
10daca92 543 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
fb73f3b3 544 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
91d284c1 545 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
3c134875 546 $event->cmid = $module->id;
9958a08c 547
9958a08c 548
3c134875 549 } else if($event->courseid == SITEID) { // Site event
b5d0cafc 550 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 551 $event->cssclass = 'calendar_event_global';
3c134875 552 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
553 calendar_get_course_cached($coursecache, $event->courseid);
91d284c1
SH
554
555 $context = get_context_instance(CONTEXT_COURSE, $event->courseid);
556 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
557
b5d0cafc 558 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
91d284c1 559 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
90723839 560 $event->cssclass = 'calendar_event_course';
3c134875 561 } else if ($event->groupid) { // Group event
b5d0cafc 562 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 563 $event->cssclass = 'calendar_event_group';
3c134875 564 } else if($event->userid) { // User event
b5d0cafc 565 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 566 $event->cssclass = 'calendar_event_user';
3c134875 567 }
9df8ff44 568 return $event;
e295df44 569}
9df8ff44 570
36dc3b71
SH
571/**
572 * Prints a calendar event
573 *
574 * @deprecated 2.0
575 */
76d9df3f 576function calendar_print_event($event, $showactions=true) {
ae53bd1d 577 global $CFG, $USER, $OUTPUT, $PAGE;
36dc3b71
SH
578 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
579 $renderer = $PAGE->get_renderer('core_calendar');
8bdc9cac
SH
580 if (!($event instanceof calendar_event)) {
581 $event = new calendar_event($event);
582 }
36dc3b71 583 echo $renderer->event($event);
7423f116 584}
585
8263f802 586/**
587 * Get calendar events
588 * @param int $tstart Start time of time range for events
589 * @param int $tend End time of time range for events
590 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
591 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
592 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
593 * @param boolean $withduration whether only events starting within time range selected
594 * or events in progress/already started selected as well
595 * @param boolean $ignorehidden whether to select only visible events or all events
596 * @return array of selected events or an empty array if there aren't any (or there was an error)
597 */
598function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
62d11d77 599 global $DB;
600
7423f116 601 $whereclause = '';
602 // Quick test
603 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
8263f802 604 return array();
7423f116 605 }
482dbe0c 606
7423f116 607 if(is_array($users) && !empty($users)) {
608 // Events from a number of users
609 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 610 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
36dc3b71 611 } else if(is_numeric($users)) {
7423f116 612 // Events from one user
613 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 614 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
36dc3b71 615 } else if($users === true) {
7423f116 616 // Events from ALL users
617 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 618 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
36dc3b71 619 } else if($users === false) {
6e957c41 620 // No user at all, do nothing
f52f7413 621 }
482dbe0c 622
7423f116 623 if(is_array($groups) && !empty($groups)) {
624 // Events from a number of groups
625 if(!empty($whereclause)) $whereclause .= ' OR';
626 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
36dc3b71 627 } else if(is_numeric($groups)) {
7423f116 628 // Events from one group
629 if(!empty($whereclause)) $whereclause .= ' OR ';
630 $whereclause .= ' groupid = '.$groups;
36dc3b71 631 } else if($groups === true) {
7423f116 632 // Events from ALL groups
633 if(!empty($whereclause)) $whereclause .= ' OR ';
634 $whereclause .= ' groupid != 0';
635 }
482dbe0c 636 // boolean false (no groups at all): we don't need to do anything
637
36dc3b71
SH
638 if(is_array($courses) && !empty($courses)) {
639 if(!empty($whereclause)) {
640 $whereclause .= ' OR';
f52f7413 641 }
36dc3b71
SH
642 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
643 } else if(is_numeric($courses)) {
7423f116 644 // One course
645 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 646 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
36dc3b71 647 } else if ($courses === true) {
7423f116 648 // Events from ALL courses
649 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 650 $whereclause .= ' (groupid = 0 AND courseid != 0)';
7423f116 651 }
8c165fe9 652
482dbe0c 653 // Security check: if, by now, we have NOTHING in $whereclause, then it means
654 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
655 // events no matter what. Allowing the code to proceed might return a completely
656 // valid query with only time constraints, thus selecting ALL events in that time frame!
657 if(empty($whereclause)) {
8263f802 658 return array();
482dbe0c 659 }
660
7423f116 661 if($withduration) {
b4892fa2 662 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
7423f116 663 }
664 else {
665 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
666 }
667 if(!empty($whereclause)) {
668 // We have additional constraints
669 $whereclause = $timeclause.' AND ('.$whereclause.')';
670 }
671 else {
672 // Just basic time filtering
673 $whereclause = $timeclause;
674 }
f52f7413 675
0ad072de 676 if ($ignorehidden) {
677 $whereclause .= ' AND visible = 1';
678 }
679
62d11d77 680 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
8263f802 681 if ($events === false) {
682 $events = array();
683 }
684 return $events;
7423f116 685}
686
687function calendar_top_controls($type, $data) {
797cedc7 688 global $CFG;
7423f116 689 $content = '';
690 if(!isset($data['d'])) {
691 $data['d'] = 1;
692 }
5147ad48 693
f21ed0f3 694 // Ensure course id passed if relevant
695 // Required due to changes in view/lib.php mainly (calendar_session_vars())
696 $courseid = '';
697 if (!empty($data['id'])) {
698 $courseid = '&amp;course='.$data['id'];
699 }
700
5147ad48 701 if(!checkdate($data['m'], $data['d'], $data['y'])) {
702 $time = time();
703 }
704 else {
705 $time = make_timestamp($data['y'], $data['m'], $data['d']);
706 }
707 $date = usergetdate($time);
e295df44 708
7423f116 709 $data['m'] = $date['mon'];
710 $data['y'] = $date['year'];
7423f116 711
2a06efcc 712 //Accessibility: calendar block controls, replaced <table> with <div>.
a84dea2c 713 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
714 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
2a06efcc 715
7423f116 716 switch($type) {
717 case 'frontpage':
718 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
719 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 720 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
721 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
ae53bd1d 722
0f927f1e
SH
723 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
724 if (!empty($data['id'])) {
725 $calendarlink->param('course', $data['id']);
726 }
727
43c90b9b 728 if (right_to_left()) {
0f927f1e
SH
729 $left = $nextlink;
730 $right = $prevlink;
43c90b9b 731 } else {
0f927f1e
SH
732 $left = $prevlink;
733 $right = $nextlink;
43c90b9b 734 }
ae53bd1d 735
0f927f1e
SH
736 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
737 $content .= $left.'<span class="hide"> | </span>';
e71e340d 738 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
0f927f1e 739 $content .= '<span class="hide"> | </span>'. $right;
6694ff84 740 $content .= "<span class=\"clearer\"><!-- --></span>\n";
0f927f1e
SH
741 $content .= html_writer::end_tag('div');
742
743 break;
7423f116 744 case 'course':
745 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
746 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 747 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
748 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
0f927f1e
SH
749
750 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
751 if (!empty($data['id'])) {
752 $calendarlink->param('course', $data['id']);
753 }
754
755 if (right_to_left()) {
756 $left = $nextlink;
757 $right = $prevlink;
758 } else {
759 $left = $prevlink;
760 $right = $nextlink;
761 }
762
763 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
764 $content .= $left.'<span class="hide"> | </span>';
e71e340d 765 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
0f927f1e
SH
766 $content .= '<span class="hide"> | </span>'. $right;
767 $content .= "<span class=\"clearer\"><!-- --></span>";
768 $content .= html_writer::end_tag('div');
769 break;
7423f116 770 case 'upcoming':
0f927f1e
SH
771 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
772 if (!empty($data['id'])) {
773 $calendarlink->param('course', $data['id']);
774 }
775 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
776 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
777 break;
7423f116 778 case 'display':
0f927f1e
SH
779 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
780 if (!empty($data['id'])) {
781 $calendarlink->param('course', $data['id']);
782 }
783 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
784 $content .= html_writer::tag('h3', $calendarlink);
785 break;
7423f116 786 case 'month':
787 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
788 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
5147ad48 789 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
790 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
0f927f1e
SH
791 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
792 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
793
794 if (right_to_left()) {
795 $left = $nextlink;
796 $right = $prevlink;
797 } else {
798 $left = $prevlink;
799 $right = $nextlink;
800 }
801
802 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
803 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
804 $content .= '<span class="hide"> | </span>' . $right;
805 $content .= '<span class="clearer"><!-- --></span>';
806 $content .= html_writer::end_tag('div')."\n";
807 break;
7423f116 808 case 'day':
797cedc7 809 $days = calendar_get_days();
7423f116 810 $data['d'] = $date['mday']; // Just for convenience
5147ad48 811 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
812 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
797cedc7
SH
813 $prevname = calendar_wday_name($days[$prevdate['wday']]);
814 $nextname = calendar_wday_name($days[$nextdate['wday']]);
0f927f1e
SH
815 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
816 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
817
818 if (right_to_left()) {
819 $left = $nextlink;
820 $right = $prevlink;
821 } else {
822 $left = $prevlink;
823 $right = $nextlink;
824 }
825
826 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
827 $content .= $left;
828 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
829 $content .= '<span class="hide"> | </span>'. $right;
830 $content .= "<span class=\"clearer\"><!-- --></span>";
831 $content .= html_writer::end_tag('div')."\n";
832
833 break;
7423f116 834 }
835 return $content;
836}
837
797cedc7
SH
838function calendar_filter_controls(moodle_url $returnurl) {
839 global $CFG, $USER, $OUTPUT;
7423f116 840
48f508ab 841 $groupevents = true;
e295df44 842
7f4d18fc 843 $id = optional_param( 'id',0,PARAM_INT );
d715f7c4 844
eb59a448 845 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
7423f116 846
2ad2cbc3 847 $content = '<table>';
48f508ab 848 $content .= '<tr>';
797cedc7
SH
849
850 $seturl->param('var', 'showglobal');
851 if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
852 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
853 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
fdbffa54 854 } else {
797cedc7
SH
855 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
856 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
48f508ab 857 }
aa6c1ced 858
797cedc7
SH
859 $seturl->param('var', 'showcourses');
860 if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
861 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
862 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
863 } else {
864 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
865 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
e3bb6401 866 }
48f508ab 867
4f0c2d00 868 if (isloggedin() && !isguestuser()) {
e3bb6401 869 $content .= "</tr>\n<tr>";
10b1d598 870
797cedc7 871 if ($groupevents) {
43c3ffbe 872 // This course MIGHT have group events defined, so show the filter
797cedc7
SH
873 $seturl->param('var', 'showgroups');
874 if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
875 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
876 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
e3bb6401 877 } else {
797cedc7
SH
878 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
879 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
43c3ffbe 880 }
e3bb6401 881 } else {
43c3ffbe 882 // This course CANNOT have group events, so lose the filter
5c53988f 883 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
fdbffa54 884 }
797cedc7
SH
885
886 $seturl->param('var', 'showuser');
887 if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
888 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
889 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
fdbffa54 890 } else {
797cedc7
SH
891 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
892 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
48f508ab 893 }
894 }
895 $content .= "</tr>\n</table>\n";
896
7423f116 897 return $content;
898}
899
900function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
901
0ef7c973 902 static $shortformat;
903 if(empty($shortformat)) {
e70fdac0 904 $shortformat = get_string('strftimedayshort');
0ef7c973 905 }
906
7423f116 907 if($now === false) {
908 $now = time();
909 }
910
911 // To have it in one place, if a change is needed
e70fdac0 912 $formal = userdate($tstamp, $shortformat);
7423f116 913
7b38bfa6 914 $datestamp = usergetdate($tstamp);
915 $datenow = usergetdate($now);
7423f116 916
917 if($usecommonwords == false) {
918 // We don't want words, just a date
919 return $formal;
920 }
7b38bfa6 921 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 922 // Today
923 return get_string('today', 'calendar');
924 }
7b38bfa6 925 else if(
926 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
927 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
928 ) {
7423f116 929 // Yesterday
930 return get_string('yesterday', 'calendar');
931 }
7b38bfa6 932 else if(
933 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
934 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
935 ) {
7423f116 936 // Tomorrow
937 return get_string('tomorrow', 'calendar');
938 }
939 else {
940 return $formal;
941 }
942}
943
944function calendar_time_representation($time) {
1b0ebe79 945 static $langtimeformat = NULL;
946 if($langtimeformat === NULL) {
947 $langtimeformat = get_string('strftimetime');
948 }
949 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 950 if(empty($timeformat)){
951 $timeformat = get_config(NULL,'calendar_site_timeformat');
952 }
1b0ebe79 953 // The ? is needed because the preference might be present, but empty
954 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 955}
956
e295df44 957/**
14236cbd
SH
958 * Adds day, month, year arguments to a URL and returns a moodle_url object.
959 *
960 * @param string|moodle_url $linkbase
961 * @param int $d
962 * @param int $m
963 * @param int $y
1d5bd3d2 964 * @return moodle_url
e295df44 965 */
7423f116 966function calendar_get_link_href($linkbase, $d, $m, $y) {
0f927f1e
SH
967 if (empty($linkbase)) {
968 return '';
969 }
970 if (!($linkbase instanceof moodle_url)) {
971 $linkbase = new moodle_url();
972 }
973 if (!empty($d)) {
974 $linkbase->param('cal_d', $d);
975 }
976 if (!empty($m)) {
977 $linkbase->param('cal_m', $m);
978 }
979 if (!empty($y)) {
980 $linkbase->param('cal_y', $y);
981 }
982 return $linkbase;
7423f116 983}
984
e295df44 985/**
0f927f1e
SH
986 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
987 *
988 * @deprecated
989 * @since 2.0
990 *
991 * @param string $text
992 * @param string|moodle_url $linkbase
993 * @param int|null $d
994 * @param int|null $m
995 * @param int|null $y
996 * @return string HTML link
e295df44 997 */
7423f116 998function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
0f927f1e
SH
999 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1000 if (empty($url)) {
1001 return $text;
1002 }
1003 return html_writer::link($url, $text);
7423f116 1004}
1005
a84dea2c 1006/**
1007 * Build and return a previous month HTML link, with an arrow.
14236cbd 1008 *
a84dea2c 1009 * @param string $text The text label.
14236cbd 1010 * @param string|moodle_url $linkbase The URL stub.
a84dea2c 1011 * @param int $d $m $y Day of month, month and year numbers.
1012 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1013 * @return string HTML string.
1014 */
1015function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
0f927f1e
SH
1016 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1017 if (empty($href)) {
1018 return $text;
1019 }
1020 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
a84dea2c 1021}
1022
1023/**
1024 * Build and return a next month HTML link, with an arrow.
1d5bd3d2 1025 *
a84dea2c 1026 * @param string $text The text label.
14236cbd 1027 * @param string|moodle_url $linkbase The URL stub.
a84dea2c 1028 * @param int $d $m $y Day of month, month and year numbers.
1029 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1030 * @return string HTML string.
1031 */
1032function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
0f927f1e
SH
1033 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1034 if (empty($href)) {
1035 return $text;
1036 }
1037 return link_arrow_right($text, (string)$href, $accesshide, 'next');
a84dea2c 1038}
1039
7423f116 1040function calendar_wday_name($englishname) {
1041 return get_string(strtolower($englishname), 'calendar');
1042}
1043
1044function calendar_days_in_month($month, $year) {
7b38bfa6 1045 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 1046}
1047
6605ff8c 1048function calendar_get_block_upcoming($events, $linkhref = NULL) {
7423f116 1049 $content = '';
1050 $lines = count($events);
396b61f0 1051 if (!$lines) {
1052 return $content;
1053 }
7423f116 1054
396b61f0 1055 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 1056 if (!isset($events[$i]->time)) { // Just for robustness
1057 continue;
1058 }
9df8ff44 1059 $events[$i] = calendar_add_event_metadata($events[$i]);
ea21c1f4 1060 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
43c3ffbe 1061 if (!empty($events[$i]->referer)) {
7423f116 1062 // That's an activity event, so let's provide the hyperlink
396b61f0 1063 $content .= $events[$i]->referer;
1064 } else {
e749554e 1065 if(!empty($linkhref)) {
1066 $ed = usergetdate($events[$i]->timestart);
0f927f1e
SH
1067 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1068 $href->set_anchor('event_'.$events[$i]->id);
1069 $content .= html_writer::link($href, $events[$i]->name);
e749554e 1070 }
1071 else {
1072 $content .= $events[$i]->name;
1073 }
7423f116 1074 }
9ecf051d 1075 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1076 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 1077 if ($i < $lines - 1) $content .= '<hr />';
7423f116 1078 }
1079
1080 return $content;
7423f116 1081}
1082
1083function calendar_add_month($month, $year) {
1084 if($month == 12) {
1085 return array(1, $year + 1);
1086 }
1087 else {
1088 return array($month + 1, $year);
1089 }
1090}
1091
1092function calendar_sub_month($month, $year) {
1093 if($month == 1) {
1094 return array(12, $year - 1);
1095 }
1096 else {
1097 return array($month - 1, $year);
1098 }
1099}
1100
7c50db30 1101function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
7423f116 1102 $eventsbyday = array();
1103 $typesbyday = array();
1104 $durationbyday = array();
1105
1106 if($events === false) {
1107 return;
1108 }
1109
7423f116 1110 foreach($events as $event) {
7423f116 1111
7b38bfa6 1112 $startdate = usergetdate($event->timestart);
b4892fa2 1113 // Set end date = start date if no duration
1114 if ($event->timeduration) {
1115 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1116 } else {
1117 $enddate = $startdate;
1118 }
7423f116 1119
7b38bfa6 1120 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 1121 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 1122 // Out of bounds
1123 continue;
7423f116 1124 }
1125
7b38bfa6 1126 $eventdaystart = intval($startdate['mday']);
7423f116 1127
7b38bfa6 1128 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1129 // Give the event to its day
1130 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 1131
7b38bfa6 1132 // Mark the day as having such an event
9064751b 1133 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1134 $typesbyday[$eventdaystart]['startglobal'] = true;
b4892fa2 1135 // Set event class for global event
90723839 1136 $events[$event->id]->class = 'calendar_event_global';
7b38bfa6 1137 }
c3d3b6d4 1138 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1139 $typesbyday[$eventdaystart]['startcourse'] = true;
b4892fa2 1140 // Set event class for course event
90723839 1141 $events[$event->id]->class = 'calendar_event_course';
7b38bfa6 1142 }
1143 else if($event->groupid) {
1144 $typesbyday[$eventdaystart]['startgroup'] = true;
b4892fa2 1145 // Set event class for group event
90723839 1146 $events[$event->id]->class = 'calendar_event_group';
7b38bfa6 1147 }
1148 else if($event->userid) {
1149 $typesbyday[$eventdaystart]['startuser'] = true;
b4892fa2 1150 // Set event class for user event
90723839 1151 $events[$event->id]->class = 'calendar_event_user';
7b38bfa6 1152 }
1153 }
7423f116 1154
7b38bfa6 1155 if($event->timeduration == 0) {
1156 // Proceed with the next
1157 continue;
1158 }
7423f116 1159
7b38bfa6 1160 // The event starts on $month $year or before. So...
ef618501 1161 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 1162
1163 // Also, it ends on $month $year or later...
1164 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1165
1166 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1167 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1168 $durationbyday[$i][] = $event->id;
9064751b 1169 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1170 $typesbyday[$i]['durationglobal'] = true;
1171 }
c3d3b6d4 1172 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1173 $typesbyday[$i]['durationcourse'] = true;
1174 }
1175 else if($event->groupid) {
1176 $typesbyday[$i]['durationgroup'] = true;
1177 }
1178 else if($event->userid) {
1179 $typesbyday[$i]['durationuser'] = true;
7423f116 1180 }
1181 }
7b38bfa6 1182
7423f116 1183 }
1184 return;
1185}
1186
b63c0ee5 1187function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1188 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 1189
1190 if($module === false) return false;
b63c0ee5 1191 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 1192 return false;
1193 }
1194 return $module;
1195}
1196
1197function calendar_get_course_cached(&$coursecache, $courseid) {
62d11d77 1198 global $COURSE, $DB;
1199
b571c6b3 1200 if (!isset($coursecache[$courseid])) {
1201 if ($courseid == $COURSE->id) {
1202 $coursecache[$courseid] = $COURSE;
1203 } else {
62d11d77 1204 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
b571c6b3 1205 }
7423f116 1206 }
1207 return $coursecache[$courseid];
1208}
1209
797cedc7
SH
1210/**
1211 * Returns the courses to load events for, the
1212 *
1213 * @global moodle_database $DB
1214 * @param array $courseeventsfrom An array of courses to load calendar events for
1215 * @param bool $ignorefilters
1216 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1217 */
1218function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1219 global $USER, $CFG, $DB;
7423f116 1220
797cedc7
SH
1221 // For backwards compatability we have to check whether the courses array contains
1222 // just id's in which case we need to load course objects.
1223 $coursestoload = array();
1224 foreach ($courseeventsfrom as $id => $something) {
1225 if (!is_object($something)) {
1226 $coursestoload[] = $id;
1227 unset($courseeventsfrom[$id]);
753b799d 1228 }
dd97c328 1229 }
797cedc7
SH
1230 if (!empty($coursestoload)) {
1231 // TODO remove this in 2.2
1232 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1233 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
89adb174 1234 }
7423f116 1235
797cedc7
SH
1236 $courses = array();
1237 $user = false;
1238 $group = false;
7423f116 1239
797cedc7 1240 $isloggedin = isloggedin();
d12e3ff2 1241
797cedc7
SH
1242 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1243 $courses = array_keys($courseeventsfrom);
7423f116 1244 }
797cedc7
SH
1245 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1246 $courses[] = SITEID;
7423f116 1247 }
797cedc7
SH
1248 $courses = array_unique($courses);
1249 sort($courses);
7c50db30 1250
797cedc7 1251 if (!empty($courses) && in_array(SITEID, $courses)) {
7c50db30 1252 // Sort courses for consistent colour highlighting
1253 // Effectively ignoring SITEID as setting as last course id
1254 $key = array_search(SITEID, $courses);
797cedc7
SH
1255 unset($courses[$key]);
1256 $courses[] = SITEID;
0e6a8f4b 1257 }
7423f116 1258
797cedc7
SH
1259 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1260 $user = $USER->id;
7423f116 1261 }
257e3f4c 1262
797cedc7
SH
1263 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1264
1265 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_system_context())) {
257e3f4c 1266 $group = true;
797cedc7
SH
1267 } else if ($isloggedin) {
1268 $groupids = array();
69762501 1269
257e3f4c 1270 // We already have the courses to examine in $courses
1271 // For each course...
797cedc7 1272 foreach ($courseeventsfrom as $courseid => $course) {
257e3f4c 1273 // If the user is an editing teacher in there,
797cedc7
SH
1274 if (!empty($USER->groupmember[$course->id])) {
1275 // We've already cached the users groups for this course so we can just use that
1276 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1277 } else if (($course->groupmode != NOGROUPS || !$course->groupmodeforce) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $course->id))) {
69762501 1278 // If this course has groups, show events from all of them
797cedc7
SH
1279 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1280 $groupids = array_merge($groupids, $coursegroups['0']);
7423f116 1281 }
1282 }
6b4aeb31 1283 if (!empty($groupids)) {
797cedc7 1284 $group = $groupids;
6c9584d1 1285 }
7423f116 1286 }
7423f116 1287 }
797cedc7
SH
1288 if (empty($courses)) {
1289 $courses = false;
7423f116 1290 }
797cedc7
SH
1291
1292 return array($courses, $group, $user);
7423f116 1293}
1294
1295function calendar_edit_event_allowed($event) {
62d11d77 1296 global $USER, $DB;
7423f116 1297
2ac8da76 1298 // Must be logged in
1299 if (!isloggedin()) {
1300 return false;
1301 }
1302
89491dbd 1303 // can not be using guest account
2396a414 1304 if (isguestuser()) {
e295df44 1305 return false;
89491dbd 1306 }
e295df44 1307
ef35441d 1308 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
89491dbd 1309 // if user has manageentries at site level, return true
28ee98c5 1310 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1311 return true;
f52f7413 1312 }
e295df44 1313
c0a2c361 1314 // if groupid is set, it's definitely a group event
438e4add 1315 if (!empty($event->groupid)) {
f63d2922 1316 // Allow users to add/edit group events if:
1317 // 1) They have manageentries (= entries for whole course)
1318 // 2) They have managegroupentries AND are in the group
62d11d77 1319 $group = $DB->get_record('groups', array('id'=>$event->groupid));
f63d2922 1320 return $group && (
f4700b91
RW
1321 has_capability('moodle/calendar:manageentries', $event->context) ||
1322 (has_capability('moodle/calendar:managegroupentries', $event->context)
f63d2922 1323 && groups_is_member($event->groupid)));
438e4add 1324 } else if (!empty($event->courseid)) {
c0a2c361 1325 // if groupid is not set, but course is set,
1326 // it's definiely a course event
f4700b91 1327 return has_capability('moodle/calendar:manageentries', $event->context);
438e4add 1328 } else if (!empty($event->userid) && $event->userid == $USER->id) {
c0a2c361 1329 // if course is not set, but userid id set, it's a user event
f4700b91
RW
1330 return (has_capability('moodle/calendar:manageownentries', $event->context));
1331 } else if (!empty($event->userid)) {
1332 return (has_capability('moodle/calendar:manageentries', $event->context));
e295df44 1333 }
7423f116 1334 return false;
1335}
1336
797cedc7
SH
1337/**
1338 * Returns the default courses to display on the calendar when there isn't a specific
1339 * course to display.
1340 *
1341 * @global moodle_database $DB
1342 * @return array Array of courses to display
1343 */
1344function calendar_get_default_courses() {
1345 global $CFG, $DB;
7423f116 1346
4f0c2d00 1347 if (!isloggedin()) {
2ef75eee 1348 return array();
1349 }
1350
7423f116 1351 $courses = array();
797cedc7
SH
1352 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
1353 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1354 $sql = "SELECT c.* $select
1355 FROM {course} c
1356 JOIN {event} e ON e.courseid = c.id
1357 $join";
1358 $courses = $DB->get_records_sql($sql, null, 0, 20);
1359 foreach ($courses as $course) {
1360 context_instance_preload($course);
86f092d2 1361 }
797cedc7 1362 return $courses;
95a89225 1363 }
e295df44 1364
df997f84 1365 $courses = enrol_get_my_courses();
37d87d11 1366
1367 return $courses;
7423f116 1368}
1369
797cedc7
SH
1370function calendar_preferences_button(stdClass $course) {
1371 global $OUTPUT;
7423f116 1372
1373 // Guests have no preferences
4f0c2d00 1374 if (!isloggedin() || isguestuser()) {
7423f116 1375 return '';
1376 }
1377
797cedc7 1378 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
7423f116 1379}
1380
0f927f1e 1381function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
8f896582 1382 $startdate = usergetdate($event->timestart);
1383 $enddate = usergetdate($event->timestart + $event->timeduration);
1384 $usermidnightstart = usergetmidnight($event->timestart);
1385
1386 if($event->timeduration) {
1387 // To avoid doing the math if one IF is enough :)
1388 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1389 }
1390 else {
1391 $usermidnightend = $usermidnightstart;
1392 }
1393
0f927f1e
SH
1394 if (empty($linkparams) || !is_array($linkparams)) {
1395 $linkparams = array();
1396 }
1397 $linkparams['view'] = 'day';
1398
8f896582 1399 // OK, now to get a meaningful display...
1400 // First of all we have to construct a human-readable date/time representation
1401
b4892fa2 1402 if($event->timeduration) {
8f896582 1403 // It has a duration
b4892fa2 1404 if($usermidnightstart == $usermidnightend ||
1405 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1406 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
8f896582 1407 // But it's all on the same day
8f896582 1408 $timestart = calendar_time_representation($event->timestart);
1409 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
b4892fa2 1410 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1411
1412 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1413 $time = get_string('allday', 'calendar');
1414 }
8f896582 1415
1416 // Set printable representation
b4892fa2 1417 if (!$showtime) {
1418 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
0f927f1e
SH
1419 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1420 $eventtime = html_writer::link($url, $day).', '.$time;
b4892fa2 1421 } else {
1422 $eventtime = $time;
1423 }
1424 } else {
8f896582 1425 // It spans two or more days
b4892fa2 1426 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1427 if ($showtime == $usermidnightstart) {
1428 $daystart = '';
1429 }
8f896582 1430 $timestart = calendar_time_representation($event->timestart);
b4892fa2 1431 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1432 if ($showtime == $usermidnightend) {
1433 $dayend = '';
1434 }
8f896582 1435 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1436
1437 // Set printable representation
b4892fa2 1438 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
0f927f1e
SH
1439 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1440 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
b4892fa2 1441 } else {
0f927f1e
SH
1442 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1443 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1d5bd3d2 1444
0f927f1e
SH
1445 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1446 $eventtime .= html_writer::link($url, $dayend).$timeend;
b4892fa2 1447 }
8f896582 1448 }
b4892fa2 1449 } else {
1c4bedd7 1450 $time = ' ';
8f896582 1451
1452 // Set printable representation
b4892fa2 1453 if (!$showtime) {
1454 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
0f927f1e
SH
1455 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1456 $eventtime = html_writer::link($url, $day).trim($time);
b4892fa2 1457 } else {
1458 $eventtime = $time;
1459 }
1460 }
1461
1462 if($event->timestart + $event->timeduration < $now) {
1463 // It has expired
1464 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
8f896582 1465 }
09d36284 1466
8f896582 1467 return $eventtime;
1468}
054193be 1469
86f092d2 1470function calendar_print_month_selector($name, $selected) {
86f092d2 1471 $months = array();
86f092d2 1472 for ($i=1; $i<=12; $i++) {
76ab1c33 1473 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1474 }
d776d59e 1475 echo html_writer::select($months, $name, $selected, false);
86f092d2 1476}
1477
797cedc7
SH
1478/**
1479 * Checks to see if the requested type of event should be shown for the given user.
1480 *
1481 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1482 * The type to check the display for (default is to display all)
1483 * @param stdClass|int|null $user The user to check for - by default the current user
1484 * @return bool True if the tyep should be displayed false otherwise
1485 */
1486function calendar_show_event_type($type, $user = null) {
1487 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1488 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1489 global $SESSION;
1490 if (!isset($SESSION->calendarshoweventtype)) {
1491 $SESSION->calendarshoweventtype = $default;
1492 }
1493 return $SESSION->calendarshoweventtype & $type;
1494 } else {
1495 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
054193be 1496 }
797cedc7
SH
1497}
1498
1499/**
1500 * Sets the display of the event type given $display.
1501 * If $display = true the event type will be shown.
1502 * If $display = false the event type will NOT be shown.
1503 * If $display = null the current value will be toggled and saved.
1504 *
1505 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1506 * @param true|false|null $display
1507 * @param stdClass|int|null $user
1508 */
1509function calendar_set_event_type_display($type, $display = null, $user = null) {
1510 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1511 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1512 if ($persist === 0) {
1513 global $SESSION;
1514 if (!isset($SESSION->calendarshoweventtype)) {
1515 $SESSION->calendarshoweventtype = $default;
1516 }
1517 $preference = $SESSION->calendarshoweventtype;
1518 } else {
1519 $preference = get_user_preferences('calendar_savedflt', $default, $user);
054193be 1520 }
797cedc7
SH
1521 $current = $preference & $type;
1522 if ($display === null) {
1523 $display = !$current;
054193be 1524 }
797cedc7
SH
1525 if ($display && !$current) {
1526 $preference += $type;
1527 } else if (!$display && $current) {
1528 $preference -= $type;
054193be 1529 }
797cedc7
SH
1530 if ($persist === 0) {
1531 $SESSION->calendarshoweventtype = $preference;
1532 } else {
1533 if ($preference == $default) {
1534 unset_user_preference('calendar_savedflt', $user);
1535 } else {
1536 set_user_preference('calendar_savedflt', $preference, $user);
1537 }
054193be 1538 }
054193be 1539}
1540
797cedc7
SH
1541function calendar_get_allowed_types(&$allowed, $course = null) {
1542 global $USER, $CFG, $DB;
b85b25eb 1543 $allowed = new stdClass();
797cedc7 1544 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
86ac8b24 1545 $allowed->groups = false; // This may change just below
1546 $allowed->courses = false; // This may change just below
1547 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1548
797cedc7
SH
1549 if (!empty($course)) {
1550 if (!is_object($course)) {
1551 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1552 }
1553 if ($course->id != SITEID) {
1554 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
86ac8b24 1555
797cedc7
SH
1556 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1557 $allowed->courses = array($course->id => 1);
aa6c1ced 1558
797cedc7
SH
1559 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1560 $allowed->groups = groups_get_all_groups($course->id);
1561 }
1562 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1563 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1564 $allowed->groups = groups_get_all_groups($course->id);
1565 }
f63d2922 1566 }
86ac8b24 1567 }
1568 }
1569}
1570
1571/**
1572 * see if user can add calendar entries at all
1573 * used to print the "New Event" button
1574 * @return bool
1575 */
797cedc7
SH
1576function calendar_user_can_add_event($course) {
1577 if (!isloggedin() || isguestuser()) {
1578 return false;
1579 }
1580 calendar_get_allowed_types($allowed, $course);
e295df44 1581 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
86ac8b24 1582}
76d9df3f
SH
1583
1584/**
1585 * Check wether the current user is permitted to add events
1586 *
1587 * @param object $event
1588 * @return bool
1589 */
1590function calendar_add_event_allowed($event) {
1591 global $USER, $DB;
1592
1593 // can not be using guest account
4f0c2d00 1594 if (!isloggedin() or isguestuser()) {
76d9df3f
SH
1595 return false;
1596 }
1597
1598 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1599 // if user has manageentries at site level, always return true
1600 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1601 return true;
1602 }
1603
1604 switch ($event->eventtype) {
1605 case 'course':
f4700b91 1606 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1607
1608 case 'group':
1609 // Allow users to add/edit group events if:
1610 // 1) They have manageentries (= entries for whole course)
1611 // 2) They have managegroupentries AND are in the group
1612 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1613 return $group && (
f4700b91
RW
1614 has_capability('moodle/calendar:manageentries', $event->context) ||
1615 (has_capability('moodle/calendar:managegroupentries', $event->context)
76d9df3f
SH
1616 && groups_is_member($event->groupid)));
1617
1618 case 'user':
1619 if ($event->userid == $USER->id) {
f4700b91 1620 return (has_capability('moodle/calendar:manageownentries', $event->context));
76d9df3f
SH
1621 }
1622 //there is no 'break;' intentionally
1623
1624 case 'site':
f4700b91 1625 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1626
1627 default:
f4700b91 1628 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1629 }
1630}
1631
1632/**
1633 * A class to manage calendar events
1634 *
1635 * This class provides the required functionality in order to manage calendar events.
1636 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1637 * better framework for dealing with calendar events in particular regard to file
1638 * handling through the new file API
1639 *
1640 * @property int $id The id within the event table
1641 * @property string $name The name of the event
1642 * @property string $description The description of the event
1643 * @property int $format The format of the description FORMAT_?
1644 * @property int $courseid The course the event is associated with (0 if none)
1645 * @property int $groupid The group the event is associated with (0 if none)
1646 * @property int $userid The user the event is associated with (0 if none)
1647 * @property int $repeatid If this is a repeated event this will be set to the
1648 * id of the original
1649 * @property string $modulename If added by a module this will be the module name
1650 * @property int $instance If added by a module this will be the module instance
1651 * @property string $eventtype The event type
1652 * @property int $timestart The start time as a timestamp
1653 * @property int $timeduration The duration of the event in seconds
1654 * @property int $visible 1 if the event is visible
1655 * @property int $uuid ?
1656 * @property int $sequence ?
1657 * @property int $timemodified The time last modified as a timestamp
1658 */
1659class calendar_event {
1660
1661 /**
1662 * An object containing the event properties can be accessed via the
1663 * magic __get/set methods
1664 * @var array
1665 */
1666 protected $properties = null;
1667 /**
1668 * The converted event discription with file paths resolved
1669 * This gets populated when someone requests description for the first time
1670 * @var string
1671 */
1672 protected $_description = null;
76d9df3f
SH
1673 /**
1674 * The options to use with this description editor
1675 * @var array
1676 */
1677 protected $editoroptions = array(
1678 'subdirs'=>false,
1679 'forcehttps'=>false,
2b35ed1a 1680 'maxfiles'=>-1,
76d9df3f
SH
1681 'maxbytes'=>null,
1682 'trusttext'=>false);
1683 /**
1684 * The context to use with the description editor
1685 * @var object
1686 */
1687 protected $editorcontext = null;
1688
1689 /**
1690 * Instantiates a new event and optionally populates its properties with the
1691 * data provided
1692 *
1693 * @param stdClass $data Optional. An object containing the properties to for
1694 * an event
1695 */
1696 public function __construct($data=null) {
c203a277 1697 global $CFG, $USER;
76d9df3f
SH
1698
1699 // First convert to object if it is not already (should either be object or assoc array)
1700 if (!is_object($data)) {
1701 $data = (object)$data;
1702 }
1703
1704 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1705
1706 $data->eventrepeats = 0;
1707
1708 if (empty($data->id)) {
1709 $data->id = null;
1710 }
1711
c203a277
SH
1712 // Default to a user event
1713 if (empty($data->eventtype)) {
1714 $data->eventtype = 'user';
1715 }
1716
1717 // Default to the current user
1718 if (empty($data->userid)) {
1719 $data->userid = $USER->id;
1720 }
1721
76d9df3f
SH
1722 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1723 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1724 }
1725 if (!empty($data->description) && is_array($data->description)) {
1726 $data->format = $data->description['format'];
1727 $data->description = $data->description['text'];
1728 } else if (empty($data->description)) {
1729 $data->description = '';
20e5da7d 1730 $data->format = editors_get_preferred_format();
76d9df3f 1731 }
c203a277
SH
1732 // Ensure form is defaulted correctly
1733 if (empty($data->format)) {
1734 $data->format = editors_get_preferred_format();
1735 }
76d9df3f 1736
f4700b91
RW
1737 if (empty($data->context)) {
1738 $data->context = $this->calculate_context($data);
1739 }
76d9df3f
SH
1740 $this->properties = $data;
1741 }
1742
1743 /**
1744 * Magic property method
1745 *
1746 * Attempts to call a set_$key method if one exists otherwise falls back
1747 * to simply set the property
1748 *
1749 * @param string $key
1750 * @param mixed $value
1751 */
1752 public function __set($key, $value) {
1753 if (method_exists($this, 'set_'.$key)) {
1754 $this->{'set_'.$key}($value);
1755 }
1756 $this->properties->{$key} = $value;
1757 }
1758
1759 /**
1760 * Magic get method
1761 *
1762 * Attempts to call a get_$key method to return the property and ralls over
1763 * to return the raw property
1764 *
1765 * @param str $key
1766 * @return mixed
1767 */
1768 public function __get($key) {
1769 if (method_exists($this, 'get_'.$key)) {
1770 return $this->{'get_'.$key}();
1771 }
c203a277
SH
1772 if (!isset($this->properties->{$key})) {
1773 throw new coding_exception('Undefined property requested');
1774 }
76d9df3f
SH
1775 return $this->properties->{$key};
1776 }
1777
1778 /**
1779 * Stupid PHP needs an isset magic method if you use the get magic method and
1780 * still want empty calls to work.... blah ~!
1781 *
1782 * @param string $key
1783 * @return bool
1784 */
1785 public function __isset($key) {
1786 return !empty($this->properties->{$key});
1787 }
1788
f4700b91
RW
1789 /**
1790 * Calculate the context value needed for calendar_event.
1791 * Event's type can be determine by the available value store in $data
1792 * It is important to check for the existence of course/courseid to determine
1793 * the course event.
1794 * Default value is set to CONTEXT_USER
1795 *
1796 * @return stdClass
1797 */
1798 protected function calculate_context(stdClass $data) {
025d82e0 1799 global $USER, $DB;
f4700b91 1800
f4700b91
RW
1801 $context = null;
1802 if (isset($data->courseid) && $data->courseid > 0) {
1803 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1804 } else if (isset($data->course) && $data->course > 0) {
1805 $context = get_context_instance(CONTEXT_COURSE, $data->course);
1806 } else if (isset($data->groupid) && $data->groupid > 0) {
1807 $group = $DB->get_record('groups', array('id'=>$data->groupid));
1808 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
1809 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
d52777b4 1810 $context = get_context_instance(CONTEXT_USER, $data->userid);
f4700b91
RW
1811 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
1812 isset($data->instance) && $data->instance > 0) {
18d63ffb 1813 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
f4700b91
RW
1814 $context = get_context_instance(CONTEXT_COURSE, $cm->course);
1815 } else {
1816 $context = get_context_instance(CONTEXT_USER);
1817 }
1818
1819 return $context;
1820 }
1821
76d9df3f
SH
1822 /**
1823 * Returns an array of editoroptions for this event: Called by __get
1824 * Please use $blah = $event->editoroptions;
1825 * @return array
1826 */
1827 protected function get_editoroptions() {
1828 return $this->editoroptions;
1829 }
1830
1831 /**
1832 * Returns an event description: Called by __get
1833 * Please use $blah = $event->description;
1834 *
1835 * @return string
1836 */
1837 protected function get_description() {
f4700b91 1838 global $CFG;
99d19c13
PS
1839
1840 require_once($CFG->libdir . '/filelib.php');
1841
76d9df3f
SH
1842 if ($this->_description === null) {
1843 // Check if we have already resolved the context for this event
1844 if ($this->editorcontext === null) {
1845 // Switch on the event type to decide upon the appropriate context
1846 // to use for this event
f4700b91
RW
1847 $this->editorcontext = $this->properties->context;
1848 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
1849 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
1850 return clean_text($this->properties->description, $this->properties->format);
76d9df3f
SH
1851 }
1852 }
1853
1854 // Work out the item id for the editor, if this is a repeated event then the files will
1855 // be associated with the original
1856 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1857 $itemid = $this->properties->repeatid;
1858 } else {
1859 $itemid = $this->properties->id;
1860 }
1861
1862 // Convert file paths in the description so that things display correctly
64f93798 1863 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
76d9df3f
SH
1864 // Clean the text so no nasties get through
1865 $this->_description = clean_text($this->_description, $this->properties->format);
1866 }
1867 // Finally return the description
1868 return $this->_description;
1869 }
1870
1871 /**
1872 * Return the number of repeat events there are in this events series
aa6c1ced 1873 *
76d9df3f
SH
1874 * @return int
1875 */
1876 public function count_repeats() {
1877 global $DB;
1878 if (!empty($this->properties->repeatid)) {
1879 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1880 // We don't want to count ourselves
1881 $this->properties->eventrepeats--;
1882 }
1883 return $this->properties->eventrepeats;
1884 }
1885
1886 /**
1887 * Update or create an event within the database
1888 *
1889 * Pass in a object containing the event properties and this function will
1890 * insert it into the database and deal with any associated files
1891 *
1892 * @see add_event()
1893 * @see update_event()
1894 *
1895 * @param stdClass $data
1d5bd3d2 1896 * @param boolean $checkcapability if moodle should check calendar managing capability or not
76d9df3f 1897 */
1d5bd3d2 1898 public function update($data, $checkcapability=true) {
76d9df3f
SH
1899 global $CFG, $DB, $USER;
1900
438e4add
SH
1901 foreach ($data as $key=>$value) {
1902 $this->properties->$key = $value;
1903 }
1904
76d9df3f
SH
1905 $this->properties->timemodified = time();
1906 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1907
1908 if (empty($this->properties->id) || $this->properties->id < 1) {
1909
1d5bd3d2
DC
1910 if ($checkcapability) {
1911 if (!calendar_add_event_allowed($this->properties)) {
1912 print_error('nopermissiontoupdatecalendar');
1913 }
76d9df3f
SH
1914 }
1915
1916 if ($usingeditor) {
1917 switch ($this->properties->eventtype) {
1918 case 'user':
f4700b91 1919 $this->editorcontext = $this->properties->context;
76d9df3f
SH
1920 $this->properties->courseid = 0;
1921 $this->properties->groupid = 0;
1922 $this->properties->userid = $USER->id;
1923 break;
1924 case 'site':
f4700b91 1925 $this->editorcontext = $this->properties->context;
76d9df3f
SH
1926 $this->properties->courseid = SITEID;
1927 $this->properties->groupid = 0;
1928 $this->properties->userid = $USER->id;
1929 break;
1930 case 'course':
f4700b91 1931 $this->editorcontext = $this->properties->context;
76d9df3f
SH
1932 $this->properties->groupid = 0;
1933 $this->properties->userid = $USER->id;
1934 break;
1935 case 'group':
f4700b91 1936 $this->editorcontext = $this->properties->context;
76d9df3f
SH
1937 $this->properties->userid = $USER->id;
1938 break;
1939 default:
1940 // Ewww we should NEVER get here, but just incase we do lets
1941 // fail gracefully
1942 $usingeditor = false;
1943 break;
1944 }
1945
1946 $editor = $this->properties->description;
1947 $this->properties->format = $this->properties->description['format'];
1948 $this->properties->description = $this->properties->description['text'];
1949 }
1950
1951 // Insert the event into the database
1952 $this->properties->id = $DB->insert_record('event', $this->properties);
1953
1954 if ($usingeditor) {
1955 $this->properties->description = file_save_draft_area_files(
1956 $editor['itemid'],
1957 $this->editorcontext->id,
64f93798
PS
1958 'calendar',
1959 'event_description',
76d9df3f
SH
1960 $this->properties->id,
1961 $this->editoroptions,
1962 $editor['text'],
1963 $this->editoroptions['forcehttps']);
1964
1965 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
1966 }
aa6c1ced 1967
76d9df3f
SH
1968 // Log the event entry.
1969 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
1970
1971 $repeatedids = array();
1972
1973 if (!empty($this->properties->repeat)) {
1974 $this->properties->repeatid = $this->properties->id;
1975 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
1976
1977 $eventcopy = clone($this->properties);
1978 unset($eventcopy->id);
1979
1980 for($i = 1; $i < $eventcopy->repeats; $i++) {
1981
1982 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
1983
1984 // Get the event id for the log record.
1985 $eventcopyid = $DB->insert_record('event', $eventcopy);
1986
1987 // If the context has been set delete all associated files
1988 if ($usingeditor) {
1989 $fs = get_file_storage();
64f93798 1990 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
1991 foreach ($files as $file) {
1992 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
1993 }
1994 }
1995
1996 $repeatedids[] = $eventcopyid;
1997 // Log the event entry.
1998 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
1999 }
2000 }
2001
2002 // Hook for tracking added events
2003 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2004 return true;
2005 } else {
2006
1d5bd3d2
DC
2007 if ($checkcapability) {
2008 if(!calendar_edit_event_allowed($this->properties)) {
2009 print_error('nopermissiontoupdatecalendar');
2010 }
76d9df3f
SH
2011 }
2012
2013 if ($usingeditor) {
2014 if ($this->editorcontext !== null) {
2015 $this->properties->description = file_save_draft_area_files(
2016 $this->properties->description['itemid'],
2017 $this->editorcontext->id,
64f93798
PS
2018 'calendar',
2019 'event_description',
76d9df3f
SH
2020 $this->properties->id,
2021 $this->editoroptions,
2022 $this->properties->description['text'],
2023 $this->editoroptions['forcehttps']);
2024 } else {
2025 $this->properties->format = $this->properties->description['format'];
2026 $this->properties->description = $this->properties->description['text'];
2027 }
2028 }
2029
2030 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2031
2032 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2033
2034 if ($updaterepeated) {
2035 // Update all
2036 if ($this->properties->timestart != $event->timestart) {
2037 $timestartoffset = $this->properties->timestart - $event->timestart;
2038 $sql = "UPDATE {event}
2039 SET name = ?,
2040 description = ?,
2041 timestart = timestart + ?,
2042 timeduration = ?,
2043 timemodified = ?
2044 WHERE repeatid = ?";
2045 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2046 } else {
2047 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2048 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2049 }
2050 $DB->execute($sql, $params);
2051
2052 // Log the event update.
2053 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2054 } else {
2055 $DB->update_record('event', $this->properties);
ddaff608
SH
2056 $event = calendar_event::load($this->properties->id);
2057 $this->properties = $event->properties();
76d9df3f
SH
2058 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2059 }
2060
2061 // Hook for tracking event updates
2062 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2063 return true;
2064 }
2065 }
2066
2067 /**
2068 * Deletes an event and if selected an repeated events in the same series
2069 *
2070 * This function deletes an event, any associated events if $deleterepeated=true,
2071 * and cleans up any files associated with the events.
2072 *
2073 * @see delete_event()
2074 *
2075 * @param bool $deleterepeated
2076 * @return bool
2077 */
2078 public function delete($deleterepeated=false) {
f4700b91 2079 global $DB;
76d9df3f
SH
2080
2081 // If $this->properties->id is not set then something is wrong
2082 if (empty($this->properties->id)) {
2083 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2084 return false;
2085 }
2086
2087 // Delete the event
2088 $DB->delete_records('event', array('id'=>$this->properties->id));
2089
2090 // If the editor context hasn't already been set then set it now
2091 if ($this->editorcontext === null) {
f4700b91 2092 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2093 }
2094
2095 // If the context has been set delete all associated files
2096 if ($this->editorcontext !== null) {
2097 $fs = get_file_storage();
64f93798 2098 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2099 foreach ($files as $file) {
2100 $file->delete();
2101 }
2102 }
2103
2104 // Fire the event deleted hook
2105 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2106
2107 // If we need to delete repeated events then we will fetch them all and delete one by one
2108 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2109 // Get all records where the repeatid is the same as the event being removed
2110 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2111 // For each of the returned events populate a calendar_event object and call delete
2112 // make sure the arg passed is false as we are already deleting all repeats
2113 foreach ($events as $event) {
2114 $event = new calendar_event($event);
2115 $event->delete(false);
2116 }
2117 }
2118
2119 return true;
2120 }
2121
2122 /**
2123 * Fetch all event properties
2124 *
2125 * This function returns all of the events properties as an object and optionally
2126 * can prepare an editor for the description field at the same time. This is
2127 * designed to work when the properties are going to be used to set the default
2128 * values of a moodle forms form.
2129 *
2130 * @param bool $prepareeditor If set to true a editor is prepared for use with
2131 * the mforms editor element. (for description)
2132 * @return stdClass Object containing event properties
2133 */
2134 public function properties($prepareeditor=false) {
2135 global $USER, $CFG, $DB;
2136
2137 // First take a copy of the properties. We don't want to actually change the
2138 // properties or we'd forever be converting back and forwards between an
2139 // editor formatted description and not
2140 $properties = clone($this->properties);
2141 // Clean the description here
2142 $properties->description = clean_text($properties->description, $properties->format);
2143
2144 // If set to true we need to prepare the properties for use with an editor
2145 // and prepare the file area
2146 if ($prepareeditor) {
2147
2148 // We may or may not have a property id. If we do then we need to work
2149 // out the context so we can copy the existing files to the draft area
2150 if (!empty($properties->id)) {
2151
2152 if ($properties->eventtype === 'site') {
2153 // Site context
f4700b91 2154 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2155 } else if ($properties->eventtype === 'user') {
2156 // User context
f4700b91 2157 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2158 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2159 // First check the course is valid
2160 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2161 if (!$course) {
2162 print_error('invalidcourse');
2163 }
2164 // Course context
f4700b91 2165 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2166 // We have a course and are within the course context so we had
2167 // better use the courses max bytes value
2168 $this->editoroptions['maxbytes'] = $course->maxbytes;
2169 } else {
2170 // If we get here we have a custom event type as used by some
2171 // modules. In this case the event will have been added by
2172 // code and we won't need the editor
2173 $this->editoroptions['maxbytes'] = 0;
2174 $this->editoroptions['maxfiles'] = 0;
2175 }
2176
2177 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2178 $contextid = false;
2179 } else {
2180 // Get the context id that is what we really want
2181 $contextid = $this->editorcontext->id;
2182 }
2183 } else {
2184
2185 // If we get here then this is a new event in which case we don't need a
2186 // context as there is no existing files to copy to the draft area.
2187 $contextid = null;
2188 }
2189
2190 // If the contextid === false we don't support files so no preparing
2191 // a draft area
2192 if ($contextid !== false) {
2193 // Just encase it has already been submitted
2194 $draftiddescription = file_get_submitted_draft_itemid('description');
2195 // Prepare the draft area, this copies existing files to the draft area as well
64f93798 2196 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
76d9df3f
SH
2197 } else {
2198 $draftiddescription = 0;
2199 }
aa6c1ced 2200
76d9df3f
SH
2201 // Structure the description field as the editor requires
2202 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2203 }
2204
2205 // Finally return the properties
2206 return $properties;
2207 }
2208
2209 /**
2210 * Toggles the visibility of an event
2211 *
2212 * @param null|bool $force If it is left null the events visibility is flipped,
2213 * If it is false the event is made hidden, if it is true it
2214 * is made visible.
2215 */
2216 public function toggle_visibility($force=null) {
2217 global $CFG, $DB;
2218
2219 // Set visible to the default if it is not already set
2220 if (empty($this->properties->visible)) {
2221 $this->properties->visible = 1;
2222 }
2223
2224 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2225 // Make this event visible
2226 $this->properties->visible = 1;
2227 // Fire the hook
2228 self::calendar_event_hook('show_event', array($this->properties));
2229 } else {
2230 // Make this event hidden
2231 $this->properties->visible = 0;
2232 // Fire the hook
2233 self::calendar_event_hook('hide_event', array($this->properties));
2234 }
2235
2236 // Update the database to reflect this change
2237 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2238 }
2239
2240 /**
2241 * Attempts to call the hook for the specified action should a calendar type
2242 * by set $CFG->calendar, and the appopriate function defined
2243 *
2244 * @static
2245 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2246 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2247 * @param array $args The args to pass to the hook, usually the event is the first element
2248 * @return bool
2249 */
2250 public static function calendar_event_hook($action, array $args) {
2251 global $CFG;
2252 static $extcalendarinc;
2253 if ($extcalendarinc === null) {
2254 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2255 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2256 $extcalendarinc = true;
2257 } else {
2258 $extcalendarinc = false;
2259 }
2260 }
2261 if($extcalendarinc === false) {
2262 return false;
2263 }
438e4add 2264 $hook = $CFG->calendar .'_'.$action;
76d9df3f
SH
2265 if (function_exists($hook)) {
2266 call_user_func_array($hook, $args);
2267 return true;
2268 }
2269 return false;
2270 }
2271
2272 /**
2273 * Returns a calendar_event object when provided with an event id
2274 *
2275 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2276 * it will result in an exception being thrown
2277 *
fd699564 2278 * @param int|object $param
76d9df3f
SH
2279 * @return calendar_event|false
2280 */
fd699564 2281 public static function load($param) {
76d9df3f 2282 global $DB;
fd699564
SH
2283 if (is_object($param)) {
2284 $event = new calendar_event($param);
2285 } else {
2286 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2287 $event = new calendar_event($event);
2288 }
76d9df3f
SH
2289 return $event;
2290 }
2291
2292 /**
2293 * Creates a new event and returns a calendar_event object
2294 *
2295 * @param object|array $properties An object containing event properties
2296 * @return calendar_event|false The event object or false if it failed
2297 */
2298 public static function create($properties) {
2299 if (is_array($properties)) {
2300 $properties = (object)$properties;
2301 }
2302 if (!is_object($properties)) {
2303 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2304 }
f4700b91 2305 $event = new calendar_event($properties);
76d9df3f
SH
2306 if ($event->update($properties)) {
2307 return $event;
2308 } else {
2309 return false;
2310 }
2311 }
2312}
36dc3b71
SH
2313
2314/**
2315 * Calendar information class
2316 *
2317 * This class is used simply to organise the information pertaining to a calendar
2318 * and is used primarily to make information easily available.
2319 */
2320class calendar_information {
2321 /**
2322 * The day
2323 * @var int
2324 */
2325 public $day;
2326 /**
2327 * The month
2328 * @var int
2329 */
2330 public $month;
2331 /**
2332 * The year
2333 * @var int
2334 */
2335 public $year;
2336
2337 /**
2338 * A course id
2339 * @var int
2340 */
2341 public $courseid = null;
2342 /**
2343 * An array of courses
2344 * @var array
2345 */
2346 public $courses = array();
2347 /**
2348 * An array of groups
2349 * @var array
2350 */
2351 public $groups = array();
2352 /**
2353 * An array of users
2354 * @var array
2355 */
2356 public $users = array();
2357
2358 /**
2359 * Creates a new instance
2360 *
2361 * @param int $day
2362 * @param int $month
2363 * @param int $year
2364 */
d8d8bdd9
SH
2365 public function __construct($day=0, $month=0, $year=0) {
2366
2367 $date = usergetdate(time());
2368
2369 if (empty($day)) {
2370 $day = $date['mday'];
2371 }
2372
2373 if (empty($month)) {
2374 $month = $date['mon'];
2375 }
2376
2377 if (empty($year)) {
2378 $year = $date['year'];
2379 }
2380
36dc3b71
SH
2381 $this->day = $day;
2382 $this->month = $month;
2383 $this->year = $year;
2384 }
2385
797cedc7
SH
2386 /**
2387 *
2388 * @param stdClass $course
2389 * @param array $coursestoload An array of courses [$course->id => $course]
2390 * @param type $ignorefilters
2391 */
2392 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2393 $this->courseid = $course->id;
2394 $this->course = $course;
2395 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2396 $this->courses = $courses;
2397 $this->groups = $group;
2398 $this->users = $user;
2399 }
2400
36dc3b71
SH
2401 /**
2402 * Ensures the date for the calendar is correct and either sets it to now
2403 * or throws a moodle_exception if not
2404 *
2405 * @param bool $defaultonow
2406 * @return bool
2407 */
2408 public function checkdate($defaultonow = true) {
2409 if (!checkdate($this->month, $this->day, $this->year)) {
2410 if ($defaultonow) {
2411 $now = usergetdate(time());
2412 $this->day = intval($now['mday']);
2413 $this->month = intval($now['mon']);
2414 $this->year = intval($now['year']);
2415 return true;
2416 } else {
2417 throw new moodle_exception('invaliddate');
2418 }
2419 }
2420 return true;
2421 }
2422 /**
2423 * Gets todays timestamp for the calendar
2424 * @return int
2425 */
2426 public function timestamp_today() {
2427 return make_timestamp($this->year, $this->month, $this->day);
2428 }
2429 /**
2430 * Gets tomorrows timestamp for the calendar
2431 * @return int
2432 */
2433 public function timestamp_tomorrow() {
2434 return make_timestamp($this->year, $this->month, $this->day+1);
2435 }
2436 /**
2437 * Adds the pretend blocks for teh calendar
2438 *
2439 * @param core_calendar_renderer $renderer
2440 * @param bool $showfilters
2441 * @param string|null $view
2442 */
2443 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2444 if ($showfilters) {
2445 $filters = new block_contents();
2446 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2447 $filters->footer = '';
2448 $filters->title = get_string('eventskey', 'calendar');
2449 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2450 }
2451 $block = new block_contents;
2452 $block->content = $renderer->fake_block_threemonths($this);
2453 $block->footer = '';
2454 $block->title = get_string('monthlyview', 'calendar');
2455 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2456 }
1d5bd3d2 2457}