comparison forum/Sources/Subs-Calendar.php @ 76:e3e11437ecea website

Add forum code
author Chris Cannam
date Sun, 07 Jul 2013 11:25:48 +0200
parents
children
comparison
equal deleted inserted replaced
75:72f59aa7e503 76:e3e11437ecea
1 <?php
2
3 /**
4 * Simple Machines Forum (SMF)
5 *
6 * @package SMF
7 * @author Simple Machines http://www.simplemachines.org
8 * @copyright 2011 Simple Machines
9 * @license http://www.simplemachines.org/about/smf/license.php BSD
10 *
11 * @version 2.0
12 */
13
14 if (!defined('SMF'))
15 die('Hacking attempt...');
16
17 /* This file contains several functions for retrieving and manipulating
18 calendar events, birthdays and holidays.
19
20 array getBirthdayRange(string earliest_date, string latest_date)
21 - finds all the birthdays in the specified range of days.
22 - earliest_date and latest_date are inclusive, and should both be in
23 the YYYY-MM-DD format.
24 - works with birthdays set for no year, or any other year, and
25 respects month and year boundaries.
26 - returns an array of days, each of which an array of birthday
27 information for the context.
28
29 array getEventRange(string earliest_date, string latest_date,
30 bool use_permissions = true)
31 - finds all the posted calendar events within a date range.
32 - both the earliest_date and latest_date should be in the standard
33 YYYY-MM-DD format.
34 - censors the posted event titles.
35 - uses the current user's permissions if use_permissions is true,
36 otherwise it does nothing "permission specific".
37 - returns an array of contextual information if use_permissions is
38 true, and an array of the data needed to build that otherwise.
39
40 array getHolidayRange(string earliest_date, string latest_date)
41 - finds all the applicable holidays for the specified date range.
42 - earliest_date and latest_date should be YYYY-MM-DD.
43 - returns an array of days, which are all arrays of holiday names.
44
45 void canLinkEvent()
46 - checks if the current user can link the current topic to the
47 calendar, permissions et al.
48 - this requires the calendar_post permission, a forum moderator, or a
49 topic starter.
50 - expects the $topic and $board variables to be set.
51 - if the user doesn't have proper permissions, an error will be shown.
52
53 array getTodayInfo()
54 - returns an array with the current date, day, month, and year.
55 - takes the users time offset into account.
56
57 array getCalendarGrid(int month, int year, array calendarOptions)
58 - returns an array containing all the information needed to show a
59 calendar grid for the given month.
60 - also provides information (link, month, year) about the previous and
61 next month.
62
63 array getCalendarWeek(int month, int year, int day, array calendarOptions)
64 - as for getCalendarGrid but provides information relating to the week
65 within which the passed date sits.
66
67 array cache_getOffsetIndependentEvents(int days_to_index)
68 - cache callback function used to retrieve the birthdays, holidays, and
69 events between now and now + days_to_index.
70 - widens the search range by an extra 24 hours to support time offset
71 shifts.
72 - used by the cache_getRecentEvents function to get the information
73 needed to calculate the events taking the users time offset into
74 account.
75
76 array cache_getRecentEvents(array eventOptions)
77 - cache callback function used to retrieve the upcoming birthdays,
78 holidays, and events within the given period, taking into account
79 the users time offset.
80 - used by the board index and SSI to show the upcoming events.
81
82 void validateEventPost()
83 - checks if the calendar post was valid.
84
85 int getEventPoster(int event_id)
86 - gets the member_id of an event identified by event_id.
87 - returns false if the event was not found.
88
89 void insertEvent(array eventOptions)
90 - inserts the passed event information into the calendar table.
91 - allows to either set a time span (in days) or an end_date.
92 - does not check any permissions of any sort.
93
94 void modifyEvent(int event_id, array eventOptions)
95 - modifies an event.
96 - allows to either set a time span (in days) or an end_date.
97 - does not check any permissions of any sort.
98
99 void removeEvent(int event_id)
100 - removes an event.
101 - does no permission checks.
102 */
103
104 // Get all birthdays within the given time range.
105 function getBirthdayRange($low_date, $high_date)
106 {
107 global $scripturl, $modSettings, $smcFunc;
108
109 // We need to search for any birthday in this range, and whatever year that birthday is on.
110 $year_low = (int) substr($low_date, 0, 4);
111 $year_high = (int) substr($high_date, 0, 4);
112
113 // Collect all of the birthdays for this month. I know, it's a painful query.
114 $result = $smcFunc['db_query']('birthday_array', '
115 SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
116 FROM {db_prefix}members
117 WHERE YEAR(birthdate) != {string:year_one}
118 AND MONTH(birthdate) != {int:no_month}
119 AND DAYOFMONTH(birthdate) != {int:no_day}
120 AND YEAR(birthdate) <= {int:max_year}
121 AND (
122 DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
123 OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
124 )
125 AND is_activated = {int:is_activated}',
126 array(
127 'is_activated' => 1,
128 'no_month' => 0,
129 'no_day' => 0,
130 'year_one' => '0001',
131 'year_low' => $year_low . '-%m-%d',
132 'year_high' => $year_high . '-%m-%d',
133 'low_date' => $low_date,
134 'high_date' => $high_date,
135 'max_year' => $year_high,
136 )
137 );
138 $bday = array();
139 while ($row = $smcFunc['db_fetch_assoc']($result))
140 {
141 if ($year_low != $year_high)
142 $age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
143 else
144 $age_year = $year_low;
145
146 $bday[$age_year . substr($row['birthdate'], 4)][] = array(
147 'id' => $row['id_member'],
148 'name' => $row['real_name'],
149 'age' => $row['birth_year'] > 4 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
150 'is_last' => false
151 );
152 }
153 $smcFunc['db_free_result']($result);
154
155 // Set is_last, so the themes know when to stop placing separators.
156 foreach ($bday as $mday => $array)
157 $bday[$mday][count($array) - 1]['is_last'] = true;
158
159 return $bday;
160 }
161
162 // Get all events within the given time range.
163 function getEventRange($low_date, $high_date, $use_permissions = true)
164 {
165 global $scripturl, $modSettings, $user_info, $smcFunc, $context;
166
167 $low_date_time = sscanf($low_date, '%04d-%02d-%02d');
168 $low_date_time = mktime(0, 0, 0, $low_date_time[1], $low_date_time[2], $low_date_time[0]);
169 $high_date_time = sscanf($high_date, '%04d-%02d-%02d');
170 $high_date_time = mktime(0, 0, 0, $high_date_time[1], $high_date_time[2], $high_date_time[0]);
171
172 // Find all the calendar info...
173 $result = $smcFunc['db_query']('', '
174 SELECT
175 cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
176 cal.id_board, b.member_groups, t.id_first_msg, t.approved, b.id_board
177 FROM {db_prefix}calendar AS cal
178 LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
179 LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
180 WHERE cal.start_date <= {date:high_date}
181 AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
182 AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
183 array(
184 'high_date' => $high_date,
185 'low_date' => $low_date,
186 'no_board_link' => 0,
187 )
188 );
189 $events = array();
190 while ($row = $smcFunc['db_fetch_assoc']($result))
191 {
192 // If the attached topic is not approved then for the moment pretend it doesn't exist
193 //!!! This should be fixed to show them all and then sort by approval state later?
194 if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
195 continue;
196
197 // Force a censor of the title - as often these are used by others.
198 censorText($row['title'], $use_permissions ? false : true);
199
200 $start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
201 $start_date = max(mktime(0, 0, 0, $start_date[1], $start_date[2], $start_date[0]), $low_date_time);
202 $end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
203 $end_date = min(mktime(0, 0, 0, $end_date[1], $end_date[2], $end_date[0]), $high_date_time);
204
205 $lastDate = '';
206 for ($date = $start_date; $date <= $end_date; $date += 86400)
207 {
208 // Attempt to avoid DST problems.
209 //!!! Resolve this properly at some point.
210 if (strftime('%Y-%m-%d', $date) == $lastDate)
211 $date += 3601;
212 $lastDate = strftime('%Y-%m-%d', $date);
213
214 // If we're using permissions (calendar pages?) then just ouput normal contextual style information.
215 if ($use_permissions)
216 $events[strftime('%Y-%m-%d', $date)][] = array(
217 'id' => $row['id_event'],
218 'title' => $row['title'],
219 'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
220 'modify_href' => $scripturl . '?action=' . ($row['id_board'] == 0 ? 'calendar;sa=post;' : 'post;msg=' . $row['id_first_msg'] . ';topic=' . $row['id_topic'] . '.0;calendar;') . 'eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
221 'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
222 'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
223 'start_date' => $row['start_date'],
224 'end_date' => $row['end_date'],
225 'is_last' => false,
226 'id_board' => $row['id_board'],
227 );
228 // Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
229 else
230 $events[strftime('%Y-%m-%d', $date)][] = array(
231 'id' => $row['id_event'],
232 'title' => $row['title'],
233 'topic' => $row['id_topic'],
234 'msg' => $row['id_first_msg'],
235 'poster' => $row['id_member'],
236 'start_date' => $row['start_date'],
237 'end_date' => $row['end_date'],
238 'is_last' => false,
239 'allowed_groups' => explode(',', $row['member_groups']),
240 'id_board' => $row['id_board'],
241 'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
242 'link' => $row['id_topic'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
243 'can_edit' => false,
244 );
245 }
246 }
247 $smcFunc['db_free_result']($result);
248
249 // If we're doing normal contextual data, go through and make things clear to the templates ;).
250 if ($use_permissions)
251 {
252 foreach ($events as $mday => $array)
253 $events[$mday][count($array) - 1]['is_last'] = true;
254 }
255
256 return $events;
257 }
258
259 // Get all holidays within the given time range.
260 function getHolidayRange($low_date, $high_date)
261 {
262 global $smcFunc;
263
264 // Get the lowest and highest dates for "all years".
265 if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
266 $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
267 OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
268 else
269 $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
270
271 // Find some holidays... ;).
272 $result = $smcFunc['db_query']('', '
273 SELECT event_date, YEAR(event_date) AS year, title
274 FROM {db_prefix}calendar_holidays
275 WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
276 OR ' . $allyear_part,
277 array(
278 'low_date' => $low_date,
279 'high_date' => $high_date,
280 'all_year_low' => '0004' . substr($low_date, 4),
281 'all_year_high' => '0004' . substr($high_date, 4),
282 'all_year_jan' => '0004-01-01',
283 'all_year_dec' => '0004-12-31',
284 )
285 );
286 $holidays = array();
287 while ($row = $smcFunc['db_fetch_assoc']($result))
288 {
289 if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
290 $event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
291 else
292 $event_year = substr($low_date, 0, 4);
293
294 $holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
295 }
296 $smcFunc['db_free_result']($result);
297
298 return $holidays;
299 }
300
301 // Does permission checks to see if an event can be linked to a board/topic.
302 function canLinkEvent()
303 {
304 global $user_info, $topic, $board, $smcFunc;
305
306 // If you can't post, you can't link.
307 isAllowedTo('calendar_post');
308
309 // No board? No topic?!?
310 if (empty($board))
311 fatal_lang_error('missing_board_id', false);
312 if (empty($topic))
313 fatal_lang_error('missing_topic_id', false);
314
315 // Administrator, Moderator, or owner. Period.
316 if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
317 {
318 // Not admin or a moderator of this board. You better be the owner - or else.
319 $result = $smcFunc['db_query']('', '
320 SELECT id_member_started
321 FROM {db_prefix}topics
322 WHERE id_topic = {int:current_topic}
323 LIMIT 1',
324 array(
325 'current_topic' => $topic,
326 )
327 );
328 if ($row = $smcFunc['db_fetch_assoc']($result))
329 {
330 // Not the owner of the topic.
331 if ($row['id_member_started'] != $user_info['id'])
332 fatal_lang_error('not_your_topic', 'user');
333 }
334 // Topic/Board doesn't exist.....
335 else
336 fatal_lang_error('calendar_no_topic', 'general');
337 $smcFunc['db_free_result']($result);
338 }
339 }
340
341 // Returns date information about 'today' relative to the users time offset.
342 function getTodayInfo()
343 {
344 return array(
345 'day' => (int) strftime('%d', forum_time()),
346 'month' => (int) strftime('%m', forum_time()),
347 'year' => (int) strftime('%Y', forum_time()),
348 'date' => strftime('%Y-%m-%d', forum_time()),
349 );
350 }
351
352 // Returns the information needed to show a calendar grid for the given month.
353 function getCalendarGrid($month, $year, $calendarOptions)
354 {
355 global $scripturl, $modSettings;
356
357 // Eventually this is what we'll be returning.
358 $calendarGrid = array(
359 'week_days' => array(),
360 'weeks' => array(),
361 'short_day_titles' => !empty($calendarOptions['short_day_titles']),
362 'current_month' => $month,
363 'current_year' => $year,
364 'show_next_prev' => !empty($calendarOptions['show_next_prev']),
365 'show_week_links' => !empty($calendarOptions['show_week_links']),
366 'previous_calendar' => array(
367 'year' => $month == 1 ? $year - 1 : $year,
368 'month' => $month == 1 ? 12 : $month - 1,
369 'disabled' => $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
370 ),
371 'next_calendar' => array(
372 'year' => $month == 12 ? $year + 1 : $year,
373 'month' => $month == 12 ? 1 : $month + 1,
374 'disabled' => $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
375 ),
376 //!!! Better tweaks?
377 'size' => isset($calendarOptions['size']) ? $calendarOptions['size'] : 'large',
378 );
379
380 // Get todays date.
381 $today = getTodayInfo();
382
383 // Get information about this month.
384 $month_info = array(
385 'first_day' => array(
386 'day_of_week' => (int) strftime('%w', mktime(0, 0, 0, $month, 1, $year)),
387 'week_num' => (int) strftime('%U', mktime(0, 0, 0, $month, 1, $year)),
388 'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month, 1, $year)),
389 ),
390 'last_day' => array(
391 'day_of_month' => (int) strftime('%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
392 'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
393 ),
394 'first_day_of_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year)),
395 'first_day_of_next_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1)),
396 );
397
398 // The number of days the first row is shifted to the right for the starting day.
399 $nShift = $month_info['first_day']['day_of_week'];
400
401 $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
402
403 // Starting any day other than Sunday means a shift...
404 if (!empty($calendarOptions['start_day']))
405 {
406 $nShift -= $calendarOptions['start_day'];
407 if ($nShift < 0)
408 $nShift = 7 + $nShift;
409 }
410
411 // Number of rows required to fit the month.
412 $nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
413 if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
414 $nRows++;
415
416 // Fetch the arrays for birthdays, posted events, and holidays.
417 $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
418 $events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
419 $holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
420
421 // Days of the week taking into consideration that they may want it to start on any day.
422 $count = $calendarOptions['start_day'];
423 for ($i = 0; $i < 7; $i++)
424 {
425 $calendarGrid['week_days'][] = $count;
426 $count++;
427 if ($count == 7)
428 $count = 0;
429 }
430
431 // An adjustment value to apply to all calculated week numbers.
432 if (!empty($calendarOptions['show_week_num']))
433 {
434 // If the first day of the year is a Sunday, then there is no
435 // adjustment to be made. However, if the first day of the year is not
436 // a Sunday, then there is a partial week at the start of the year
437 // that needs to be accounted for.
438 if ($calendarOptions['start_day'] === 0)
439 $nWeekAdjust = $month_info['first_day_of_year'] === 0 ? 0 : 1;
440 // If we are viewing the weeks, with a starting date other than Sunday,
441 // then things get complicated! Basically, as PHP is calculating the
442 // weeks with a Sunday starting date, we need to take this into account
443 // and offset the whole year dependant on whether the first day in the
444 // year is above or below our starting date. Note that we offset by
445 // two, as some of this will get undone quite quickly by the statement
446 // below.
447 else
448 $nWeekAdjust = $calendarOptions['start_day'] > $month_info['first_day_of_year'] && $month_info['first_day_of_year'] !== 0 ? 2 : 1;
449
450 // If our week starts on a day greater than the day the month starts
451 // on, then our week numbers will be one too high. So we need to
452 // reduce it by one - all these thoughts of offsets makes my head
453 // hurt...
454 if ($month_info['first_day']['day_of_week'] < $calendarOptions['start_day'] || $month_info['first_day_of_year'] > 4)
455 $nWeekAdjust--;
456 }
457 else
458 $nWeekAdjust = 0;
459
460 // Iterate through each week.
461 $calendarGrid['weeks'] = array();
462 for ($nRow = 0; $nRow < $nRows; $nRow++)
463 {
464 // Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
465 $calendarGrid['weeks'][$nRow] = array(
466 'days' => array(),
467 'number' => $month_info['first_day']['week_num'] + $nRow + $nWeekAdjust
468 );
469 // Handle the dreaded "week 53", it can happen, but only once in a blue moon ;)
470 if ($calendarGrid['weeks'][$nRow]['number'] == 53 && $nShift != 4 && $month_info['first_day_of_next_year'] < 4)
471 $calendarGrid['weeks'][$nRow]['number'] = 1;
472
473 // And figure out all the days.
474 for ($nCol = 0; $nCol < 7; $nCol++)
475 {
476 $nDay = ($nRow * 7) + $nCol - $nShift + 1;
477
478 if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
479 $nDay = 0;
480
481 $date = sprintf('%04d-%02d-%02d', $year, $month, $nDay);
482
483 $calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
484 'day' => $nDay,
485 'date' => $date,
486 'is_today' => $date == $today['date'],
487 'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
488 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
489 'events' => !empty($events[$date]) ? $events[$date] : array(),
490 'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
491 );
492 }
493 }
494
495 // Set the previous and the next month's links.
496 $calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'];
497 $calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'];
498
499 return $calendarGrid;
500 }
501
502 // Returns the information needed to show a calendar for the given week.
503 function getCalendarWeek($month, $year, $day, $calendarOptions)
504 {
505 global $scripturl, $modSettings;
506
507 // Get todays date.
508 $today = getTodayInfo();
509
510 // What is the actual "start date" for the passed day.
511 $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
512 $day_of_week = (int) strftime('%w', mktime(0, 0, 0, $month, $day, $year));
513 if ($day_of_week != $calendarOptions['start_day'])
514 {
515 // Here we offset accordingly to get things to the real start of a week.
516 $date_diff = $day_of_week - $calendarOptions['start_day'];
517 if ($date_diff < 0)
518 $date_diff += 7;
519 $new_timestamp = mktime(0, 0, 0, $month, $day, $year) - $date_diff * 86400;
520 $day = (int) strftime('%d', $new_timestamp);
521 $month = (int) strftime('%m', $new_timestamp);
522 $year = (int) strftime('%Y', $new_timestamp);
523 }
524
525 // Now start filling in the calendar grid.
526 $calendarGrid = array(
527 'show_next_prev' => !empty($calendarOptions['show_next_prev']),
528 // Previous week is easy - just step back one day.
529 'previous_week' => array(
530 'year' => $day == 1 ? ($month == 1 ? $year - 1 : $year) : $year,
531 'month' => $day == 1 ? ($month == 1 ? 12 : $month - 1) : $month,
532 'day' => $day == 1 ? 28 : $day - 1,
533 'disabled' => $day < 7 && $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
534 ),
535 'next_week' => array(
536 'disabled' => $day > 25 && $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
537 ),
538 );
539
540 // The next week calculation requires a bit more work.
541 $curTimestamp = mktime(0, 0, 0, $month, $day, $year);
542 $nextWeekTimestamp = $curTimestamp + 604800;
543 $calendarGrid['next_week']['day'] = (int) strftime('%d', $nextWeekTimestamp);
544 $calendarGrid['next_week']['month'] = (int) strftime('%m', $nextWeekTimestamp);
545 $calendarGrid['next_week']['year'] = (int) strftime('%Y', $nextWeekTimestamp);
546
547 // Fetch the arrays for birthdays, posted events, and holidays.
548 $startDate = strftime('%Y-%m-%d', $curTimestamp);
549 $endDate = strftime('%Y-%m-%d', $nextWeekTimestamp);
550 $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($startDate, $endDate) : array();
551 $events = $calendarOptions['show_events'] ? getEventRange($startDate, $endDate) : array();
552 $holidays = $calendarOptions['show_holidays'] ? getHolidayRange($startDate, $endDate) : array();
553
554 // An adjustment value to apply to all calculated week numbers.
555 if (!empty($calendarOptions['show_week_num']))
556 {
557 $first_day_of_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year));
558 $first_day_of_next_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1));
559 $last_day_of_last_year = (int) strftime('%w', mktime(0, 0, 0, 12, 31, $year - 1));
560
561 // All this is as getCalendarGrid.
562 if ($calendarOptions['start_day'] === 0)
563 $nWeekAdjust = $first_day_of_year === 0 && $first_day_of_year > 3 ? 0 : 1;
564 else
565 $nWeekAdjust = $calendarOptions['start_day'] > $first_day_of_year && $first_day_of_year !== 0 ? 2 : 1;
566
567 $calendarGrid['week_number'] = (int) strftime('%U', mktime(0, 0, 0, $month, $day, $year)) + $nWeekAdjust;
568
569 // If this crosses a year boundry and includes january it should be week one.
570 if ((int) strftime('%Y', $curTimestamp + 518400) != $year && $calendarGrid['week_number'] > 53 && $first_day_of_next_year < 5)
571 $calendarGrid['week_number'] = 1;
572 }
573
574 // This holds all the main data - there is at least one month!
575 $calendarGrid['months'] = array();
576 $lastDay = 99;
577 $curDay = $day;
578 $curDayOfWeek = $calendarOptions['start_day'];
579 for ($i = 0; $i < 7; $i++)
580 {
581 // Have we gone into a new month (Always happens first cycle too)
582 if ($lastDay > $curDay)
583 {
584 $curMonth = $lastDay == 99 ? $month : ($month == 12 ? 1 : $month + 1);
585 $curYear = $lastDay == 99 ? $year : ($curMonth == 1 && $month == 12 ? $year + 1 : $year);
586 $calendarGrid['months'][$curMonth] = array(
587 'current_month' => $curMonth,
588 'current_year' => $curYear,
589 'days' => array(),
590 );
591 }
592
593 // Add todays information to the pile!
594 $date = sprintf('%04d-%02d-%02d', $curYear, $curMonth, $curDay);
595
596 $calendarGrid['months'][$curMonth]['days'][$curDay] = array(
597 'day' => $curDay,
598 'day_of_week' => $curDayOfWeek,
599 'date' => $date,
600 'is_today' => $date == $today['date'],
601 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
602 'events' => !empty($events[$date]) ? $events[$date] : array(),
603 'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
604 );
605
606 // Make the last day what the current day is and work out what the next day is.
607 $lastDay = $curDay;
608 $curTimestamp += 86400;
609 $curDay = (int) strftime('%d', $curTimestamp);
610
611 // Also increment the current day of the week.
612 $curDayOfWeek = $curDayOfWeek >= 6 ? 0 : ++$curDayOfWeek;
613 }
614
615 // Set the previous and the next week's links.
616 $calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
617 $calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];
618
619 return $calendarGrid;
620 }
621
622 // Retrieve all events for the given days, independently of the users offset.
623 function cache_getOffsetIndependentEvents($days_to_index)
624 {
625 global $sourcedir;
626
627 $low_date = strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
628 $high_date = strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);
629
630 return array(
631 'data' => array(
632 'holidays' => getHolidayRange($low_date, $high_date),
633 'birthdays' => getBirthdayRange($low_date, $high_date),
634 'events' => getEventRange($low_date, $high_date, false),
635 ),
636 'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
637 'expires' => time() + 3600,
638 );
639 }
640
641 // Called from the BoardIndex to display the current day's events on the board index.
642 function cache_getRecentEvents($eventOptions)
643 {
644 global $modSettings, $user_info, $scripturl;
645
646 // With the 'static' cached data we can calculate the user-specific data.
647 $cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions['num_days_shown']));
648
649 // Get the information about today (from user perspective).
650 $today = getTodayInfo();
651
652 $return_data = array(
653 'calendar_holidays' => array(),
654 'calendar_birthdays' => array(),
655 'calendar_events' => array(),
656 );
657
658 // Set the event span to be shown in seconds.
659 $days_for_index = $eventOptions['num_days_shown'] * 86400;
660
661 // Get the current member time/date.
662 $now = forum_time();
663
664 // Holidays between now and now + days.
665 for ($i = $now; $i < $now + $days_for_index; $i += 86400)
666 {
667 if (isset($cached_data['holidays'][strftime('%Y-%m-%d', $i)]))
668 $return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][strftime('%Y-%m-%d', $i)]);
669 }
670
671 // Happy Birthday, guys and gals!
672 for ($i = $now; $i < $now + $days_for_index; $i += 86400)
673 {
674 $loop_date = strftime('%Y-%m-%d', $i);
675 if (isset($cached_data['birthdays'][$loop_date]))
676 {
677 foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
678 $cached_data['birthdays'][strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
679 $return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
680 }
681 }
682
683 $duplicates = array();
684 for ($i = $now; $i < $now + $days_for_index; $i += 86400)
685 {
686 // Determine the date of the current loop step.
687 $loop_date = strftime('%Y-%m-%d', $i);
688
689 // No events today? Check the next day.
690 if (empty($cached_data['events'][$loop_date]))
691 continue;
692
693 // Loop through all events to add a few last-minute values.
694 foreach ($cached_data['events'][$loop_date] as $ev => $event)
695 {
696 // Create a shortcut variable for easier access.
697 $this_event = &$cached_data['events'][$loop_date][$ev];
698
699 // Skip duplicates.
700 if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
701 {
702 unset($cached_data['events'][$loop_date][$ev]);
703 continue;
704 }
705 else
706 $duplicates[$this_event['topic'] . $this_event['title']] = true;
707
708 // Might be set to true afterwards, depending on the permissions.
709 $this_event['can_edit'] = false;
710 $this_event['is_today'] = $loop_date === $today['date'];
711 $this_event['date'] = $loop_date;
712 }
713
714 if (!empty($cached_data['events'][$loop_date]))
715 $return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
716 }
717
718 // Mark the last item so that a list separator can be used in the template.
719 for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
720 $return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
721 for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
722 $return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
723
724 return array(
725 'data' => $return_data,
726 'expires' => time() + 3600,
727 'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
728 'post_retri_eval' => '
729 global $context, $scripturl, $user_info;
730
731 foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
732 {
733 // Remove events that the user may not see or wants to ignore.
734 if ((count(array_intersect($user_info[\'groups\'], $event[\'allowed_groups\'])) === 0 && !allowedTo(\'admin_forum\') && !empty($event[\'id_board\'])) || in_array($event[\'id_board\'], $user_info[\'ignoreboards\']))
735 unset($cache_block[\'data\'][\'calendar_events\'][$k]);
736 else
737 {
738 // Whether the event can be edited depends on the permissions.
739 $cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));
740
741 // The added session code makes this URL not cachable.
742 $cache_block[\'data\'][\'calendar_events\'][$k][\'modify_href\'] = $scripturl . \'?action=\' . ($event[\'topic\'] == 0 ? \'calendar;sa=post;\' : \'post;msg=\' . $event[\'msg\'] . \';topic=\' . $event[\'topic\'] . \'.0;calendar;\') . \'eventid=\' . $event[\'id\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'];
743 }
744 }
745
746 if (empty($params[0][\'include_holidays\']))
747 $cache_block[\'data\'][\'calendar_holidays\'] = array();
748 if (empty($params[0][\'include_birthdays\']))
749 $cache_block[\'data\'][\'calendar_birthdays\'] = array();
750 if (empty($params[0][\'include_events\']))
751 $cache_block[\'data\'][\'calendar_events\'] = array();
752
753 $cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
754 );
755 }
756
757 // Makes sure the calendar post is valid.
758 function validateEventPost()
759 {
760 global $modSettings, $txt, $sourcedir, $smcFunc;
761
762 if (!isset($_POST['deleteevent']))
763 {
764 // No month? No year?
765 if (!isset($_POST['month']))
766 fatal_lang_error('event_month_missing', false);
767 if (!isset($_POST['year']))
768 fatal_lang_error('event_year_missing', false);
769
770 // Check the month and year...
771 if ($_POST['month'] < 1 || $_POST['month'] > 12)
772 fatal_lang_error('invalid_month', false);
773 if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
774 fatal_lang_error('invalid_year', false);
775 }
776
777 // Make sure they're allowed to post...
778 isAllowedTo('calendar_post');
779
780 if (isset($_POST['span']))
781 {
782 // Make sure it's turned on and not some fool trying to trick it.
783 if (empty($modSettings['cal_allowspan']))
784 fatal_lang_error('no_span', false);
785 if ($_POST['span'] < 1 || $_POST['span'] > $modSettings['cal_maxspan'])
786 fatal_lang_error('invalid_days_numb', false);
787 }
788
789 // There is no need to validate the following values if we are just deleting the event.
790 if (!isset($_POST['deleteevent']))
791 {
792 // No day?
793 if (!isset($_POST['day']))
794 fatal_lang_error('event_day_missing', false);
795 if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
796 fatal_lang_error('event_title_missing', false);
797 elseif (!isset($_POST['evtitle']))
798 $_POST['evtitle'] = $_POST['subject'];
799
800 // Bad day?
801 if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
802 fatal_lang_error('invalid_date', false);
803
804 // No title?
805 if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
806 fatal_lang_error('no_event_title', false);
807 if ($smcFunc['strlen']($_POST['evtitle']) > 30)
808 $_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 30);
809 $_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
810 }
811 }
812
813 // Get the event's poster.
814 function getEventPoster($event_id)
815 {
816 global $smcFunc;
817
818 // A simple database query, how hard can that be?
819 $request = $smcFunc['db_query']('', '
820 SELECT id_member
821 FROM {db_prefix}calendar
822 WHERE id_event = {int:id_event}
823 LIMIT 1',
824 array(
825 'id_event' => $event_id,
826 )
827 );
828
829 // No results, return false.
830 if ($smcFunc['db_num_rows'] === 0)
831 return false;
832
833 // Grab the results and return.
834 list ($poster) = $smcFunc['db_fetch_row']($request);
835 $smcFunc['db_free_result']($request);
836 return $poster;
837 }
838
839 // Consolidating the various INSERT statements into this function.
840 function insertEvent(&$eventOptions)
841 {
842 global $modSettings, $smcFunc;
843
844 // Add special chars to the title.
845 $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
846
847 // Add some sanity checking to the span.
848 $eventOptions['span'] = isset($eventOptions['span']) && $eventOptions['span'] > 0 ? (int) $eventOptions['span'] : 0;
849
850 // Make sure the start date is in ISO order.
851 if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
852 trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);
853
854 // Set the end date (if not yet given)
855 if (!isset($eventOptions['end_date']))
856 $eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
857
858 // If no topic and board are given, they are not linked to a topic.
859 $eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
860 $eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;
861
862 // Insert the event!
863 $smcFunc['db_insert']('',
864 '{db_prefix}calendar',
865 array(
866 'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
867 'start_date' => 'date', 'end_date' => 'date',
868 ),
869 array(
870 $eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
871 $eventOptions['start_date'], $eventOptions['end_date'],
872 ),
873 array('id_event')
874 );
875
876 // Store the just inserted id_event for future reference.
877 $eventOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}calendar', 'id_event');
878
879 // Update the settings to show something calendarish was updated.
880 updateSettings(array(
881 'calendar_updated' => time(),
882 ));
883 }
884
885 function modifyEvent($event_id, &$eventOptions)
886 {
887 global $smcFunc;
888
889 // Properly sanitize the title.
890 $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
891
892 // Scan the start date for validity and get its components.
893 if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
894 trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);
895
896 // Default span to 0 days.
897 $eventOptions['span'] = isset($eventOptions['span']) ? (int) $eventOptions['span'] : 0;
898
899 // Set the end date to the start date + span (if the end date wasn't already given).
900 if (!isset($eventOptions['end_date']))
901 $eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
902
903 $smcFunc['db_query']('', '
904 UPDATE {db_prefix}calendar
905 SET
906 start_date = {date:start_date},
907 end_date = {date:end_date},
908 title = SUBSTRING({string:title}, 1, 60),
909 id_board = {int:id_board},
910 id_topic = {int:id_topic}
911 WHERE id_event = {int:id_event}',
912 array(
913 'start_date' => $eventOptions['start_date'],
914 'end_date' => $eventOptions['end_date'],
915 'title' => $eventOptions['title'],
916 'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
917 'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
918 'id_event' => $event_id,
919 )
920 );
921
922 updateSettings(array(
923 'calendar_updated' => time(),
924 ));
925 }
926
927 function removeEvent($event_id)
928 {
929 global $smcFunc;
930
931 $smcFunc['db_query']('', '
932 DELETE FROM {db_prefix}calendar
933 WHERE id_event = {int:id_event}',
934 array(
935 'id_event' => $event_id,
936 )
937 );
938
939 updateSettings(array(
940 'calendar_updated' => time(),
941 ));
942 }
943
944 function getEventProperties($event_id)
945 {
946 global $smcFunc;
947
948 $request = $smcFunc['db_query']('', '
949 SELECT
950 c.id_event, c.id_board, c.id_topic, MONTH(c.start_date) AS month,
951 DAYOFMONTH(c.start_date) AS day, YEAR(c.start_date) AS year,
952 (TO_DAYS(c.end_date) - TO_DAYS(c.start_date)) AS span, c.id_member, c.title,
953 t.id_first_msg, t.id_member_started
954 FROM {db_prefix}calendar AS c
955 LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
956 WHERE c.id_event = {int:id_event}',
957 array(
958 'id_event' => $event_id,
959 )
960 );
961
962 // If nothing returned, we are in poo, poo.
963 if ($smcFunc['db_num_rows']($request) === 0)
964 return false;
965
966 $row = $smcFunc['db_fetch_assoc']($request);
967 $smcFunc['db_free_result']($request);
968
969 $return_value = array(
970 'boards' => array(),
971 'board' => $row['id_board'],
972 'new' => 0,
973 'eventid' => $event_id,
974 'year' => $row['year'],
975 'month' => $row['month'],
976 'day' => $row['day'],
977 'title' => $row['title'],
978 'span' => 1 + $row['span'],
979 'member' => $row['id_member'],
980 'topic' => array(
981 'id' => $row['id_topic'],
982 'member_started' => $row['id_member_started'],
983 'first_msg' => $row['id_first_msg'],
984 ),
985 );
986
987 $return_value['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $return_value['month'] == 12 ? 1 : $return_value['month'] + 1, 0, $return_value['month'] == 12 ? $return_value['year'] + 1 : $return_value['year']));
988
989 return $return_value;
990 }
991
992 function list_getHolidays($start, $items_per_page, $sort)
993 {
994 global $smcFunc;
995
996 $request = $smcFunc['db_query']('', '
997 SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
998 FROM {db_prefix}calendar_holidays
999 ORDER BY {raw:sort}
1000 LIMIT ' . $start . ', ' . $items_per_page,
1001 array(
1002 'sort' => $sort,
1003 )
1004 );
1005 $holidays = array();
1006 while ($row = $smcFunc['db_fetch_assoc']($request))
1007 $holidays[] = $row;
1008 $smcFunc['db_free_result']($request);
1009
1010 return $holidays;
1011 }
1012
1013 function list_getNumHolidays()
1014 {
1015 global $smcFunc;
1016
1017 $request = $smcFunc['db_query']('', '
1018 SELECT COUNT(*)
1019 FROM {db_prefix}calendar_holidays',
1020 array(
1021 )
1022 );
1023 list($num_items) = $smcFunc['db_fetch_row']($request);
1024 $smcFunc['db_free_result']($request);
1025
1026 return $num_items;
1027 }
1028
1029 function removeHolidays($holiday_ids)
1030 {
1031 global $smcFunc;
1032
1033 $smcFunc['db_query']('', '
1034 DELETE FROM {db_prefix}calendar_holidays
1035 WHERE id_holiday IN ({array_int:id_holiday})',
1036 array(
1037 'id_holiday' => $holiday_ids,
1038 )
1039 );
1040
1041 updateSettings(array(
1042 'calendar_updated' => time(),
1043 ));
1044 }
1045
1046 ?>