Issues (1065)

Sources/Subs-Calendar.php (1 issue)

1
<?php
2
3
/**
4
 * This file contains several functions for retrieving and manipulating calendar events, birthdays and holidays.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2025 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.5
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Get all birthdays within the given time range.
21
 * finds all the birthdays in the specified range of days.
22
 * works with birthdays set for no year, or any other year, and respects month and year boundaries.
23
 *
24
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
25
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
26
 * @return array An array of days, each of which is an array of birthday information for the context
27
 */
28
function getBirthdayRange($low_date, $high_date)
29
{
30
	global $smcFunc;
31
32
	// We need to search for any birthday in this range, and whatever year that birthday is on.
33
	$year_low = (int) substr($low_date, 0, 4);
34
	$year_high = (int) substr($high_date, 0, 4);
35
36
	if ($smcFunc['db_title'] !== POSTGRE_TITLE)
37
	{
38
		// Collect all of the birthdays for this month.  I know, it's a painful query.
39
		$result = $smcFunc['db_query']('', '
40
			SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
41
			FROM {db_prefix}members
42
			WHERE birthdate != {date:no_birthdate}
43
				AND (
44
					DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
45
					OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
46
				)
47
				AND is_activated = {int:is_activated}',
48
			array(
49
				'is_activated' => 1,
50
				'no_birthdate' => '1004-01-01',
51
				'year_low' => $year_low . '-%m-%d',
52
				'year_high' => $year_high . '-%m-%d',
53
				'low_date' => $low_date,
54
				'high_date' => $high_date,
55
			)
56
		);
57
	}
58
	else
59
	{
60
		$result = $smcFunc['db_query']('', '
61
			SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
62
			FROM {db_prefix}members
63
			WHERE birthdate != {date:no_birthdate}
64
				AND (
65
					indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_low_low_date}) AND indexable_month_day({date:year_low_high_date})' . ($year_low == $year_high ? '' : '
66
					OR indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_high_low_date}) AND indexable_month_day({date:year_high_high_date})') . '
67
				)
68
				AND is_activated = {int:is_activated}',
69
			array(
70
				'is_activated' => 1,
71
				'no_birthdate' => '1004-01-01',
72
				'year_low_low_date' => $low_date,
73
				'year_low_high_date' => $year_low == $year_high ? $high_date : $year_low . '-12-31',
74
				'year_high_low_date' => $year_low == $year_high ? $low_date : $year_high . '-01-01',
75
				'year_high_high_date' => $high_date,
76
			)
77
		);
78
	}
79
	$bday = array();
80
	while ($row = $smcFunc['db_fetch_assoc']($result))
81
	{
82
		if ($year_low != $year_high)
83
			$age_year = substr($row['birthdate'], 5) <= substr($high_date, 5) ? $year_high : $year_low;
84
		else
85
			$age_year = $year_low;
86
87
		$bday[$age_year . substr($row['birthdate'], 4)][] = array(
88
			'id' => $row['id_member'],
89
			'name' => $row['real_name'],
90
			'age' => $row['birth_year'] > 1004 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
91
			'is_last' => false
92
		);
93
	}
94
	$smcFunc['db_free_result']($result);
95
96
	ksort($bday);
97
98
	// Set is_last, so the themes know when to stop placing separators.
99
	foreach ($bday as $mday => $array)
100
		$bday[$mday][count($array) - 1]['is_last'] = true;
101
102
	return $bday;
103
}
104
105
/**
106
 * Get all calendar events within the given time range.
107
 *
108
 * - finds all the posted calendar events within a date range.
109
 * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
110
 * - censors the posted event titles.
111
 * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
112
 *
113
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
114
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
115
 * @param bool $use_permissions Whether to use permissions
116
 * @return array Contextual information if use_permissions is true, and an array of the data needed to build that otherwise
117
 */
118
function getEventRange($low_date, $high_date, $use_permissions = true)
119
{
120
	global $scripturl, $modSettings, $user_info, $smcFunc, $context, $sourcedir;
121
	static $timezone_array = array();
122
	require_once($sourcedir . '/Subs.php');
123
124
	if (empty($timezone_array['default']))
125
		$timezone_array['default'] = timezone_open(getUserTimezone());
126
127
	$low_object = date_create($low_date, $timezone_array['default']);
128
	$high_object = date_create($high_date, $timezone_array['default']);
129
130
	// Find all the calendar info...
131
	$result = $smcFunc['db_query']('calendar_get_events', '
132
		SELECT
133
			cal.id_event, cal.title, cal.id_member, cal.id_topic, cal.id_board,
134
			cal.start_date, cal.end_date, cal.start_time, cal.end_time, cal.timezone, cal.location,
135
			b.member_groups, t.id_first_msg, t.approved, b.id_board
136
		FROM {db_prefix}calendar AS cal
137
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
138
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
139
		WHERE cal.start_date <= {date:high_date}
140
			AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
141
			AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
142
		array(
143
			'high_date' => $high_date,
144
			'low_date' => $low_date,
145
			'no_board_link' => 0,
146
		)
147
	);
148
	$events = array();
149
	while ($row = $smcFunc['db_fetch_assoc']($result))
150
	{
151
		// If the attached topic is not approved then for the moment pretend it doesn't exist
152
		if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
153
			continue;
154
155
		// Force a censor of the title - as often these are used by others.
156
		censorText($row['title'], $use_permissions ? false : true);
157
158
		// Get the various time and date properties for this event
159
		list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
160
161
		if (empty($timezone_array[$tz]))
162
			$timezone_array[$tz] = timezone_open($tz);
163
164
		// Sanity check
165
		if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
166
			continue;
167
168
		// Get set up for the loop
169
		$start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$tz]);
170
		$end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$tz]);
171
		date_timezone_set($start_object, $timezone_array['default']);
172
		date_timezone_set($end_object, $timezone_array['default']);
173
		date_time_set($start_object, 0, 0, 0);
174
		date_time_set($end_object, 0, 0, 0);
175
		$start_date_string = date_format($start_object, 'Y-m-d');
176
		$end_date_string = date_format($end_object, 'Y-m-d');
177
178
		$cal_date = ($start_object >= $low_object) ? (clone $start_object) : (clone $low_object);
179
		while ($cal_date <= $end_object && $cal_date <= $high_object)
180
		{
181
			$starts_today = (date_format($cal_date, 'Y-m-d') == $start_date_string);
182
			$ends_today = (date_format($cal_date, 'Y-m-d') == $end_date_string);
183
184
			$eventProperties = array(
185
				'id' => $row['id_event'],
186
				'title' => $row['title'],
187
				'year' => $start['year'],
188
				'month' => $start['month'],
189
				'day' => $start['day'],
190
				'hour' => !$allday ? $start['hour'] : null,
191
				'minute' => !$allday ? $start['minute'] : null,
192
				'second' => !$allday ? $start['second'] : null,
193
				'start_date' => $row['start_date'],
194
				'start_date_local' => $start['date_local'],
195
				'start_date_orig' => $start['date_orig'],
196
				'start_time' => !$allday ? $row['start_time'] : null,
197
				'start_time_local' => !$allday ? $start['time_local'] : null,
198
				'start_time_orig' => !$allday ? $start['time_orig'] : null,
199
				'start_timestamp' => $start['timestamp'],
200
				'start_datetime' => $start['datetime'],
201
				'start_iso_gmdate' => $start['iso_gmdate'],
202
				'end_year' => $end['year'],
203
				'end_month' => $end['month'],
204
				'end_day' => $end['day'],
205
				'end_hour' => !$allday ? $end['hour'] : null,
206
				'end_minute' => !$allday ? $end['minute'] : null,
207
				'end_second' => !$allday ? $end['second'] : null,
208
				'end_date' => $row['end_date'],
209
				'end_date_local' => $end['date_local'],
210
				'end_date_orig' => $end['date_orig'],
211
				'end_time' => !$allday ? $row['end_time'] : null,
212
				'end_time_local' => !$allday ? $end['time_local'] : null,
213
				'end_time_orig' => !$allday ? $end['time_orig'] : null,
214
				'end_timestamp' => $end['timestamp'],
215
				'end_datetime' => $end['datetime'],
216
				'end_iso_gmdate' => $end['iso_gmdate'],
217
				'allday' => $allday,
218
				'tz' => !$allday ? $tz : null,
219
				'tz_abbrev' => !$allday ? $tz_abbrev : null,
220
				'span' => $span,
221
				'is_last' => false,
222
				'id_board' => $row['id_board'],
223
				'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
224
				'starts_today' => $starts_today,
225
				'ends_today' => $ends_today,
226
				'location' => $row['location'],
227
			);
228
229
			// If we're using permissions (calendar pages?) then just ouput normal contextual style information.
230
			if ($use_permissions)
231
				$events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
232
					'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
233
					'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
234
					'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
235
					'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'],
236
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
237
					'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
238
				));
239
			// Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
240
			else
241
				$events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
242
					'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
243
					'link' => $row['id_topic'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
244
					'can_edit' => false,
245
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
246
					'topic' => $row['id_topic'],
247
					'msg' => $row['id_first_msg'],
248
					'poster' => $row['id_member'],
249
					'allowed_groups' => isset($row['member_groups']) ? explode(',', $row['member_groups']) : array(),
250
				));
251
252
			date_add($cal_date, date_interval_create_from_date_string('1 day'));
253
		}
254
	}
255
	$smcFunc['db_free_result']($result);
256
257
	// If we're doing normal contextual data, go through and make things clear to the templates ;).
258
	if ($use_permissions)
259
	{
260
		foreach ($events as $mday => $array)
261
			$events[$mday][count($array) - 1]['is_last'] = true;
262
	}
263
264
	ksort($events);
265
266
	return $events;
267
}
268
269
/**
270
 * Get all holidays within the given time range.
271
 *
272
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
273
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
274
 * @return array An array of days, which are all arrays of holiday names.
275
 */
276
function getHolidayRange($low_date, $high_date)
277
{
278
	global $smcFunc;
279
280
	// Get the lowest and highest dates for "all years".
281
	if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
282
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
283
			OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
284
	else
285
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
286
287
	// Find some holidays... ;).
288
	$result = $smcFunc['db_query']('', '
289
		SELECT event_date, YEAR(event_date) AS year, title
290
		FROM {db_prefix}calendar_holidays
291
		WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
292
			OR ' . $allyear_part,
293
		array(
294
			'low_date' => $low_date,
295
			'high_date' => $high_date,
296
			'all_year_low' => '1004' . substr($low_date, 4),
297
			'all_year_high' => '1004' . substr($high_date, 4),
298
			'all_year_jan' => '1004-01-01',
299
			'all_year_dec' => '1004-12-31',
300
		)
301
	);
302
	$holidays = array();
303
	while ($row = $smcFunc['db_fetch_assoc']($result))
304
	{
305
		if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
306
			$event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
307
		else
308
			$event_year = substr($low_date, 0, 4);
309
310
		$holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
311
	}
312
	$smcFunc['db_free_result']($result);
313
314
	ksort($holidays);
315
316
	return $holidays;
317
}
318
319
/**
320
 * Does permission checks to see if an event can be linked to a board/topic.
321
 * checks if the current user can link the current topic to the calendar, permissions et al.
322
 * this requires the calendar_post permission, a forum moderator, or a topic starter.
323
 * expects the $topic and $board variables to be set.
324
 * if the user doesn't have proper permissions, an error will be shown.
325
 */
326
function canLinkEvent()
327
{
328
	global $user_info, $topic, $board, $smcFunc;
329
330
	// If you can't post, you can't link.
331
	isAllowedTo('calendar_post');
332
333
	// No board?  No topic?!?
334
	if (empty($board))
335
		fatal_lang_error('missing_board_id', false);
336
	if (empty($topic))
337
		fatal_lang_error('missing_topic_id', false);
338
339
	// Administrator, Moderator, or owner.  Period.
340
	if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
341
	{
342
		// Not admin or a moderator of this board. You better be the owner - or else.
343
		$result = $smcFunc['db_query']('', '
344
			SELECT id_member_started
345
			FROM {db_prefix}topics
346
			WHERE id_topic = {int:current_topic}
347
			LIMIT 1',
348
			array(
349
				'current_topic' => $topic,
350
			)
351
		);
352
		if ($row = $smcFunc['db_fetch_assoc']($result))
353
		{
354
			// Not the owner of the topic.
355
			if ($row['id_member_started'] != $user_info['id'])
356
				fatal_lang_error('not_your_topic', 'user');
357
		}
358
		// Topic/Board doesn't exist.....
359
		else
360
			fatal_lang_error('calendar_no_topic', 'general');
361
		$smcFunc['db_free_result']($result);
362
	}
363
}
364
365
/**
366
 * Returns date information about 'today' relative to the users time offset.
367
 * returns an array with the current date, day, month, and year.
368
 * takes the users time offset into account.
369
 *
370
 * @return array An array of info about today, based on forum time. Has 'day', 'month', 'year' and 'date' (in YYYY-MM-DD format)
371
 */
372
function getTodayInfo()
373
{
374
	return array(
375
		'day' => (int) smf_strftime('%d', time(), getUserTimezone()),
376
		'month' => (int) smf_strftime('%m', time(), getUserTimezone()),
377
		'year' => (int) smf_strftime('%Y', time(), getUserTimezone()),
378
		'date' => smf_strftime('%Y-%m-%d', time(), getUserTimezone()),
379
	);
380
}
381
382
/**
383
 * Provides information (link, month, year) about the previous and next month.
384
 *
385
 * @param string $selected_date A date in YYYY-MM-DD format
386
 * @param array $calendarOptions An array of calendar options
387
 * @param bool $is_previous Whether this is the previous month
388
 * @param bool $has_picker Wheter to add javascript to handle a date picker
389
 * @return array A large array containing all the information needed to show a calendar grid for the given month
390
 */
391
function getCalendarGrid($selected_date, $calendarOptions, $is_previous = false, $has_picker = true)
392
{
393
	global $scripturl, $modSettings;
394
395
	$selected_object = date_create($selected_date . ' ' . getUserTimezone());
396
397
	$next_object = date_create($selected_date . ' ' . getUserTimezone());
398
	$next_object->modify('first day of next month');
399
400
	$prev_object = date_create($selected_date . ' ' . getUserTimezone());
401
	$prev_object->modify('first day of previous month');
402
403
	// Eventually this is what we'll be returning.
404
	$calendarGrid = array(
405
		'week_days' => array(),
406
		'weeks' => array(),
407
		'short_day_titles' => !empty($calendarOptions['short_day_titles']),
408
		'short_month_titles' => !empty($calendarOptions['short_month_titles']),
409
		'current_month' => date_format($selected_object, 'n'),
410
		'current_year' => date_format($selected_object, 'Y'),
411
		'current_day' => date_format($selected_object, 'd'),
412
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
413
		'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
414
		'previous_calendar' => array(
415
			'year' => date_format($prev_object, 'Y'),
416
			'month' => date_format($prev_object, 'n'),
417
			'day' => date_format($prev_object, 'd'),
418
			'start_date' => date_format($prev_object, 'Y-m-d'),
419
			'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
420
		),
421
		'next_calendar' => array(
422
			'year' => date_format($next_object, 'Y'),
423
			'month' => date_format($next_object, 'n'),
424
			'day' => date_format($next_object, 'd'),
425
			'start_date' => date_format($next_object, 'Y-m-d'),
426
			'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
427
		),
428
		'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
429
	);
430
431
	// Get today's date.
432
	$today = getTodayInfo();
433
434
	$first_day_object = date_create(date_format($selected_object, 'Y-m-01') . ' ' . getUserTimezone());
435
	$last_day_object = date_create(date_format($selected_object, 'Y-m-t') . ' ' . getUserTimezone());
436
437
	// Get information about this month.
438
	$month_info = array(
439
		'first_day' => array(
440
			'day_of_week' => date_format($first_day_object, 'w'),
441
			'week_num' => date_format($first_day_object, 'W'),
442
			'date' => date_format($first_day_object, 'Y-m-d'),
443
		),
444
		'last_day' => array(
445
			'day_of_month' => date_format($last_day_object, 't'),
446
			'date' => date_format($last_day_object, 'Y-m-d'),
447
		),
448
		'first_day_of_year' => date_format(date_create(date_format($selected_object, 'Y-01-01') . ' ' . getUserTimezone()), 'w'),
449
		'first_day_of_next_year' => date_format(date_create((date_format($selected_object, 'Y') + 1) . '-01-01' . ' ' . getUserTimezone()), 'w'),
450
	);
451
452
	// The number of days the first row is shifted to the right for the starting day.
453
	$nShift = $month_info['first_day']['day_of_week'];
454
455
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
456
457
	// Starting any day other than Sunday means a shift...
458
	if (!empty($calendarOptions['start_day']))
459
	{
460
		$nShift -= $calendarOptions['start_day'];
461
		if ($nShift < 0)
462
			$nShift = 7 + $nShift;
463
	}
464
465
	// Number of rows required to fit the month.
466
	$nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
467
	if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
468
		$nRows++;
469
470
	// Fetch the arrays for birthdays, posted events, and holidays.
471
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
472
	$events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
473
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
474
475
	// Days of the week taking into consideration that they may want it to start on any day.
476
	$count = $calendarOptions['start_day'];
477
	for ($i = 0; $i < 7; $i++)
478
	{
479
		$calendarGrid['week_days'][] = $count;
480
		$count++;
481
		if ($count == 7)
482
			$count = 0;
483
	}
484
485
	// Iterate through each week.
486
	$calendarGrid['weeks'] = array();
487
	for ($nRow = 0; $nRow < $nRows; $nRow++)
488
	{
489
		// Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
490
		$calendarGrid['weeks'][$nRow] = array(
491
			'days' => array(),
492
		);
493
494
		// And figure out all the days.
495
		for ($nCol = 0; $nCol < 7; $nCol++)
496
		{
497
			$nDay = ($nRow * 7) + $nCol - $nShift + 1;
498
499
			if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
500
				$nDay = 0;
501
502
			$date = date_format($selected_object, 'Y-m-') . sprintf('%02d', $nDay);
503
504
			$calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
505
				'day' => $nDay,
506
				'date' => $date,
507
				'is_today' => $date == $today['date'],
508
				'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
509
				'is_first_of_month' => $nDay === 1,
510
				'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
511
				'events' => !empty($events[$date]) ? $events[$date] : array(),
512
				'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
513
			);
514
		}
515
	}
516
517
	// What is the last day of the month?
518
	if ($is_previous === true)
519
		$calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];
520
521
	// We'll use the shift in the template.
522
	$calendarGrid['shift'] = $nShift;
523
524
	// Set the previous and the next month's links.
525
	$calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
526
	$calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
527
528
	if ($has_picker)
529
	{
530
		loadDatePicker('#calendar_navigation .date_input');
531
		loadDatePair('#calendar_navigation', 'date_input');
532
	}
533
534
	return $calendarGrid;
535
}
536
537
/**
538
 * Returns the information needed to show a calendar for the given week.
539
 *
540
 * @param string $selected_date A date in YYYY-MM-DD format
541
 * @param array $calendarOptions An array of calendar options
542
 * @return array An array of information needed to display the grid for a single week on the calendar
543
 */
544
function getCalendarWeek($selected_date, $calendarOptions)
545
{
546
	global $scripturl, $modSettings, $txt;
547
548
	$selected_object = date_create($selected_date . ' ' . getUserTimezone());
549
550
	// Get today's date.
551
	$today = getTodayInfo();
552
553
	// What is the actual "start date" for the passed day.
554
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
555
	$day_of_week = date_format($selected_object, 'w');
556
	$first_day_object = date_create($selected_date . ' ' . getUserTimezone());
557
	if ($day_of_week != $calendarOptions['start_day'])
558
	{
559
		// Here we offset accordingly to get things to the real start of a week.
560
		$date_diff = $day_of_week - $calendarOptions['start_day'];
561
		if ($date_diff < 0)
562
			$date_diff += 7;
563
564
		date_sub($first_day_object, date_interval_create_from_date_string($date_diff . ' days'));
565
	}
566
567
	$last_day_object = date_create(date_format($first_day_object, 'Y-m-d') . ' ' . getUserTimezone());
568
	date_add($last_day_object, date_interval_create_from_date_string('1 week'));
569
570
	$month = date_format($first_day_object, 'n');
571
	$year = date_format($first_day_object, 'Y');
572
	$day = date_format($first_day_object, 'd');
573
574
	$next_object = date_create($selected_date . ' ' . getUserTimezone());
575
	date_add($next_object, date_interval_create_from_date_string('1 week'));
576
577
	$prev_object = date_create($selected_date . ' ' . getUserTimezone());
578
	date_sub($prev_object, date_interval_create_from_date_string('1 week'));
579
580
	// Now start filling in the calendar grid.
581
	$calendarGrid = array(
582
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
583
		'previous_week' => array(
584
			'year' => date_format($prev_object, 'Y'),
585
			'month' => date_format($prev_object, 'n'),
586
			'day' => date_format($prev_object, 'd'),
587
			'start_date' => date_format($prev_object, 'Y-m-d'),
588
			'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
589
		),
590
		'next_week' => array(
591
			'year' => date_format($next_object, 'Y'),
592
			'month' => date_format($next_object, 'n'),
593
			'day' => date_format($next_object, 'd'),
594
			'start_date' => date_format($next_object, 'Y-m-d'),
595
			'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
596
		),
597
		'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
598
		'show_events' => $calendarOptions['show_events'],
599
		'show_holidays' => $calendarOptions['show_holidays'],
600
		'show_birthdays' => $calendarOptions['show_birthdays'],
601
	);
602
603
	// Fetch the arrays for birthdays, posted events, and holidays.
604
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
605
	$events = $calendarOptions['show_events'] ? getEventRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
606
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
607
608
	$calendarGrid['week_title'] = sprintf($txt['calendar_week_beginning'], $txt['months'][date_format($first_day_object, 'n')], date_format($first_day_object, 'j'), date_format($first_day_object, 'Y'));
609
610
	// This holds all the main data - there is at least one month!
611
	$calendarGrid['months'] = array();
612
	$current_day_object = date_create(date_format($first_day_object, 'Y-m-d') . ' ' . getUserTimezone());
613
	for ($i = 0; $i < 7; $i++)
614
	{
615
		$current_month = date_format($current_day_object, 'n');
616
		$current_day = date_format($current_day_object, 'j');
617
		$current_date = date_format($current_day_object, 'Y-m-d');
618
619
		if (!isset($calendarGrid['months'][$current_month]))
620
			$calendarGrid['months'][$current_month] = array(
621
				'current_month' => $current_month,
622
				'current_year' => date_format($current_day_object, 'Y'),
623
				'days' => array(),
624
			);
625
626
		$calendarGrid['months'][$current_month]['days'][$current_day] = array(
627
			'day' => $current_day,
628
			'day_of_week' => (date_format($current_day_object, 'w') + 7) % 7,
629
			'date' => $current_date,
630
			'is_today' => $current_date == $today['date'],
631
			'holidays' => !empty($holidays[$current_date]) ? $holidays[$current_date] : array(),
632
			'events' => !empty($events[$current_date]) ? $events[$current_date] : array(),
633
			'birthdays' => !empty($bday[$current_date]) ? $bday[$current_date] : array()
634
		);
635
636
		date_add($current_day_object, date_interval_create_from_date_string('1 day'));
637
	}
638
639
	// Set the previous and the next week's links.
640
	$calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
641
	$calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];
642
643
	loadDatePicker('#calendar_navigation .date_input');
644
	loadDatePair('#calendar_navigation', 'date_input', '');
645
646
	return $calendarGrid;
647
}
648
649
/**
650
 * Returns the information needed to show a list of upcoming events, birthdays, and holidays on the calendar.
651
 *
652
 * @param string $start_date The start of a date range in YYYY-MM-DD format
653
 * @param string $end_date The end of a date range in YYYY-MM-DD format
654
 * @param array $calendarOptions An array of calendar options
655
 * @return array An array of information needed to display a list of upcoming events, etc., on the calendar
656
 */
657
function getCalendarList($start_date, $end_date, $calendarOptions)
658
{
659
	global $modSettings, $user_info, $txt, $context, $sourcedir;
660
	require_once($sourcedir . '/Subs.php');
661
662
	// DateTime objects make life easier
663
	$start_object = date_create($start_date . ' ' . getUserTimezone());
664
	$end_object = date_create($end_date . ' ' . getUserTimezone());
665
666
	$calendarGrid = array(
667
		'start_date' => timeformat(date_format($start_object, 'U'), get_date_or_time_format('date')),
668
		'start_year' => date_format($start_object, 'Y'),
669
		'start_month' => date_format($start_object, 'm'),
670
		'start_day' => date_format($start_object, 'd'),
671
		'end_date' => timeformat(date_format($end_object, 'U'), get_date_or_time_format('date')),
672
		'end_year' => date_format($end_object, 'Y'),
673
		'end_month' => date_format($end_object, 'm'),
674
		'end_day' => date_format($end_object, 'd'),
675
	);
676
677
	$calendarGrid['birthdays'] = $calendarOptions['show_birthdays'] ? getBirthdayRange($start_date, $end_date) : array();
678
	$calendarGrid['holidays'] = $calendarOptions['show_holidays'] ? getHolidayRange($start_date, $end_date) : array();
679
	$calendarGrid['events'] = $calendarOptions['show_events'] ? getEventRange($start_date, $end_date) : array();
680
681
	// Get rid of duplicate events
682
	$temp = array();
683
	foreach ($calendarGrid['events'] as $date => $date_events)
684
	{
685
		foreach ($date_events as $event_key => $event_val)
686
		{
687
			if (in_array($event_val['id'], $temp))
688
				unset($calendarGrid['events'][$date][$event_key]);
689
			else
690
				$temp[] = $event_val['id'];
691
		}
692
	}
693
694
	// Give birthdays and holidays a friendly format, without the year
695
	$date_format = str_replace(array('%Y', '%y', '%G', '%g', '%C', '%c', '%D'), array('', '', '', '', '', '%b %d', '%m/%d'), get_date_or_time_format('date'));
696
697
	foreach (array('birthdays', 'holidays') as $type)
698
	{
699
		foreach ($calendarGrid[$type] as $date => $date_content)
700
		{
701
			// Make sure to apply no offsets
702
			$date_local = preg_replace('~(?<=\s)0+(\d)~', '$1', trim(timeformat(strtotime($date), $date_format, true), " \t\n\r\0\x0B,./;:<>()[]{}\\|-_=+"));
0 ignored issues
show
true of type true is incompatible with the type null|string expected by parameter $tzid of timeformat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

702
			$date_local = preg_replace('~(?<=\s)0+(\d)~', '$1', trim(timeformat(strtotime($date), $date_format, /** @scrutinizer ignore-type */ true), " \t\n\r\0\x0B,./;:<>()[]{}\\|-_=+"));
Loading history...
703
704
			$calendarGrid[$type][$date]['date_local'] = $date_local;
705
		}
706
	}
707
708
	loadDatePicker('#calendar_range .date_input');
709
	loadDatePair('#calendar_range', 'date_input', '');
710
711
	return $calendarGrid;
712
}
713
714
/**
715
 * Loads the necessary JavaScript and CSS to create a datepicker.
716
 *
717
 * @param string $selector A CSS selector for the input field(s) that the datepicker should be attached to.
718
 * @param string $date_format The date format to use, in strftime() format.
719
 */
720
function loadDatePicker($selector = 'input.date_input', $date_format = '')
721
{
722
	global $modSettings, $txt, $context, $user_info, $options;
723
724
	if (empty($date_format))
725
		$date_format = get_date_or_time_format('date');
726
727
	// Convert to format used by datepicker
728
	$date_format = strtr($date_format, array(
729
		// Day
730
		'%a' => 'D', '%A' => 'DD', '%e' => 'd', '%d' => 'dd', '%j' => 'oo', '%u' => '', '%w' => '',
731
		// Week
732
		'%U' => '', '%V' => '', '%W' => '',
733
		// Month
734
		'%b' => 'M', '%B' => 'MM', '%h' => 'M', '%m' => 'mm',
735
		// Year
736
		'%C' => '', '%g' => 'y', '%G' => 'yy', '%y' => 'y', '%Y' => 'yy',
737
		// Time (we remove all of these)
738
		'%H' => '', '%k' => '', '%I' => '', '%l' => '', '%M' => '', '%p' => '', '%P' => '',
739
		'%r' => '', '%R' => '', '%S' => '', '%T' => '', '%X' => '', '%z' => '', '%Z' => '',
740
		// Time and Date Stamps
741
		'%c' => 'D, d M yy', '%D' => 'mm/dd/y', '%F' => 'yy-mm-dd', '%s' => '@', '%x' => 'D, d M yy',
742
		// Miscellaneous
743
		'%n' => ' ', '%t' => ' ', '%%' => '%',
744
	));
745
746
	loadCSSFile('jquery-ui.datepicker.css', array(), 'smf_datepicker');
747
	loadJavaScriptFile('jquery-ui.datepicker.min.js', array('defer' => true), 'smf_datepicker');
748
	addInlineJavaScript('
749
	$("' . $selector . '").datepicker({
750
		dateFormat: "' . $date_format . '",
751
		autoSize: true,
752
		isRTL: ' . ($context['right_to_left'] ? 'true' : 'false') . ',
753
		constrainInput: true,
754
		showAnim: "",
755
		showButtonPanel: false,
756
		yearRange: "' . $modSettings['cal_minyear'] . ':' . $modSettings['cal_maxyear'] . '",
757
		hideIfNoPrevNext: true,
758
		monthNames: ["' . implode('", "', $txt['months_titles']) . '"],
759
		monthNamesShort: ["' . implode('", "', $txt['months_short']) . '"],
760
		dayNames: ["' . implode('", "', $txt['days']) . '"],
761
		dayNamesShort: ["' . implode('", "', $txt['days_short']) . '"],
762
		dayNamesMin: ["' . implode('", "', $txt['days_short']) . '"],
763
		prevText: "' . $txt['prev_month'] . '",
764
		nextText: "' . $txt['next_month'] . '",
765
		firstDay: ' . (!empty($options['calendar_start_day']) ? $options['calendar_start_day'] : 0) . ',
766
	});', true);
767
}
768
769
/**
770
 * Loads the necessary JavaScript and CSS to create a timepicker.
771
 *
772
 * @param string $selector A CSS selector for the input field(s) that the timepicker should be attached to.
773
 * @param string $time_format A time format in strftime format
774
 */
775
function loadTimePicker($selector = 'input.time_input', $time_format = '')
776
{
777
	global $modSettings, $txt, $context;
778
779
	if (empty($time_format))
780
		$time_format = get_date_or_time_format('time');
781
782
	// Format used for timepicker
783
	$time_format = strtr($time_format, array(
784
		'%H' => 'H',
785
		'%k' => 'G',
786
		'%I' => 'h',
787
		'%l' => 'g',
788
		'%M' => 'i',
789
		'%p' => 'A',
790
		'%P' => 'a',
791
		'%r' => 'h:i:s A',
792
		'%R' => 'H:i',
793
		'%S' => 's',
794
		'%T' => 'H:i:s',
795
		'%X' => 'H:i:s',
796
	));
797
798
	loadCSSFile('jquery.timepicker.css', array(), 'smf_timepicker');
799
	loadJavaScriptFile('jquery.timepicker.min.js', array('defer' => true), 'smf_timepicker');
800
	addInlineJavaScript('
801
	$("' . $selector . '").timepicker({
802
		timeFormat: "' . $time_format . '",
803
		showDuration: true,
804
		maxTime: "23:59:59",
805
		lang: {
806
			am: "' . strtolower($txt['time_am']) . '",
807
			pm: "' . strtolower($txt['time_pm']) . '",
808
			AM: "' . strtoupper($txt['time_am']) . '",
809
			PM: "' . strtoupper($txt['time_pm']) . '",
810
			decimal: "' . $txt['decimal_sign'] . '",
811
			mins: "' . $txt['minutes_short'] . '",
812
			hr: "' . $txt['hour_short'] . '",
813
			hrs: "' . $txt['hours_short'] . '",
814
		}
815
	});', true);
816
}
817
818
/**
819
 * Loads the necessary JavaScript for Datepair.js.
820
 *
821
 * Datepair.js helps to keep date ranges sane in the UI.
822
 *
823
 * @param string $container CSS selector for the containing element of the date/time inputs to be paired.
824
 * @param string $date_class The CSS class of the date inputs to be paired.
825
 * @param string $time_class The CSS class of the time inputs to be paired.
826
 */
827
function loadDatePair($container, $date_class = '', $time_class = '')
828
{
829
	global $modSettings, $txt, $context;
830
831
	$container = (string) $container;
832
	$date_class = (string) $date_class;
833
	$time_class = (string) $time_class;
834
835
	if ($container == '')
836
		return;
837
838
	loadJavaScriptFile('jquery.datepair.min.js', array('defer' => true), 'smf_datepair');
839
840
	$datepair_options = '';
841
842
	// If we're not using a date input, we might as well disable these.
843
	if ($date_class == '')
844
	{
845
		$datepair_options .= '
846
		parseDate: function (el) {},
847
		updateDate: function (el, v) {},';
848
	}
849
	else
850
	{
851
		$datepair_options .= '
852
		dateClass: "' . $date_class . '",';
853
854
		// Customize Datepair to work with jQuery UI's datepicker.
855
		$datepair_options .= '
856
		parseDate: function (el) {
857
			var val = $(el).datepicker("getDate");
858
			if (!val) {
859
				return null;
860
			}
861
			var utc = new Date(val);
862
			return utc && new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
863
		},
864
		updateDate: function (el, v) {
865
			$(el).datepicker("setDate", new Date(v.getTime() - (v.getTimezoneOffset() * 60000)));
866
		},';
867
	}
868
869
	// If not using a time input, disable time functions.
870
	if ($time_class == '')
871
	{
872
		$datepair_options .= '
873
		parseTime: function(input){},
874
		updateTime: function(input, dateObj){},
875
		setMinTime: function(input, dateObj){},';
876
	}
877
	else
878
	{
879
		$datepair_options .= '
880
		timeClass: "' . $time_class . '",';
881
	}
882
883
	addInlineJavaScript('
884
	$("' . $container . '").datepair({' . $datepair_options . "\n\t});", true);
885
886
}
887
888
/**
889
 * Retrieve all events for the given days, independently of the users offset.
890
 * cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
891
 * widens the search range by an extra 24 hours to support time offset shifts.
892
 * used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
893
 *
894
 * @param array $eventOptions With the keys 'num_days_shown', 'include_holidays', 'include_birthdays' and 'include_events'
895
 * @return array An array containing the data that was cached as well as an expression to calculate whether the data should be refreshed and when it expires
896
 */
897
function cache_getOffsetIndependentEvents($eventOptions)
898
{
899
	$days_to_index = $eventOptions['num_days_shown'];
900
901
	$low_date = smf_strftime('%Y-%m-%d', time() - 24 * 3600);
902
	$high_date = smf_strftime('%Y-%m-%d', time() + $days_to_index * 24 * 3600);
903
904
	return array(
905
		'data' => array(
906
			'holidays' => (!empty($eventOptions['include_holidays']) ? getHolidayRange($low_date, $high_date) : array()),
907
			'birthdays' => (!empty($eventOptions['include_birthdays']) ? getBirthdayRange($low_date, $high_date) : array()),
908
			'events' => (!empty($eventOptions['include_events']) ? getEventRange($low_date, $high_date, false) : array()),
909
		),
910
		'refresh_eval' => 'return \'' . smf_strftime('%Y%m%d', time()) . '\' != smf_strftime(\'%Y%m%d\', time()) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
911
		'expires' => time() + 3600,
912
	);
913
}
914
915
/**
916
 * cache callback function used to retrieve the upcoming birthdays, holidays, and events within the given period, taking into account the users time offset.
917
 * Called from the BoardIndex to display the current day's events on the board index
918
 * used by the board index and SSI to show the upcoming events.
919
 *
920
 * @param array $eventOptions An array of event options.
921
 * @return array An array containing the info that was cached as well as a few other relevant things
922
 */
923
function cache_getRecentEvents($eventOptions)
924
{
925
	// With the 'static' cached data we can calculate the user-specific data.
926
	$cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions));
927
928
	// Get the information about today (from user perspective).
929
	$today = getTodayInfo();
930
931
	$return_data = array(
932
		'calendar_holidays' => array(),
933
		'calendar_birthdays' => array(),
934
		'calendar_events' => array(),
935
	);
936
937
	// Set the event span to be shown in seconds.
938
	$days_for_index = $eventOptions['num_days_shown'] * 86400;
939
940
	// Get the current member time/date.
941
	$now = time();
942
943
	if (!empty($eventOptions['include_holidays']))
944
	{
945
		// Holidays between now and now + days.
946
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
947
		{
948
			if (isset($cached_data['holidays'][smf_strftime('%Y-%m-%d', $i)]))
949
				$return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][smf_strftime('%Y-%m-%d', $i)]);
950
		}
951
	}
952
953
	if (!empty($eventOptions['include_birthdays']))
954
	{
955
		// Happy Birthday, guys and gals!
956
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
957
		{
958
			$loop_date = smf_strftime('%Y-%m-%d', $i);
959
			if (isset($cached_data['birthdays'][$loop_date]))
960
			{
961
				foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
962
					$cached_data['birthdays'][smf_strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
963
				$return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
964
			}
965
		}
966
	}
967
968
	if (!empty($eventOptions['include_events']))
969
	{
970
		$duplicates = array();
971
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
972
		{
973
			// Determine the date of the current loop step.
974
			$loop_date = smf_strftime('%Y-%m-%d', $i);
975
976
			// No events today? Check the next day.
977
			if (empty($cached_data['events'][$loop_date]))
978
				continue;
979
980
			// Loop through all events to add a few last-minute values.
981
			foreach ($cached_data['events'][$loop_date] as $ev => $event)
982
			{
983
				// Create a shortcut variable for easier access.
984
				$this_event = &$cached_data['events'][$loop_date][$ev];
985
986
				// Skip duplicates.
987
				if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
988
				{
989
					unset($cached_data['events'][$loop_date][$ev]);
990
					continue;
991
				}
992
				else
993
					$duplicates[$this_event['topic'] . $this_event['title']] = true;
994
995
				// Might be set to true afterwards, depending on the permissions.
996
				$this_event['can_edit'] = false;
997
				$this_event['is_today'] = $loop_date === $today['date'];
998
				$this_event['date'] = $loop_date;
999
			}
1000
1001
			if (!empty($cached_data['events'][$loop_date]))
1002
				$return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
1003
		}
1004
	}
1005
1006
	// Mark the last item so that a list separator can be used in the template.
1007
	for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
1008
		$return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
1009
	for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
1010
		$return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
1011
1012
	return array(
1013
		'data' => $return_data,
1014
		'expires' => time() + 3600,
1015
		'refresh_eval' => 'return \'' . smf_strftime('%Y%m%d', time()) . '\' != smf_strftime(\'%Y%m%d\', time()) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
1016
		'post_retri_eval' => '
1017
			global $context, $scripturl, $user_info;
1018
1019
			foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
1020
			{
1021
				// Remove events that the user may not see or wants to ignore.
1022
				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\']))
1023
					unset($cache_block[\'data\'][\'calendar_events\'][$k]);
1024
				else
1025
				{
1026
					// Whether the event can be edited depends on the permissions.
1027
					$cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));
1028
1029
					// The added session code makes this URL not cachable.
1030
					$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\'];
1031
				}
1032
			}
1033
1034
			if (empty($params[0][\'include_holidays\']))
1035
				$cache_block[\'data\'][\'calendar_holidays\'] = array();
1036
			if (empty($params[0][\'include_birthdays\']))
1037
				$cache_block[\'data\'][\'calendar_birthdays\'] = array();
1038
			if (empty($params[0][\'include_events\']))
1039
				$cache_block[\'data\'][\'calendar_events\'] = array();
1040
1041
			$cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
1042
	);
1043
}
1044
1045
/**
1046
 * Makes sure the calendar post is valid.
1047
 */
1048
function validateEventPost()
1049
{
1050
	global $modSettings, $smcFunc;
1051
1052
	if (!isset($_POST['deleteevent']))
1053
	{
1054
		// The 2.1 way
1055
		if (isset($_POST['start_date']))
1056
		{
1057
			$d = date_parse(str_replace(',', '', convertDateToEnglish($_POST['start_date'])));
1058
			if (!empty($d['error_count']) || !empty($d['warning_count']))
1059
				fatal_lang_error('invalid_date', false);
1060
			if (empty($d['year']))
1061
				fatal_lang_error('event_year_missing', false);
1062
			if (empty($d['month']))
1063
				fatal_lang_error('event_month_missing', false);
1064
		}
1065
		elseif (isset($_POST['start_datetime']))
1066
		{
1067
			$d = date_parse(str_replace(',', '', convertDateToEnglish($_POST['start_datetime'])));
1068
			if (!empty($d['error_count']) || !empty($d['warning_count']))
1069
				fatal_lang_error('invalid_date', false);
1070
			if (empty($d['year']))
1071
				fatal_lang_error('event_year_missing', false);
1072
			if (empty($d['month']))
1073
				fatal_lang_error('event_month_missing', false);
1074
		}
1075
		// The 2.0 way
1076
		else
1077
		{
1078
			// No month?  No year?
1079
			if (!isset($_POST['month']))
1080
				fatal_lang_error('event_month_missing', false);
1081
			if (!isset($_POST['year']))
1082
				fatal_lang_error('event_year_missing', false);
1083
1084
			// Check the month and year...
1085
			if ($_POST['month'] < 1 || $_POST['month'] > 12)
1086
				fatal_lang_error('invalid_month', false);
1087
			if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
1088
				fatal_lang_error('invalid_year', false);
1089
		}
1090
	}
1091
1092
	// Make sure they're allowed to post...
1093
	isAllowedTo('calendar_post');
1094
1095
	// If they want to us to calculate an end date, make sure it will fit in an acceptable range.
1096
	if (isset($_POST['span']))
1097
	{
1098
		if (($_POST['span'] < 1) || (!empty($modSettings['cal_maxspan']) && $_POST['span'] > $modSettings['cal_maxspan']))
1099
			fatal_lang_error('invalid_days_numb', false);
1100
	}
1101
1102
	// There is no need to validate the following values if we are just deleting the event.
1103
	if (!isset($_POST['deleteevent']))
1104
	{
1105
		// If we're doing things the 2.0 way, check the day
1106
		if (empty($_POST['start_date']) && empty($_POST['start_datetime']))
1107
		{
1108
			// No day?
1109
			if (!isset($_POST['day']))
1110
				fatal_lang_error('event_day_missing', false);
1111
1112
			// Bad day?
1113
			if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
1114
				fatal_lang_error('invalid_date', false);
1115
		}
1116
1117
		if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
1118
			fatal_lang_error('event_title_missing', false);
1119
		elseif (!isset($_POST['evtitle']))
1120
			$_POST['evtitle'] = $_POST['subject'];
1121
1122
		// No title?
1123
		if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
1124
			fatal_lang_error('no_event_title', false);
1125
		if ($smcFunc['strlen']($_POST['evtitle']) > 100)
1126
			$_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 100);
1127
		$_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
1128
	}
1129
}
1130
1131
/**
1132
 * Get the event's poster.
1133
 *
1134
 * @param int $event_id The ID of the event
1135
 * @return int|bool The ID of the poster or false if the event was not found
1136
 */
1137
function getEventPoster($event_id)
1138
{
1139
	global $smcFunc;
1140
1141
	// A simple database query, how hard can that be?
1142
	$request = $smcFunc['db_query']('', '
1143
		SELECT id_member
1144
		FROM {db_prefix}calendar
1145
		WHERE id_event = {int:id_event}
1146
		LIMIT 1',
1147
		array(
1148
			'id_event' => $event_id,
1149
		)
1150
	);
1151
1152
	// No results, return false.
1153
	if ($smcFunc['db_num_rows'] === 0)
1154
		return false;
1155
1156
	// Grab the results and return.
1157
	list ($poster) = $smcFunc['db_fetch_row']($request);
1158
	$smcFunc['db_free_result']($request);
1159
	return (int) $poster;
1160
}
1161
1162
/**
1163
 * Consolidating the various INSERT statements into this function.
1164
 * Inserts the passed event information into the calendar table.
1165
 * Allows to either set a time span (in days) or an end_date.
1166
 * Does not check any permissions of any sort.
1167
 *
1168
 * @param array $eventOptions An array of event options ('title', 'span', 'start_date', 'end_date', etc.)
1169
 */
1170
function insertEvent(&$eventOptions)
1171
{
1172
	global $smcFunc, $context;
1173
1174
	// Add special chars to the title.
1175
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
1176
1177
	$eventOptions['location'] = isset($eventOptions['location']) ? $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES) : '';
1178
1179
	// Set the start and end dates and times
1180
	list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);
1181
1182
	// If no topic and board are given, they are not linked to a topic.
1183
	$eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
1184
	$eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;
1185
1186
	$event_columns = array(
1187
		'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
1188
		'start_date' => 'date', 'end_date' => 'date', 'location' => 'string-255',
1189
	);
1190
	$event_parameters = array(
1191
		$eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
1192
		$start_date, $end_date, $eventOptions['location'],
1193
	);
1194
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
1195
	{
1196
		$event_columns['start_time'] = 'time';
1197
		$event_parameters[] = $start_time;
1198
		$event_columns['end_time'] = 'time';
1199
		$event_parameters[] = $end_time;
1200
		$event_columns['timezone'] = 'string';
1201
		$event_parameters[] = $tz;
1202
	}
1203
1204
	call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));
1205
1206
	// Insert the event!
1207
	$eventOptions['id'] = $smcFunc['db_insert']('',
1208
		'{db_prefix}calendar',
1209
		$event_columns,
1210
		$event_parameters,
1211
		array('id_event'),
1212
		1
1213
	);
1214
1215
	// If this isn't tied to a topic, we need to notify people about it.
1216
	if (empty($eventOptions['topic']))
1217
	{
1218
		$smcFunc['db_insert']('insert',
1219
			'{db_prefix}background_tasks',
1220
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
1221
			array('$sourcedir/tasks/EventNew-Notify.php', 'EventNew_Notify_Background', $smcFunc['json_encode'](array(
1222
				'event_title' => $eventOptions['title'],
1223
				'event_id' => $eventOptions['id'],
1224
				'sender_id' => $eventOptions['member'],
1225
				'sender_name' => $eventOptions['member'] == $context['user']['id'] ? $context['user']['name'] : '',
1226
				'time' => time(),
1227
			)), 0),
1228
			array('id_task')
1229
		);
1230
	}
1231
1232
	// Update the settings to show something calendar-ish was updated.
1233
	updateSettings(array(
1234
		'calendar_updated' => time(),
1235
	));
1236
}
1237
1238
/**
1239
 * modifies an event.
1240
 * allows to either set a time span (in days) or an end_date.
1241
 * does not check any permissions of any sort.
1242
 *
1243
 * @param int $event_id The ID of the event
1244
 * @param array $eventOptions An array of event information
1245
 */
1246
function modifyEvent($event_id, &$eventOptions)
1247
{
1248
	global $smcFunc;
1249
1250
	// Properly sanitize the title and location
1251
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
1252
	$eventOptions['location'] = $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES);
1253
1254
	// Set the new start and end dates and times
1255
	list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);
1256
1257
	$event_columns = array(
1258
		'start_date' => '{date:start_date}',
1259
		'end_date' => '{date:end_date}',
1260
		'title' => 'SUBSTRING({string:title}, 1, 60)',
1261
		'id_board' => '{int:id_board}',
1262
		'id_topic' => '{int:id_topic}',
1263
		'location' => 'SUBSTRING({string:location}, 1, 255)',
1264
	);
1265
	$event_parameters = array(
1266
		'start_date' => $start_date,
1267
		'end_date' => $end_date,
1268
		'title' => $eventOptions['title'],
1269
		'location' => $eventOptions['location'],
1270
		'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
1271
		'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
1272
	);
1273
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
1274
	{
1275
		$event_columns['start_time'] = '{time:start_time}';
1276
		$event_parameters['start_time'] = $start_time;
1277
		$event_columns['end_time'] = '{time:end_time}';
1278
		$event_parameters['end_time'] = $end_time;
1279
		$event_columns['timezone'] = '{string:timezone}';
1280
		$event_parameters['timezone'] = $tz;
1281
	}
1282
1283
	// This is to prevent hooks to modify the id of the event
1284
	$real_event_id = $event_id;
1285
	call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns, &$event_parameters));
1286
1287
	$column_clauses = array();
1288
	foreach ($event_columns as $col => $crit)
1289
		$column_clauses[] = $col . ' = ' . $crit;
1290
1291
	$smcFunc['db_query']('', '
1292
		UPDATE {db_prefix}calendar
1293
		SET
1294
			' . implode(', ', $column_clauses) . '
1295
		WHERE id_event = {int:id_event}',
1296
		array_merge(
1297
			$event_parameters,
1298
			array(
1299
				'id_event' => $real_event_id
1300
			)
1301
		)
1302
	);
1303
1304
	if (empty($start_time) || empty($end_time) || empty($tz) || !in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
1305
	{
1306
		$smcFunc['db_query']('', '
1307
			UPDATE {db_prefix}calendar
1308
			SET start_time = NULL, end_time = NULL, timezone = NULL
1309
			WHERE id_event = {int:id_event}',
1310
			array(
1311
				'id_event' => $real_event_id
1312
			)
1313
		);
1314
	}
1315
1316
	updateSettings(array(
1317
		'calendar_updated' => time(),
1318
	));
1319
}
1320
1321
/**
1322
 * Remove an event
1323
 * removes an event.
1324
 * does no permission checks.
1325
 *
1326
 * @param int $event_id The ID of the event to remove
1327
 */
1328
function removeEvent($event_id)
1329
{
1330
	global $smcFunc;
1331
1332
	$smcFunc['db_query']('', '
1333
		DELETE FROM {db_prefix}calendar
1334
		WHERE id_event = {int:id_event}',
1335
		array(
1336
			'id_event' => $event_id,
1337
		)
1338
	);
1339
1340
	call_integration_hook('integrate_remove_event', array($event_id));
1341
1342
	updateSettings(array(
1343
		'calendar_updated' => time(),
1344
	));
1345
}
1346
1347
/**
1348
 * Gets all the events properties
1349
 *
1350
 * @param int $event_id The ID of the event
1351
 * @return array An array of event information
1352
 */
1353
function getEventProperties($event_id)
1354
{
1355
	global $smcFunc;
1356
1357
	$request = $smcFunc['db_query']('', '
1358
		SELECT
1359
			c.id_event, c.id_board, c.id_topic, c.id_member, c.title,
1360
			c.start_date, c.end_date, c.start_time, c.end_time, c.timezone, c.location,
1361
			t.id_first_msg, t.id_member_started,
1362
			mb.real_name, m.modified_time
1363
		FROM {db_prefix}calendar AS c
1364
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
1365
			LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
1366
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg  = t.id_first_msg)
1367
		WHERE c.id_event = {int:id_event}',
1368
		array(
1369
			'id_event' => $event_id,
1370
		)
1371
	);
1372
1373
	// If nothing returned, we are in poo, poo.
1374
	if ($smcFunc['db_num_rows']($request) === 0)
1375
		return false;
1376
1377
	$row = $smcFunc['db_fetch_assoc']($request);
1378
	$smcFunc['db_free_result']($request);
1379
1380
	list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
1381
1382
	// Sanity check
1383
	if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
1384
		return false;
1385
1386
	$return_value = array(
1387
		'boards' => array(),
1388
		'board' => $row['id_board'],
1389
		'new' => 0,
1390
		'eventid' => $event_id,
1391
		'year' => $start['year'],
1392
		'month' => $start['month'],
1393
		'day' => $start['day'],
1394
		'hour' => !$allday ? $start['hour'] : null,
1395
		'minute' => !$allday ? $start['minute'] : null,
1396
		'second' => !$allday ? $start['second'] : null,
1397
		'start_date' => $row['start_date'],
1398
		'start_date_local' => $start['date_local'],
1399
		'start_date_orig' => $start['date_orig'],
1400
		'start_time' => !$allday ? $row['start_time'] : null,
1401
		'start_time_local' => !$allday ? $start['time_local'] : null,
1402
		'start_time_orig' => !$allday ? $start['time_orig'] : null,
1403
		'start_timestamp' => $start['timestamp'],
1404
		'start_datetime' => $start['datetime'],
1405
		'start_iso_gmdate' => $start['iso_gmdate'],
1406
		'end_year' => $end['year'],
1407
		'end_month' => $end['month'],
1408
		'end_day' => $end['day'],
1409
		'end_hour' => !$allday ? $end['hour'] : null,
1410
		'end_minute' => !$allday ? $end['minute'] : null,
1411
		'end_second' => !$allday ? $end['second'] : null,
1412
		'end_date' => $row['end_date'],
1413
		'end_date_local' => $end['date_local'],
1414
		'end_date_orig' => $end['date_orig'],
1415
		'end_time' => !$allday ? $row['end_time'] : null,
1416
		'end_time_local' => !$allday ? $end['time_local'] : null,
1417
		'end_time_orig' => !$allday ? $end['time_orig'] : null,
1418
		'end_timestamp' => $end['timestamp'],
1419
		'end_datetime' => $end['datetime'],
1420
		'end_iso_gmdate' => $end['iso_gmdate'],
1421
		'allday' => $allday,
1422
		'tz' => !$allday ? $tz : null,
1423
		'tz_abbrev' => !$allday ? $tz_abbrev : null,
1424
		'span' => $span,
1425
		'title' => $row['title'],
1426
		'location' => $row['location'],
1427
		'member' => $row['id_member'],
1428
		'realname' => $row['real_name'],
1429
		'sequence' => $row['modified_time'],
1430
		'topic' => array(
1431
			'id' => $row['id_topic'],
1432
			'member_started' => $row['id_member_started'],
1433
			'first_msg' => $row['id_first_msg'],
1434
		),
1435
	);
1436
1437
	$return_value['last_day'] = (int) smf_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']));
1438
1439
	return $return_value;
1440
}
1441
1442
/**
1443
 * Gets an initial set of date and time values for creating a new event.
1444
 *
1445
 * @return array An array containing an initial set of date and time values for an event.
1446
 */
1447
function getNewEventDatetimes()
1448
{
1449
	// Ensure setEventStartEnd() has something to work with
1450
	$now = date_create();
1451
	$tz = getUserTimezone();
1452
	date_timezone_set($now, timezone_open($tz));
1453
1454
	$_POST['year'] = !empty($_POST['year']) ? $_POST['year'] : date_format($now, 'Y');
1455
	$_POST['month'] = !empty($_POST['month']) ? $_POST['month'] : date_format($now, 'm');
1456
	$_POST['day'] = !empty($_POST['day']) ? $_POST['day'] : date_format($now, 'd');
1457
	$_POST['hour'] = !empty($_POST['hour']) ? $_POST['hour'] : date_format($now, 'H');
1458
	$_POST['minute'] = !empty($_POST['minute']) ? $_POST['minute'] : date_format($now, 'i');
1459
	$_POST['second'] = !empty($_POST['second']) ? $_POST['second'] : date_format($now, 's');
1460
1461
	// Set the basic values for the new event
1462
	$row_keys = array('start_date', 'end_date', 'start_time', 'end_time', 'timezone');
1463
	$row = array_combine($row_keys, setEventStartEnd());
1464
1465
	// And now set the full suite of values
1466
	list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
1467
1468
	// Default theme only uses some of this info, but others might want it all
1469
	$eventProperties = array(
1470
		'year' => $start['year'],
1471
		'month' => $start['month'],
1472
		'day' => $start['day'],
1473
		'hour' => !$allday ? $start['hour'] : null,
1474
		'minute' => !$allday ? $start['minute'] : null,
1475
		'second' => !$allday ? $start['second'] : null,
1476
		'start_date' => $row['start_date'],
1477
		'start_date_local' => $start['date_local'],
1478
		'start_date_orig' => $start['date_orig'],
1479
		'start_time' => !$allday ? $row['start_time'] : null,
1480
		'start_time_local' => !$allday ? $start['time_local'] : null,
1481
		'start_time_orig' => !$allday ? $start['time_orig'] : null,
1482
		'start_timestamp' => $start['timestamp'],
1483
		'start_datetime' => $start['datetime'],
1484
		'start_iso_gmdate' => $start['iso_gmdate'],
1485
		'end_year' => $end['year'],
1486
		'end_month' => $end['month'],
1487
		'end_day' => $end['day'],
1488
		'end_hour' => !$allday ? $end['hour'] : null,
1489
		'end_minute' => !$allday ? $end['minute'] : null,
1490
		'end_second' => !$allday ? $end['second'] : null,
1491
		'end_date' => $row['end_date'],
1492
		'end_date_local' => $end['date_local'],
1493
		'end_date_orig' => $end['date_orig'],
1494
		'end_time' => !$allday ? $row['end_time'] : null,
1495
		'end_time_local' => !$allday ? $end['time_local'] : null,
1496
		'end_time_orig' => !$allday ? $end['time_orig'] : null,
1497
		'end_timestamp' => $end['timestamp'],
1498
		'end_datetime' => $end['datetime'],
1499
		'end_iso_gmdate' => $end['iso_gmdate'],
1500
		'allday' => $allday,
1501
		'tz' => !$allday ? $tz : null,
1502
		'tz_abbrev' => !$allday ? $tz_abbrev : null,
1503
		'span' => $span,
1504
	);
1505
1506
	return $eventProperties;
1507
}
1508
1509
/**
1510
 * Set the start and end dates and times for a posted event for insertion into the database.
1511
 * Validates all date and times given to it.
1512
 * Makes sure events do not exceed the maximum allowed duration (if any).
1513
 * If passed an array that defines any time or date parameters, they will be used. Otherwise, gets the values from $_POST.
1514
 *
1515
 * @param array $eventOptions An array of optional time and date parameters (span, start_year, end_month, etc., etc.)
1516
 * @return array An array containing $start_date, $end_date, $start_time, $end_time
1517
 */
1518
function setEventStartEnd($eventOptions = array())
1519
{
1520
	global $modSettings;
1521
1522
	// Set $span, in case we need it
1523
	$span = isset($eventOptions['span']) ? $eventOptions['span'] : (isset($_POST['span']) ? $_POST['span'] : 0);
1524
	if ($span > 0)
1525
		$span = !empty($modSettings['cal_maxspan']) ? min($modSettings['cal_maxspan'], $span - 1) : $span - 1;
1526
1527
	// Define the timezone for this event, falling back to the default if not provided
1528
	if (!empty($eventOptions['tz']) && in_array($eventOptions['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
1529
		$tz = $eventOptions['tz'];
1530
	elseif (!empty($_POST['tz']) && in_array($_POST['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
1531
		$tz = $_POST['tz'];
1532
	else
1533
		$tz = getUserTimezone();
1534
1535
	// Is this supposed to be an all day event, or should it have specific start and end times?
1536
	if (isset($eventOptions['allday']))
1537
		$allday = $eventOptions['allday'];
1538
	elseif (empty($_POST['allday']))
1539
		$allday = false;
1540
	else
1541
		$allday = true;
1542
1543
	// Input might come as individual parameters...
1544
	$start_year = isset($eventOptions['year']) ? $eventOptions['year'] : (isset($_POST['year']) ? $_POST['year'] : null);
1545
	$start_month = isset($eventOptions['month']) ? $eventOptions['month'] : (isset($_POST['month']) ? $_POST['month'] : null);
1546
	$start_day = isset($eventOptions['day']) ? $eventOptions['day'] : (isset($_POST['day']) ? $_POST['day'] : null);
1547
	$start_hour = isset($eventOptions['hour']) ? $eventOptions['hour'] : (isset($_POST['hour']) ? $_POST['hour'] : null);
1548
	$start_minute = isset($eventOptions['minute']) ? $eventOptions['minute'] : (isset($_POST['minute']) ? $_POST['minute'] : null);
1549
	$start_second = isset($eventOptions['second']) ? $eventOptions['second'] : (isset($_POST['second']) ? $_POST['second'] : null);
1550
	$end_year = isset($eventOptions['end_year']) ? $eventOptions['end_year'] : (isset($_POST['end_year']) ? $_POST['end_year'] : null);
1551
	$end_month = isset($eventOptions['end_month']) ? $eventOptions['end_month'] : (isset($_POST['end_month']) ? $_POST['end_month'] : null);
1552
	$end_day = isset($eventOptions['end_day']) ? $eventOptions['end_day'] : (isset($_POST['end_day']) ? $_POST['end_day'] : null);
1553
	$end_hour = isset($eventOptions['end_hour']) ? $eventOptions['end_hour'] : (isset($_POST['end_hour']) ? $_POST['end_hour'] : null);
1554
	$end_minute = isset($eventOptions['end_minute']) ? $eventOptions['end_minute'] : (isset($_POST['end_minute']) ? $_POST['end_minute'] : null);
1555
	$end_second = isset($eventOptions['end_second']) ? $eventOptions['end_second'] : (isset($_POST['end_second']) ? $_POST['end_second'] : null);
1556
1557
	// ... or as datetime strings ...
1558
	$start_string = isset($eventOptions['start_datetime']) ? $eventOptions['start_datetime'] : (isset($_POST['start_datetime']) ? $_POST['start_datetime'] : null);
1559
	$end_string = isset($eventOptions['end_datetime']) ? $eventOptions['end_datetime'] : (isset($_POST['end_datetime']) ? $_POST['end_datetime'] : null);
1560
1561
	// ... or as date strings and time strings.
1562
	$start_date_string = isset($eventOptions['start_date']) ? $eventOptions['start_date'] : (isset($_POST['start_date']) ? $_POST['start_date'] : null);
1563
	$start_time_string = isset($eventOptions['start_time']) ? $eventOptions['start_time'] : (isset($_POST['start_time']) ? $_POST['start_time'] : null);
1564
	$end_date_string = isset($eventOptions['end_date']) ? $eventOptions['end_date'] : (isset($_POST['end_date']) ? $_POST['end_date'] : null);
1565
	$end_time_string = isset($eventOptions['end_time']) ? $eventOptions['end_time'] : (isset($_POST['end_time']) ? $_POST['end_time'] : null);
1566
1567
	// If the date and time were given in separate strings, combine them
1568
	if (empty($start_string) && isset($start_date_string))
1569
		$start_string = $start_date_string . (isset($start_time_string) ? ' ' . $start_time_string : '');
1570
	if (empty($end_string) && isset($end_date_string))
1571
		$end_string = $end_date_string . (isset($end_time_string) ? ' ' . $end_time_string : '');
1572
1573
	// If some form of string input was given, override individually defined options with it
1574
	if (isset($start_string))
1575
	{
1576
		$start_string_parsed = date_parse(str_replace(',', '', convertDateToEnglish($start_string)));
1577
		if (empty($start_string_parsed['error_count']) && empty($start_string_parsed['warning_count']))
1578
		{
1579
			if ($start_string_parsed['year'] !== false)
1580
			{
1581
				$start_year = $start_string_parsed['year'];
1582
				$start_month = $start_string_parsed['month'];
1583
				$start_day = $start_string_parsed['day'];
1584
			}
1585
			if ($start_string_parsed['hour'] !== false)
1586
			{
1587
				$start_hour = $start_string_parsed['hour'];
1588
				$start_minute = $start_string_parsed['minute'];
1589
				$start_second = $start_string_parsed['second'];
1590
			}
1591
		}
1592
	}
1593
	if (isset($end_string))
1594
	{
1595
		$end_string_parsed = date_parse(str_replace(',', '', convertDateToEnglish($end_string)));
1596
		if (empty($end_string_parsed['error_count']) && empty($end_string_parsed['warning_count']))
1597
		{
1598
			if ($end_string_parsed['year'] !== false)
1599
			{
1600
				$end_year = $end_string_parsed['year'];
1601
				$end_month = $end_string_parsed['month'];
1602
				$end_day = $end_string_parsed['day'];
1603
			}
1604
			if ($end_string_parsed['hour'] !== false)
1605
			{
1606
				$end_hour = $end_string_parsed['hour'];
1607
				$end_minute = $end_string_parsed['minute'];
1608
				$end_second = $end_string_parsed['second'];
1609
			}
1610
		}
1611
	}
1612
1613
	// Validate input
1614
	$start_date_isvalid = isset($start_month, $start_day, $start_year) && checkdate($start_month, $start_day, $start_year);
1615
	$end_date_isvalid = isset($end_month, $end_day, $end_year) && checkdate($end_month, $end_day, $end_year);
1616
	$start_time_isvalid = isset($start_hour, $start_minute, $start_second) && $start_hour >= 0 && $start_hour < 25 && $start_minute >= 0 && $start_minute < 60 && $start_second >= 0 && $start_second < 60;
1617
	$end_time_isvalid = isset($end_hour, $end_minute, $end_second) && $end_hour >= 0 && $end_hour < 25 && $end_minute >= 0 && $end_minute < 60 && $end_second >= 0 && $end_second < 60;
1618
1619
	// Uh-oh...
1620
	if ($start_date_isvalid === false)
1621
	{
1622
		fatal_lang_error('invalid_date', false);
1623
	}
1624
1625
	// Make sure we use valid values for everything
1626
	if ($end_date_isvalid === false)
1627
	{
1628
		$end_year = $start_year;
1629
		$end_month = $start_month;
1630
		$end_day = $start_day;
1631
	}
1632
1633
	if ($allday || !$start_time_isvalid)
1634
	{
1635
		$allday = true;
1636
		$start_hour = 0;
1637
		$start_minute = 0;
1638
		$start_second = 0;
1639
	}
1640
1641
	if ($allday || !$end_time_isvalid)
1642
	{
1643
		$end_hour = $start_hour;
1644
		$end_minute = $start_minute;
1645
		$end_second = $start_second;
1646
	}
1647
1648
	// Now create our datetime objects
1649
	$start_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1650
	$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $end_year, $end_month, $end_day, $end_hour, $end_minute, $end_second) . ' ' . $tz);
1651
1652
	// Is $end_object too early?
1653
	if ($start_object >= $end_object)
1654
	{
1655
		$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1656
		if ($span > 0)
1657
			date_add($end_object, date_interval_create_from_date_string($span . ' days'));
1658
		else
1659
			date_add($end_object, date_interval_create_from_date_string('1 hour'));
1660
	}
1661
1662
	// Is $end_object too late?
1663
	if (!empty($modSettings['cal_maxspan']))
1664
	{
1665
		$date_diff = date_diff($start_object, $end_object);
1666
		if ($date_diff->days > $modSettings['cal_maxspan'])
1667
		{
1668
			if ($modSettings['cal_maxspan'] > 1)
1669
			{
1670
				$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1671
				date_add($end_object, date_interval_create_from_date_string($modSettings['cal_maxspan'] . ' days'));
1672
			}
1673
			else
1674
				$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, '11', '59', '59') . ' ' . $tz);
1675
		}
1676
	}
1677
1678
	// Finally, make our strings
1679
	$start_date = date_format($start_object, 'Y-m-d');
1680
	$end_date = date_format($end_object, 'Y-m-d');
1681
1682
	if ($allday == true)
1683
	{
1684
		$start_time = null;
1685
		$end_time = null;
1686
		$tz = null;
1687
	}
1688
	else
1689
	{
1690
		$start_time = date_format($start_object, 'H:i:s');
1691
		$end_time = date_format($end_object, 'H:i:s');
1692
	}
1693
1694
	return array($start_date, $end_date, $start_time, $end_time, $tz);
1695
}
1696
1697
/**
1698
 * Helper function for getEventRange, getEventProperties, getNewEventDatetimes, etc.
1699
 *
1700
 * @param array $row A database row representing an event from the calendar table
1701
 * @return array An array containing the start and end date and time properties for the event
1702
 */
1703
function buildEventDatetimes($row)
1704
{
1705
	global $sourcedir, $user_info, $txt;
1706
	static $date_format = '', $time_format = '';
1707
1708
	require_once($sourcedir . '/Subs.php');
1709
	static $timezone_array = array();
1710
1711
	loadLanguage('Timezones');
1712
1713
	// First, try to create a better date format, ignoring the "time" elements.
1714
	if (empty($date_format))
1715
		$date_format = get_date_or_time_format('date');
1716
1717
	// We want a fairly compact version of the time, but as close as possible to the user's settings.
1718
	if (empty($time_format))
1719
		$time_format = strtr(get_date_or_time_format('time'), array(
1720
			'%I' => '%l',
1721
			'%H' => '%k',
1722
			'%S' => '',
1723
			'%r' => '%l:%M %p',
1724
			'%R' => '%k:%M',
1725
			'%T' => '%l:%M',
1726
		));
1727
1728
	$time_format = preg_replace('~:(?=\s|$|%[pPzZ])~', '', $time_format);
1729
1730
	// Should this be an all day event?
1731
	$allday = (empty($row['start_time']) || empty($row['end_time']) || empty($row['timezone']) || !in_array($row['timezone'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))) ? true : false;
1732
1733
	// How many days does this event span?
1734
	$span = 1 + date_interval_format(date_diff(date_create($row['start_date']), date_create($row['end_date'])), '%d');
1735
1736
	// We need to have a defined timezone in the steps below
1737
	if (empty($row['timezone']))
1738
		$row['timezone'] = getUserTimezone();
1739
1740
	if (empty($timezone_array[$row['timezone']]))
1741
		$timezone_array[$row['timezone']] = timezone_open($row['timezone']);
1742
1743
	// Get most of the standard date information for the start and end datetimes
1744
	$start = date_parse($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''));
1745
	$end = date_parse($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''));
1746
1747
	// But we also want more info, so make some DateTime objects we can use
1748
	$start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$row['timezone']]);
1749
	$end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$row['timezone']]);
1750
1751
	// Unix timestamps are good
1752
	$start['timestamp'] = (int) date_format($start_object, 'U');
1753
	$end['timestamp'] = (int) date_format($end_object, 'U');
1754
1755
	// Datetime string without timezone  (e.g. '2016-12-28 22:45:30')
1756
	$start['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1757
	$end['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1758
1759
	// ISO formatted datetime string, relative to UTC (e.g. '2016-12-29T05:45:30+00:00')
1760
	$start['iso_gmdate'] = gmdate('c', $start['timestamp']);
1761
	$end['iso_gmdate'] = gmdate('c', $end['timestamp']);
1762
1763
	// Strings showing the datetimes in the user's preferred format, relative to the user's time zone
1764
	list($start['date_local'], $start['time_local']) = explode(' § ', timeformat($start['timestamp'], $date_format . ' § ' . $time_format));
1765
	list($end['date_local'], $end['time_local']) = explode(' § ', timeformat($end['timestamp'], $date_format . ' § ' . $time_format));
1766
1767
	// Strings showing the datetimes in the user's preferred format, relative to the event's time zone
1768
	list($start['date_orig'], $start['time_orig']) = explode(' § ', timeformat(strtotime(date_format($start_object, 'Y-m-d H:i:s')), $date_format . ' § ' . $time_format, 'none'));
1769
	list($end['date_orig'], $end['time_orig']) = explode(' § ', timeformat(strtotime(date_format($end_object, 'Y-m-d H:i:s')), $date_format . ' § ' . $time_format, 'none'));
1770
1771
	// The time zone identifier (e.g. 'Europe/London') and abbreviation (e.g. 'GMT')
1772
	$tz = date_format($start_object, 'e');
1773
	$tz_abbrev = date_format($start_object, 'T');
1774
1775
	// If the abbreviation is just a numerical offset from UTC, make that clear.
1776
	if (strspn($tz_abbrev, '+-') > 0)
1777
		$tz_abbrev = 'UTC' . $tz_abbrev;
1778
1779
	return array($start, $end, $allday, $span, $tz, $tz_abbrev);
1780
}
1781
1782
/**
1783
 * Gets all of the holidays for the listing
1784
 *
1785
 * @param int $start The item to start with (for pagination purposes)
1786
 * @param int $items_per_page How many items to show on each page
1787
 * @param string $sort A string indicating how to sort the results
1788
 * @return array An array of holidays, each of which is an array containing the id, year, month, day and title of the holiday
1789
 */
1790
function list_getHolidays($start, $items_per_page, $sort)
1791
{
1792
	global $smcFunc;
1793
1794
	$request = $smcFunc['db_query']('', '
1795
		SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
1796
		FROM {db_prefix}calendar_holidays
1797
		ORDER BY {raw:sort}
1798
		LIMIT {int:start}, {int:max}',
1799
		array(
1800
			'sort' => $sort,
1801
			'start' => $start,
1802
			'max' => $items_per_page,
1803
		)
1804
	);
1805
	$holidays = array();
1806
	while ($row = $smcFunc['db_fetch_assoc']($request))
1807
		$holidays[] = $row;
1808
	$smcFunc['db_free_result']($request);
1809
1810
	return $holidays;
1811
}
1812
1813
/**
1814
 * Helper function to get the total number of holidays
1815
 *
1816
 * @return int The total number of holidays
1817
 */
1818
function list_getNumHolidays()
1819
{
1820
	global $smcFunc;
1821
1822
	$request = $smcFunc['db_query']('', '
1823
		SELECT COUNT(*)
1824
		FROM {db_prefix}calendar_holidays',
1825
		array(
1826
		)
1827
	);
1828
	list($num_items) = $smcFunc['db_fetch_row']($request);
1829
	$smcFunc['db_free_result']($request);
1830
1831
	return (int) $num_items;
1832
}
1833
1834
/**
1835
 * Remove a holiday from the calendar
1836
 *
1837
 * @param array $holiday_ids An array of IDs of holidays to delete
1838
 */
1839
function removeHolidays($holiday_ids)
1840
{
1841
	global $smcFunc;
1842
1843
	$smcFunc['db_query']('', '
1844
		DELETE FROM {db_prefix}calendar_holidays
1845
		WHERE id_holiday IN ({array_int:id_holiday})',
1846
		array(
1847
			'id_holiday' => $holiday_ids,
1848
		)
1849
	);
1850
1851
	updateSettings(array(
1852
		'calendar_updated' => time(),
1853
	));
1854
}
1855
1856
/**
1857
 * Helper function to convert date string to english
1858
 * so that date_parse can parse the date
1859
 *
1860
 * @param string $date A localized date string
1861
 * @return string English date string
1862
 */
1863
function convertDateToEnglish($date)
1864
{
1865
	global $txt, $context;
1866
1867
	if ($context['user']['language'] == 'english')
1868
		return $date;
1869
1870
	$replacements = array_combine(array_map('strtolower', $txt['months_titles']), array(
1871
		'January', 'February', 'March', 'April', 'May', 'June',
1872
		'July', 'August', 'September', 'October', 'November', 'December'
1873
	));
1874
	$replacements += array_combine(array_map('strtolower', $txt['months_short']), array(
1875
		'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
1876
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
1877
	));
1878
	$replacements += array_combine(array_map('strtolower', $txt['days']), array(
1879
		'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
1880
	));
1881
	$replacements += array_combine(array_map('strtolower', $txt['days_short']), array(
1882
		'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
1883
	));
1884
	// Find all possible variants of AM and PM for this language.
1885
	if (trim($txt['time_am']) !== '' && trim($txt['time_pm']) !== '')
1886
	{
1887
		$replacements[strtolower($txt['time_am'])] = 'AM';
1888
		$replacements[strtolower($txt['time_pm'])] = 'PM';
1889
	}
1890
	if (($am = smf_strftime('%p', strtotime('01:00:00'))) !== 'p' && $am !== false)
1891
	{
1892
		$replacements[strtolower($am)] = 'AM';
1893
		$replacements[strtolower(smf_strftime('%p', strtotime('23:00:00')))] = 'PM';
1894
	}
1895
	if (($am = smf_strftime('%P', strtotime('01:00:00'))) !== 'P' && $am !== false)
1896
	{
1897
		$replacements[strtolower($am)] = 'AM';
1898
		$replacements[strtolower(smf_strftime('%P', strtotime('23:00:00')))] = 'PM';
1899
	}
1900
1901
	return strtr(strtolower($date), $replacements);
1902
}
1903
1904
?>