calendar/lib: calendar_set_filters() use pre-fetched context and course recs
[moodle-pu.git] / calendar / event.php
blob7d9aab24adb9d08b71e933a06646bb98aa58f4cb
1 <?php // $Id$
3 /////////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Calendar extension //
8 // //
9 // Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10 // //
11 // Designed by: //
12 // Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13 // Jon Papaioannou (pj@moodle.org) //
14 // //
15 // Programming and development: //
16 // Jon Papaioannou (pj@moodle.org) //
17 // //
18 // For bugs, suggestions, etc contact: //
19 // Jon Papaioannou (pj@moodle.org) //
20 // //
21 // The current module was developed at the University of Macedonia //
22 // (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23 // The aim of this project is to provide additional and improved //
24 // functionality to the Asynchronous Distance Education service that the //
25 // Greek School Network deploys. //
26 // //
27 // This program is free software; you can redistribute it and/or modify //
28 // it under the terms of the GNU General Public License as published by //
29 // the Free Software Foundation; either version 2 of the License, or //
30 // (at your option) any later version. //
31 // //
32 // This program is distributed in the hope that it will be useful, //
33 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
34 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35 // GNU General Public License for more details: //
36 // //
37 // http://www.gnu.org/copyleft/gpl.html //
38 // //
39 /////////////////////////////////////////////////////////////////////////////
41 require_once('../config.php');
42 require_once($CFG->dirroot.'/calendar/lib.php');
43 require_once($CFG->dirroot.'/course/lib.php');
44 require_once($CFG->dirroot.'/mod/forum/lib.php');
46 require_login();
48 $action = required_param('action', PARAM_ALPHA);
49 $eventid = optional_param('id', 0, PARAM_INT);
50 $eventtype = optional_param('type', 'select', PARAM_ALPHA);
51 $urlcourse = optional_param('course', 0, PARAM_INT);
52 $cal_y = optional_param('cal_y');
53 $cal_m = optional_param('cal_m');
54 $cal_d = optional_param('cal_d');
56 if(isguest()) {
57 // Guests cannot do anything with events
58 redirect(CALENDAR_URL.'view.php?view=upcoming&amp;course='.$urlcourse);
61 $focus = '';
63 if(!$site = get_site()) {
64 redirect($CFG->wwwroot.'/'.$CFG->admin.'/index.php');
67 $strcalendar = get_string('calendar', 'calendar');
69 // Initialize the session variables
70 calendar_session_vars();
72 $now = usergetdate(time());
73 $navlinks = array();
74 $calendar_navlink = array('name' => $strcalendar,
75 'link' =>calendar_get_link_href(CALENDAR_URL.'view.php?view=upcoming&amp;course='.$urlcourse.'&amp;',
76 $now['mday'], $now['mon'], $now['year']),
77 'type' => 'misc');
79 $day = intval($now['mday']);
80 $mon = intval($now['mon']);
81 $yr = intval($now['year']);
83 if ($usehtmleditor = can_use_richtext_editor()) {
84 $defaultformat = FORMAT_HTML;
85 } else {
86 $defaultformat = FORMAT_MOODLE;
89 // If a course has been supplied in the URL, change the filters to show that one
90 if($urlcourse > 0 && record_exists('course', 'id', $urlcourse)) {
91 require_login($urlcourse, false);
93 if($urlcourse == SITEID) {
94 // If coming from the site page, show all courses
95 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
96 calendar_set_referring_course(0);
98 else {
99 // Otherwise show just this one
100 $SESSION->cal_courses_shown = $urlcourse;
101 calendar_set_referring_course($SESSION->cal_courses_shown);
105 switch($action) {
106 case 'delete':
107 $title = get_string('deleteevent', 'calendar');
108 $event = get_record('event', 'id', $eventid);
109 if($event === false) {
110 error('Invalid event');
112 if(!calendar_edit_event_allowed($event)) {
113 error('You are not authorized to do this');
115 break;
117 case 'edit':
118 $title = get_string('editevent', 'calendar');
119 $event = get_record('event', 'id', $eventid);
120 $repeats = optional_param('repeats', 0, PARAM_INT);
122 if($event === false) {
123 error('Invalid event');
125 if(!calendar_edit_event_allowed($event)) {
126 error('You are not authorized to do this');
129 if($form = data_submitted()) {
131 $form->name = clean_param(strip_tags($form->name,'<lang><span>'), PARAM_CLEAN);
133 $form->timestart = make_timestamp($form->startyr, $form->startmon, $form->startday, $form->starthr, $form->startmin);
134 if($form->duration == 1) {
135 $form->timeduration = make_timestamp($form->endyr, $form->endmon, $form->endday, $form->endhr, $form->endmin) - $form->timestart;
136 if($form->timeduration < 0) {
137 $form->timeduration = 0;
140 else if($form->duration == 2) {
141 $form->timeduration = $form->minutes * MINSECS;
143 else {
144 $form->timeduration = 0;
147 validate_form($form, $err);
149 if (count($err) == 0) {
151 if($event->repeatid && $repeats) {
152 // Update all
153 if($form->timestart >= $event->timestart) {
154 $timestartoffset = 'timestart + '.($form->timestart - $event->timestart);
156 else {
157 $timestartoffset = 'timestart - '.($event->timestart - $form->timestart);
160 execute_sql('UPDATE '.$CFG->prefix.'event SET '.
161 'name = '.$db->qstr($form->name).','.
162 'description = '.$db->qstr($form->description).','.
163 'timestart = '.$timestartoffset.','.
164 'timeduration = '.$form->timeduration.','.
165 'timemodified = '.time().' WHERE repeatid = '.$event->repeatid);
167 /// Log the event update.
168 $form->name = stripslashes($form->name); //To avoid double-slashes
169 add_to_log($form->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$form->id, $form->name);
172 else {
173 // Update this
174 $form->timemodified = time();
175 update_record('event', $form);
177 /// Log the event update.
178 $form->name = stripslashes($form->name); //To avoid double-slashes
179 add_to_log($form->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$form->id, $form->name);
182 // OK, now redirect to day view
183 redirect(CALENDAR_URL.'view.php?view=day&amp;course='.$urlcourse.'&cal_d='.$form->startday.'&cal_m='.$form->startmon.'&cal_y='.$form->startyr);
185 else {
186 foreach ($err as $key => $value) {
187 $focus = 'form.'.$key;
191 break;
193 case 'new':
194 $title = get_string('newevent', 'calendar');
195 $form = data_submitted();
196 if(!empty($form) && !empty($form->name)) {
198 $form->name = clean_text(strip_tags($form->name, '<lang><span>'));
200 $form->timestart = make_timestamp($form->startyr, $form->startmon, $form->startday, $form->starthr, $form->startmin);
201 if($form->duration == 1) {
202 $form->timeduration = make_timestamp($form->endyr, $form->endmon, $form->endday, $form->endhr, $form->endmin) - $form->timestart;
203 if($form->timeduration < 0) {
204 $form->timeduration = 0;
207 else if ($form->duration == 2) {
208 $form->timeduration = $form->minutes * MINSECS;
210 else {
211 $form->timeduration = 0;
213 if(!calendar_add_event_allowed($form)) {
214 error('You are not authorized to do this');
216 validate_form($form, $err);
217 if (count($err) == 0) {
218 $form->timemodified = time();
220 if ($form->repeat) {
221 $fetch = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix.'event');
222 $form->repeatid = empty($fetch) ? 1 : $fetch->repeatid + 1;
225 /// Get the event id for the log record.
226 $eventid = insert_record('event', $form, true);
228 /// Log the event entry.
229 add_to_log($form->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventid, stripslashes($form->name));
231 if ($form->repeat) {
232 for($i = 1; $i < $form->repeats; $i++) {
233 // What's the DST offset for the previous repeat?
234 $dst_offset_prev = dst_offset_on($form->timestart);
236 $form->timestart += WEEKSECS;
238 // If the offset has changed in the meantime, update this repeat accordingly
239 $form->timestart += $dst_offset_prev - dst_offset_on($form->timestart);
241 /// Get the event id for the log record.
242 $eventid = insert_record('event', $form, true);
244 /// Log the event entry.
245 add_to_log($form->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventid, stripslashes($form->name));
248 // OK, now redirect to day view
249 redirect(CALENDAR_URL.'view.php?view=day&amp;course='.$urlcourse.'&cal_d='.$form->startday.'&cal_m='.$form->startmon.'&cal_y='.$form->startyr);
251 else {
252 foreach ($err as $key => $value) {
253 $focus = 'form.'.$key;
257 break;
258 default: // no action
259 $title='';
260 break;
264 if (!empty($SESSION->cal_course_referer)) {
265 // TODO: This is part of the Great $course Hack in Moodle. Replace it at some point.
266 $course = get_record('course', 'id', $SESSION->cal_course_referer);
267 } else {
268 $course = $site;
270 require_login($course, false);
272 $navlinks[] = $calendar_navlink;
273 $navlinks[] = array('name' => $title, 'link' => null, 'type' => 'misc');
274 $navigation = build_navigation($navlinks);
275 print_header($site->shortname.': '.$strcalendar.': '.$title, $strcalendar, $navigation,
276 'eventform.name', '', true, '', user_login_string($site));
278 echo calendar_overlib_html();
280 echo '<table id="calendar">';
281 echo '<tr><td class="maincalendar">';
283 switch($action) {
284 case 'delete':
285 $confirm = optional_param('confirm', 0, PARAM_INT);
286 $repeats = optional_param('repeats', 0, PARAM_INT);
287 if($confirm) {
288 // Kill it and redirect to day view
289 if(($event = get_record('event', 'id', $eventid)) !== false) {
291 if($event->repeatid && $repeats) {
292 delete_records('event', 'repeatid', $event->repeatid);
293 add_to_log($event->courseid, 'calendar', 'delete all', '', $event->name);
295 else {
296 delete_records('event', 'id', $eventid);
297 add_to_log($event->courseid, 'calendar', 'delete', '', $event->name);
301 redirect(CALENDAR_URL.'view.php?view=day&amp;course='.$urlcourse.'&cal_d='.$_REQUEST['d'].'&cal_m='.$_REQUEST['m'].'&cal_y='.$_REQUEST['y']);
304 else {
305 $eventtime = usergetdate($event->timestart);
306 $m = $eventtime['mon'];
307 $d = $eventtime['mday'];
308 $y = $eventtime['year'];
310 if($event->repeatid) {
311 $fetch = get_record_sql('SELECT 1, COUNT(id) AS repeatcount FROM '.$CFG->prefix.'event WHERE repeatid = '.$event->repeatid);
312 $repeatcount = $fetch->repeatcount;
314 else {
315 $repeatcount = 0;
318 // Display confirmation form
319 echo '<div class="header">'.get_string('deleteevent', 'calendar').': '.$event->name.'</div>';
320 echo '<h2>'.get_string('confirmeventdelete', 'calendar').'</h2>';
321 if($repeatcount > 1) {
322 echo '<p>'.get_string('youcandeleteallrepeats', 'calendar', $repeatcount).'</p>';
324 echo '<div class="eventlist">';
325 $event->time = calendar_format_event_time($event, time(), '', false);
326 calendar_print_event($event);
327 echo '</div>';
328 include('event_delete.html');
330 break;
332 case 'edit':
333 if(empty($form)) {
334 $form->name = $event->name;
335 $form->courseid = $event->courseid; // Not to update, but for date validation
336 $form->description = $event->description;
337 $form->timestart = $event->timestart;
338 $form->timeduration = $event->timeduration;
339 $form->id = $event->id;
340 $form->format = $defaultformat;
341 if($event->timeduration > HOURSECS) {
342 // More than one hour, so default to normal duration mode
343 $form->duration = 1;
344 $form->minutes = '';
346 else if($event->timeduration) {
347 // Up to one hour, "minutes" mode probably is better here
348 $form->duration = 2;
349 $form->minutes = $event->timeduration / MINSECS;
351 else {
352 // No duration
353 $form->duration = 0;
354 $form->minutes = '';
358 if (!empty($form->courseid)) {
359 // TODO: This is part of the Great $course Hack in Moodle. Replace it at some point.
360 $course = get_record('course', 'id', $form->courseid);
361 } else {
362 $course = $site;
365 if($event->repeatid) {
366 $fetch = get_record_sql('SELECT 1, COUNT(id) AS repeatcount FROM '.$CFG->prefix.'event WHERE repeatid = '.$event->repeatid);
367 $repeatcount = $fetch->repeatcount;
369 else {
370 $repeatcount = 0;
373 echo '<div class="header">'.get_string('editevent', 'calendar').'</div>';
374 include('event_edit.html');
375 if ($usehtmleditor) {
376 use_html_editor("description");
378 break;
380 case 'new':
381 if($cal_y && $cal_m && $cal_d && checkdate($cal_m, $cal_d, $cal_y)) {
382 $form->timestart = make_timestamp($cal_y, $cal_m, $cal_d, 0, 0, 0);
384 else if($cal_y && $cal_m && checkdate($cal_m, 1, $cal_y)) {
385 if($cal_y == $now['year'] && $cal_m == $now['mon']) {
386 $form->timestart = make_timestamp($cal_y, $cal_m, $now['mday'], 0, 0, 0);
388 else {
389 $form->timestart = make_timestamp($cal_y, $cal_m, 1, 0, 0, 0);
392 if(!isset($form->timestart) or $form->timestart < 0) {
393 $form->timestart = time();
396 calendar_get_allowed_types($allowed);
397 if(!$allowed->groups && !$allowed->courses && !$allowed->site) {
398 // Take the shortcut
399 $eventtype = 'user';
402 $header = '';
404 switch($eventtype) {
405 case 'user':
406 $form->name = '';
407 $form->description = '';
408 $form->courseid = 0;
409 $form->groupid = 0;
410 $form->userid = $USER->id;
411 $form->modulename = '';
412 $form->eventtype = '';
413 $form->instance = 0;
414 $form->timeduration = 0;
415 $form->duration = 0;
416 $form->repeat = 0;
417 $form->repeats = '';
418 $form->minutes = '';
419 $form->type = 'user';
420 $header = get_string('typeuser', 'calendar');
421 break;
422 case 'group':
423 $groupid = optional_param('groupid', 0, PARAM_INT);
424 if (! ($group = groups_get_group($groupid))) { //TODO:check.
425 calendar_get_allowed_types($allowed);
426 $eventtype = 'select';
428 else {
429 $form->name = '';
430 $form->description = '';
431 $form->courseid = $group->courseid;
432 $form->groupid = $group->id;
433 $form->userid = $USER->id;
434 $form->modulename = '';
435 $form->eventtype = '';
436 $form->instance = 0;
437 $form->timeduration = 0;
438 $form->duration = 0;
439 $form->repeat = 0;
440 $form->repeats = '';
441 $form->minutes = '';
442 $form->type = 'group';
443 $header = get_string('typegroup', 'calendar');
445 break;
446 case 'course':
447 $courseid = optional_param('courseid', 0, PARAM_INT);
448 if(!record_exists('course', 'id', $courseid)) {
449 calendar_get_allowed_types($allowed);
450 $eventtype = 'select';
452 else {
453 $form->name = '';
454 $form->description = '';
455 $form->courseid = $courseid;
456 $form->groupid = 0;
457 $form->userid = $USER->id;
458 $form->modulename = '';
459 $form->eventtype = '';
460 $form->instance = 0;
461 $form->timeduration = 0;
462 $form->duration = 0;
463 $form->repeat = 0;
464 $form->repeats = '';
465 $form->minutes = '';
466 $form->type = 'course';
467 $header = get_string('typecourse', 'calendar');
469 break;
470 case 'site':
471 $form->name = '';
472 $form->description = '';
473 $form->courseid = SITEID;
474 $form->groupid = 0;
475 $form->userid = $USER->id;
476 $form->modulename = '';
477 $form->eventtype = '';
478 $form->instance = 0;
479 $form->timeduration = 0;
480 $form->duration = 0;
481 $form->repeat = 0;
482 $form->repeats = '';
483 $form->minutes = '';
484 $form->type = 'site';
485 $header = get_string('typesite', 'calendar');
486 break;
487 case 'select':
488 break;
489 default:
490 error('Unsupported event type');
493 $form->format = $defaultformat;
494 if(!empty($header)) {
495 $header = ' ('.$header.')';
498 echo '<div class="header">'.get_string('newevent', 'calendar').$header.'</div>';
500 if($eventtype == 'select') {
501 $courseid = optional_param('courseid', $SESSION->cal_course_referer, PARAM_INT);
502 if ($courseid == 0) { // workaround by Dan for bug #6130
503 $courseid = SITEID;
505 if (!$course = get_record('course', 'id', $courseid)) {
506 error('Incorrect course ID');
509 $groupid = groups_get_course_group($course);
511 echo '<h2>'.get_string('eventkind', 'calendar').':</h2>';
512 echo '<div id="selecteventtype">';
513 include('event_select.html');
514 echo '</div>';
516 else {
517 include('event_new.html');
518 if ($usehtmleditor) {
519 use_html_editor("description");
523 break;
525 echo '</td>';
527 // START: Last column (3-month display)
529 $defaultcourses = calendar_get_default_courses();
530 calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses);
531 list($prevmon, $prevyr) = calendar_sub_month($mon, $yr);
532 list($nextmon, $nextyr) = calendar_add_month($mon, $yr);
534 echo '<td class="sidecalendar">';
535 echo '<div class="sideblock">';
536 echo '<div class="header">'.get_string('eventskey', 'calendar').'</div>';
537 echo '<div class="filters">';
538 echo calendar_filter_controls('event', 'action='.$action.'&amp;type='.$eventtype.'&amp;id='.$eventid);
539 echo '</div>';
540 echo '</div>';
542 echo '<div class="sideblock">';
543 echo '<div class="header">'.get_string('monthlyview', 'calendar').'</div>';
544 echo '<div class="minicalendarblock minicalendartop">';
545 echo calendar_top_controls('display', array('id' => $urlcourse, 'm' => $prevmon, 'y' => $prevyr));
546 echo calendar_get_mini($courses, $groups, $users, $prevmon, $prevyr);
547 echo '</div><div class="minicalendarblock">';
548 echo calendar_top_controls('display', array('id' => $urlcourse, 'm' => $mon, 'y' => $yr));
549 echo calendar_get_mini($courses, $groups, $users, $mon, $yr);
550 echo '</div><div class="minicalendarblock">';
551 echo calendar_top_controls('display', array('id' => $urlcourse, 'm' => $nextmon, 'y' => $nextyr));
552 echo calendar_get_mini($courses, $groups, $users, $nextmon, $nextyr);
553 echo '</div>';
554 echo '</div>';
556 echo '</td>';
557 echo '</tr></table>';
559 print_footer();
562 function validate_form(&$form, &$err) {
564 $form->name = trim($form->name);
565 $form->description = trim($form->description);
567 if(empty($form->name)) {
568 $err['name'] = get_string('errornoeventname', 'calendar');
570 /* Allow events without a description
571 if(empty($form->description)) {
572 $err['description'] = get_string('errornodescription', 'calendar');
575 if(!checkdate($form->startmon, $form->startday, $form->startyr)) {
576 $err['timestart'] = get_string('errorinvaliddate', 'calendar');
578 if($form->duration == 2 and !checkdate($form->endmon, $form->endday, $form->endyr)) {
579 $err['timeduration'] = get_string('errorinvaliddate', 'calendar');
581 if($form->duration == 2 and !($form->minutes > 0 and $form->minutes < 1000)) {
582 $err['minutes'] = get_string('errorinvalidminutes', 'calendar');
584 if (!empty($form->repeat) and !($form->repeats > 1 and $form->repeats < 100)) {
585 $err['repeats'] = get_string('errorinvalidrepeats', 'calendar');
587 if(!empty($form->courseid)) {
588 // Timestamps must be >= course startdate
589 $course = get_record('course', 'id', $form->courseid);
590 if($course === false) {
591 error('Event belongs to invalid course');
593 else if($form->timestart < $course->startdate) {
594 $err['timestart'] = get_string('errorbeforecoursestart', 'calendar');
599 function calendar_add_event_allowed($event) {
600 global $USER;
602 // can not be using guest account
603 if (empty($USER->id) or $USER->username == 'guest') {
604 return false;
607 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
608 // if user has manageentries at site level, always return true
609 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
610 return true;
613 switch ($event->type) {
614 case 'course':
615 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
617 case 'group':
618 if (! groups_group_exists($event->groupid)) { //TODO:check.
619 return false;
621 // this is ok because if you have this capability at course level, you should be able
622 // to edit group calendar too
623 // there is no need to check membership, because if you have this capability
624 // you will have a role in this group context
625 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
627 case 'user':
628 if ($event->userid == $USER->id) {
629 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
631 //there is no 'break;' intentionally
633 case 'site':
634 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
636 default:
637 return false;