Issues (1014)

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