Passed
Pull Request — release-2.1 (#6635)
by
unknown
21:27
created

convertDateToEnglish()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 1
dl 0
loc 27
rs 9.7
c 0
b 0
f 0
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 2021 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC3
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']('birthday_array', '
40
			SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
41
			FROM {db_prefix}members
42
			WHERE MONTH(birthdate) != {int:no_month}
43
				AND DAYOFMONTH(birthdate) != {int:no_day}
44
				AND YEAR(birthdate) <= {int:max_year}
45
				AND (
46
					DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
47
					OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
48
				)
49
				AND is_activated = {int:is_activated}',
50
			array(
51
				'is_activated' => 1,
52
				'no_month' => 0,
53
				'no_day' => 0,
54
				'year_low' => $year_low . '-%m-%d',
55
				'year_high' => $year_high . '-%m-%d',
56
				'low_date' => $low_date,
57
				'high_date' => $high_date,
58
				'max_year' => $year_high,
59
			)
60
		);
61
	}
62
	else
63
	{
64
		$result = $smcFunc['db_query']('birthday_array', '
65
			SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
66
			FROM {db_prefix}members
67
			WHERE YEAR(birthdate) != {string:year_one}
68
				AND MONTH(birthdate) != {int:no_month}
69
				AND DAYOFMONTH(birthdate) != {int:no_day}
70
				AND (
71
					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 ? '' : '
72
					OR  indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_high_low_date}) AND indexable_month_day({date:year_high_high_date})') . '
73
				)
74
				AND is_activated = {int:is_activated}',
75
			array(
76
				'is_activated' => 1,
77
				'no_month' => 0,
78
				'no_day' => 0,
79
				'year_one' => '1004',
80
				'year_low' => $year_low . '-%m-%d',
81
				'year_high' => $year_high . '-%m-%d',
82
				'year_low_low_date' => $low_date,
83
				'year_low_high_date' => ($year_low == $year_high ? $high_date : $year_low . '-12-31'),
84
				'year_high_low_date' => ($year_low == $year_high ? $low_date : $year_high . '-01-01'),
85
				'year_high_high_date' => $high_date,
86
			)
87
		);
88
	}
89
	$bday = array();
90
	while ($row = $smcFunc['db_fetch_assoc']($result))
91
	{
92
		if ($year_low != $year_high)
93
			$age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
94
		else
95
			$age_year = $year_low;
96
97
		$bday[$age_year . substr($row['birthdate'], 4)][] = array(
98
			'id' => $row['id_member'],
99
			'name' => $row['real_name'],
100
			'age' => $row['birth_year'] > 1004 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
101
			'is_last' => false
102
		);
103
	}
104
	$smcFunc['db_free_result']($result);
105
106
	ksort($bday);
107
108
	// Set is_last, so the themes know when to stop placing separators.
109
	foreach ($bday as $mday => $array)
110
		$bday[$mday][count($array) - 1]['is_last'] = true;
111
112
	return $bday;
113
}
114
115
/**
116
 * Get all calendar events within the given time range.
117
 *
118
 * - finds all the posted calendar events within a date range.
119
 * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
120
 * - censors the posted event titles.
121
 * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
122
 *
123
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
124
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
125
 * @param bool $use_permissions Whether to use permissions
126
 * @return array Contextual information if use_permissions is true, and an array of the data needed to build that otherwise
127
 */
128
function getEventRange($low_date, $high_date, $use_permissions = true)
129
{
130
	global $scripturl, $modSettings, $user_info, $smcFunc, $context, $sourcedir;
131
	static $timezone_array = array();
132
	require_once($sourcedir . '/Subs.php');
133
134
	if (empty($timezone_array['default']))
135
		$timezone_array['default'] = timezone_open(date_default_timezone_get());
136
137
	$low_object = date_create($low_date);
138
	$high_object = date_create($high_date);
139
140
	// Find all the calendar info...
141
	$result = $smcFunc['db_query']('calendar_get_events', '
142
		SELECT
143
			cal.id_event, cal.title, cal.id_member, cal.id_topic, cal.id_board,
144
			cal.start_date, cal.end_date, cal.start_time, cal.end_time, cal.timezone, cal.location,
145
			b.member_groups, t.id_first_msg, t.approved, b.id_board
146
		FROM {db_prefix}calendar AS cal
147
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
148
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
149
		WHERE cal.start_date <= {date:high_date}
150
			AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
151
			AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
152
		array(
153
			'high_date' => $high_date,
154
			'low_date' => $low_date,
155
			'no_board_link' => 0,
156
		)
157
	);
158
	$events = array();
159
	while ($row = $smcFunc['db_fetch_assoc']($result))
160
	{
161
		// If the attached topic is not approved then for the moment pretend it doesn't exist
162
		if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
163
			continue;
164
165
		// Force a censor of the title - as often these are used by others.
166
		censorText($row['title'], $use_permissions ? false : true);
167
168
		// Get the various time and date properties for this event
169
		list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
170
171
		if (empty($timezone_array[$tz]))
172
			$timezone_array[$tz] = timezone_open($tz);
173
174
		// Sanity check
175
		if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
176
			continue;
177
178
		// Get set up for the loop
179
		$start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$tz]);
180
		$end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$tz]);
181
		date_timezone_set($start_object, $timezone_array['default']);
182
		date_timezone_set($end_object, $timezone_array['default']);
183
		date_time_set($start_object, 0, 0, 0);
184
		date_time_set($end_object, 0, 0, 0);
185
		$start_date_string = date_format($start_object, 'Y-m-d');
186
		$end_date_string = date_format($end_object, 'Y-m-d');
187
188
		$cal_date = ($start_object >= $low_object) ? $start_object : $low_object;
189
		while ($cal_date <= $end_object && $cal_date <= $high_object)
190
		{
191
			$starts_today = (date_format($cal_date, 'Y-m-d') == $start_date_string);
192
			$ends_today = (date_format($cal_date, 'Y-m-d') == $end_date_string);
193
194
			$eventProperties = array(
195
				'id' => $row['id_event'],
196
				'title' => $row['title'],
197
				'year' => $start['year'],
198
				'month' => $start['month'],
199
				'day' => $start['day'],
200
				'hour' => !$allday ? $start['hour'] : null,
201
				'minute' => !$allday ? $start['minute'] : null,
202
				'second' => !$allday ? $start['second'] : null,
203
				'start_date' => $row['start_date'],
204
				'start_date_local' => $start['date_local'],
205
				'start_date_orig' => $start['date_orig'],
206
				'start_time' => !$allday ? $row['start_time'] : null,
207
				'start_time_local' => !$allday ? $start['time_local'] : null,
208
				'start_time_orig' => !$allday ? $start['time_orig'] : null,
209
				'start_timestamp' => $start['timestamp'],
210
				'start_datetime' => $start['datetime'],
211
				'start_iso_gmdate' => $start['iso_gmdate'],
212
				'end_year' => $end['year'],
213
				'end_month' => $end['month'],
214
				'end_day' => $end['day'],
215
				'end_hour' => !$allday ? $end['hour'] : null,
216
				'end_minute' => !$allday ? $end['minute'] : null,
217
				'end_second' => !$allday ? $end['second'] : null,
218
				'end_date' => $row['end_date'],
219
				'end_date_local' => $end['date_local'],
220
				'end_date_orig' => $end['date_orig'],
221
				'end_time' => !$allday ? $row['end_time'] : null,
222
				'end_time_local' => !$allday ? $end['time_local'] : null,
223
				'end_time_orig' => !$allday ? $end['time_orig'] : null,
224
				'end_timestamp' => $end['timestamp'],
225
				'end_datetime' => $end['datetime'],
226
				'end_iso_gmdate' => $end['iso_gmdate'],
227
				'allday' => $allday,
228
				'tz' => !$allday ? $tz : null,
229
				'tz_abbrev' => !$allday ? $tz_abbrev : null,
230
				'span' => $span,
231
				'is_last' => false,
232
				'id_board' => $row['id_board'],
233
				'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
234
				'starts_today' => $starts_today,
235
				'ends_today' => $ends_today,
236
				'location' => $row['location'],
237
			);
238
239
			// If we're using permissions (calendar pages?) then just ouput normal contextual style information.
240
			if ($use_permissions)
241
				$events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
242
					'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
243
					'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
244
					'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
245
					'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'],
246
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
247
					'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
248
				));
249
			// Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
250
			else
251
				$events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
252
					'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
253
					'link' => $row['id_topic'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
254
					'can_edit' => false,
255
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
256
					'topic' => $row['id_topic'],
257
					'msg' => $row['id_first_msg'],
258
					'poster' => $row['id_member'],
259
					'allowed_groups' => explode(',', $row['member_groups']),
260
				));
261
262
			date_add($cal_date, date_interval_create_from_date_string('1 day'));
263
		}
264
	}
265
	$smcFunc['db_free_result']($result);
266
267
	// If we're doing normal contextual data, go through and make things clear to the templates ;).
268
	if ($use_permissions)
269
	{
270
		foreach ($events as $mday => $array)
271
			$events[$mday][count($array) - 1]['is_last'] = true;
272
	}
273
274
	ksort($events);
275
276
	return $events;
277
}
278
279
/**
280
 * Get all holidays within the given time range.
281
 *
282
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
283
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
284
 * @return array An array of days, which are all arrays of holiday names.
285
 */
286
function getHolidayRange($low_date, $high_date)
287
{
288
	global $smcFunc;
289
290
	// Get the lowest and highest dates for "all years".
291
	if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
292
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
293
			OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
294
	else
295
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
296
297
	// Find some holidays... ;).
298
	$result = $smcFunc['db_query']('', '
299
		SELECT event_date, YEAR(event_date) AS year, title
300
		FROM {db_prefix}calendar_holidays
301
		WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
302
			OR ' . $allyear_part,
303
		array(
304
			'low_date' => $low_date,
305
			'high_date' => $high_date,
306
			'all_year_low' => '1004' . substr($low_date, 4),
307
			'all_year_high' => '1004' . substr($high_date, 4),
308
			'all_year_jan' => '1004-01-01',
309
			'all_year_dec' => '1004-12-31',
310
		)
311
	);
312
	$holidays = array();
313
	while ($row = $smcFunc['db_fetch_assoc']($result))
314
	{
315
		if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
316
			$event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
317
		else
318
			$event_year = substr($low_date, 0, 4);
319
320
		$holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
321
	}
322
	$smcFunc['db_free_result']($result);
323
324
	ksort($holidays);
325
326
	return $holidays;
327
}
328
329
/**
330
 * Does permission checks to see if an event can be linked to a board/topic.
331
 * checks if the current user can link the current topic to the calendar, permissions et al.
332
 * this requires the calendar_post permission, a forum moderator, or a topic starter.
333
 * expects the $topic and $board variables to be set.
334
 * if the user doesn't have proper permissions, an error will be shown.
335
 */
336
function canLinkEvent()
337
{
338
	global $user_info, $topic, $board, $smcFunc;
339
340
	// If you can't post, you can't link.
341
	isAllowedTo('calendar_post');
342
343
	// No board?  No topic?!?
344
	if (empty($board))
345
		fatal_lang_error('missing_board_id', false);
346
	if (empty($topic))
347
		fatal_lang_error('missing_topic_id', false);
348
349
	// Administrator, Moderator, or owner.  Period.
350
	if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
351
	{
352
		// Not admin or a moderator of this board. You better be the owner - or else.
353
		$result = $smcFunc['db_query']('', '
354
			SELECT id_member_started
355
			FROM {db_prefix}topics
356
			WHERE id_topic = {int:current_topic}
357
			LIMIT 1',
358
			array(
359
				'current_topic' => $topic,
360
			)
361
		);
362
		if ($row = $smcFunc['db_fetch_assoc']($result))
363
		{
364
			// Not the owner of the topic.
365
			if ($row['id_member_started'] != $user_info['id'])
366
				fatal_lang_error('not_your_topic', 'user');
367
		}
368
		// Topic/Board doesn't exist.....
369
		else
370
			fatal_lang_error('calendar_no_topic', 'general');
371
		$smcFunc['db_free_result']($result);
372
	}
373
}
374
375
/**
376
 * Returns date information about 'today' relative to the users time offset.
377
 * returns an array with the current date, day, month, and year.
378
 * takes the users time offset into account.
379
 *
380
 * @return array An array of info about today, based on forum time. Has 'day', 'month', 'year' and 'date' (in YYYY-MM-DD format)
381
 */
382
function getTodayInfo()
383
{
384
	return array(
385
		'day' => (int) strftime('%d', forum_time()),
386
		'month' => (int) strftime('%m', forum_time()),
387
		'year' => (int) strftime('%Y', forum_time()),
388
		'date' => strftime('%Y-%m-%d', forum_time()),
389
	);
390
}
391
392
/**
393
 * Provides information (link, month, year) about the previous and next month.
394
 *
395
 * @param string $selected_date A date in YYYY-MM-DD format
396
 * @param array $calendarOptions An array of calendar options
397
 * @param bool $is_previous Whether this is the previous month
398
 * @param bool $has_picker Wheter to add javascript to handle a date picker
399
 * @return array A large array containing all the information needed to show a calendar grid for the given month
400
 */
401
function getCalendarGrid($selected_date, $calendarOptions, $is_previous = false, $has_picker = true)
402
{
403
	global $scripturl, $modSettings;
404
405
	$selected_object = date_create($selected_date);
406
407
	$next_object = date_create($selected_date);
408
	date_add($next_object, date_interval_create_from_date_string('1 month'));
409
410
	$prev_object = date_create($selected_date);
411
	date_sub($prev_object, date_interval_create_from_date_string('1 month'));
412
413
	// Eventually this is what we'll be returning.
414
	$calendarGrid = array(
415
		'week_days' => array(),
416
		'weeks' => array(),
417
		'short_day_titles' => !empty($calendarOptions['short_day_titles']),
418
		'short_month_titles' => !empty($calendarOptions['short_month_titles']),
419
		'current_month' => date_format($selected_object, 'n'),
420
		'current_year' => date_format($selected_object, 'Y'),
421
		'current_day' => date_format($selected_object, 'd'),
422
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
423
		'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
424
		'previous_calendar' => array(
425
			'year' => date_format($prev_object, 'Y'),
426
			'month' => date_format($prev_object, 'n'),
427
			'day' => date_format($prev_object, 'd'),
428
			'start_date' => date_format($prev_object, 'Y-m-d'),
429
			'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
430
		),
431
		'next_calendar' => array(
432
			'year' => date_format($next_object, 'Y'),
433
			'month' => date_format($next_object, 'n'),
434
			'day' => date_format($next_object, 'd'),
435
			'start_date' => date_format($next_object, 'Y-m-d'),
436
			'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
437
		),
438
		'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
0 ignored issues
show
Bug introduced by
date_format($selected_object, 'U') of type string is incompatible with the type integer expected by parameter $log_time 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

438
		'start_date' => timeformat(/** @scrutinizer ignore-type */ date_format($selected_object, 'U'), get_date_or_time_format('date')),
Loading history...
439
	);
440
441
	// Get today's date.
442
	$today = getTodayInfo();
443
444
	$first_day_object = date_create(date_format($selected_object, 'Y-m-01'));
445
	$last_day_object = date_create(date_format($selected_object, 'Y-m-t'));
446
447
	// Get information about this month.
448
	$month_info = array(
449
		'first_day' => array(
450
			'day_of_week' => date_format($first_day_object, 'w'),
451
			'week_num' => date_format($first_day_object, 'W'),
452
			'date' => date_format($first_day_object, 'Y-m-d'),
453
		),
454
		'last_day' => array(
455
			'day_of_month' => date_format($last_day_object, 't'),
456
			'date' => date_format($last_day_object, 'Y-m-d'),
457
		),
458
		'first_day_of_year' => date_format(date_create(date_format($selected_object, 'Y-01-01')), 'w'),
459
		'first_day_of_next_year' => date_format(date_create((date_format($selected_object, 'Y') + 1) . '-01-01'), 'w'),
460
	);
461
462
	// The number of days the first row is shifted to the right for the starting day.
463
	$nShift = $month_info['first_day']['day_of_week'];
464
465
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
466
467
	// Starting any day other than Sunday means a shift...
468
	if (!empty($calendarOptions['start_day']))
469
	{
470
		$nShift -= $calendarOptions['start_day'];
471
		if ($nShift < 0)
472
			$nShift = 7 + $nShift;
473
	}
474
475
	// Number of rows required to fit the month.
476
	$nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
477
	if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
478
		$nRows++;
479
480
	// Fetch the arrays for birthdays, posted events, and holidays.
481
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
482
	$events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
483
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
484
485
	// Days of the week taking into consideration that they may want it to start on any day.
486
	$count = $calendarOptions['start_day'];
487
	for ($i = 0; $i < 7; $i++)
488
	{
489
		$calendarGrid['week_days'][] = $count;
490
		$count++;
491
		if ($count == 7)
492
			$count = 0;
493
	}
494
495
	// Iterate through each week.
496
	$calendarGrid['weeks'] = array();
497
	for ($nRow = 0; $nRow < $nRows; $nRow++)
498
	{
499
		// Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
500
		$calendarGrid['weeks'][$nRow] = array(
501
			'days' => array(),
502
		);
503
504
		// And figure out all the days.
505
		for ($nCol = 0; $nCol < 7; $nCol++)
506
		{
507
			$nDay = ($nRow * 7) + $nCol - $nShift + 1;
508
509
			if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
510
				$nDay = 0;
511
512
			$date = date_format($selected_object, 'Y-m-') . sprintf('%02d', $nDay);
513
514
			$calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
515
				'day' => $nDay,
516
				'date' => $date,
517
				'is_today' => $date == $today['date'],
518
				'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
519
				'is_first_of_month' => $nDay === 1,
520
				'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
521
				'events' => !empty($events[$date]) ? $events[$date] : array(),
522
				'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
523
			);
524
		}
525
	}
526
527
	// What is the last day of the month?
528
	if ($is_previous === true)
529
		$calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];
530
531
	// We'll use the shift in the template.
532
	$calendarGrid['shift'] = $nShift;
533
534
	// Set the previous and the next month's links.
535
	$calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
536
	$calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
537
538
	if ($has_picker)
539
	{
540
		loadDatePicker('#calendar_navigation .date_input');
541
		loadDatePair('#calendar_navigation', 'date_input');
542
	}
543
544
	return $calendarGrid;
545
}
546
547
/**
548
 * Returns the information needed to show a calendar for the given week.
549
 *
550
 * @param string $selected_date A date in YYYY-MM-DD format
551
 * @param array $calendarOptions An array of calendar options
552
 * @return array An array of information needed to display the grid for a single week on the calendar
553
 */
554
function getCalendarWeek($selected_date, $calendarOptions)
555
{
556
	global $scripturl, $modSettings, $txt;
557
558
	$selected_object = date_create($selected_date);
559
560
	// Get today's date.
561
	$today = getTodayInfo();
562
563
	// What is the actual "start date" for the passed day.
564
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
565
	$day_of_week = date_format($selected_object, 'w');
566
	$first_day_object = date_create($selected_date);
567
	if ($day_of_week != $calendarOptions['start_day'])
568
	{
569
		// Here we offset accordingly to get things to the real start of a week.
570
		$date_diff = $day_of_week - $calendarOptions['start_day'];
571
		if ($date_diff < 0)
572
			$date_diff += 7;
573
574
		date_sub($first_day_object, date_interval_create_from_date_string($date_diff . ' days'));
575
	}
576
577
	$last_day_object = date_create(date_format($first_day_object, 'Y-m-d'));
578
	date_add($last_day_object, date_interval_create_from_date_string('1 week'));
579
580
	$month = date_format($first_day_object, 'n');
0 ignored issues
show
Unused Code introduced by
The assignment to $month is dead and can be removed.
Loading history...
581
	$year = date_format($first_day_object, 'Y');
0 ignored issues
show
Unused Code introduced by
The assignment to $year is dead and can be removed.
Loading history...
582
	$day = date_format($first_day_object, 'd');
0 ignored issues
show
Unused Code introduced by
The assignment to $day is dead and can be removed.
Loading history...
583
584
	$next_object = date_create($selected_date);
585
	date_add($next_object, date_interval_create_from_date_string('1 week'));
586
587
	$prev_object = date_create($selected_date);
588
	date_sub($prev_object, date_interval_create_from_date_string('1 week'));
589
590
	// Now start filling in the calendar grid.
591
	$calendarGrid = array(
592
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
593
		'previous_week' => array(
594
			'year' => date_format($prev_object, 'Y'),
595
			'month' => date_format($prev_object, 'n'),
596
			'day' => date_format($prev_object, 'd'),
597
			'start_date' => date_format($prev_object, 'Y-m-d'),
598
			'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
599
		),
600
		'next_week' => array(
601
			'year' => date_format($next_object, 'Y'),
602
			'month' => date_format($next_object, 'n'),
603
			'day' => date_format($next_object, 'd'),
604
			'start_date' => date_format($next_object, 'Y-m-d'),
605
			'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
606
		),
607
		'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
0 ignored issues
show
Bug introduced by
date_format($selected_object, 'U') of type string is incompatible with the type integer expected by parameter $log_time 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

607
		'start_date' => timeformat(/** @scrutinizer ignore-type */ date_format($selected_object, 'U'), get_date_or_time_format('date')),
Loading history...
608
	);
609
610
	// Fetch the arrays for birthdays, posted events, and holidays.
611
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
612
	$events = $calendarOptions['show_events'] ? getEventRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
613
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
614
615
	$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'));
616
617
	// This holds all the main data - there is at least one month!
618
	$calendarGrid['months'] = array();
619
	$current_day_object = date_create(date_format($first_day_object, 'Y-m-d'));
620
	for ($i = 0; $i < 7; $i++)
621
	{
622
		$current_month = date_format($current_day_object, 'n');
623
		$current_day = date_format($current_day_object, 'j');
624
		$current_date = date_format($current_day_object, 'Y-m-d');
625
626
		if (!isset($calendarGrid['months'][$current_month]))
627
			$calendarGrid['months'][$current_month] = array(
628
				'current_month' => $current_month,
629
				'current_year' => date_format($current_day_object, 'Y'),
630
				'days' => array(),
631
			);
632
633
		$calendarGrid['months'][$current_month]['days'][$current_day] = array(
634
			'day' => $current_day,
635
			'day_of_week' => (date_format($current_day_object, 'w') + 7) % 7,
636
			'date' => $current_date,
637
			'is_today' => $current_date == $today['date'],
638
			'holidays' => !empty($holidays[$current_date]) ? $holidays[$current_date] : array(),
639
			'events' => !empty($events[$current_date]) ? $events[$current_date] : array(),
640
			'birthdays' => !empty($bday[$current_date]) ? $bday[$current_date] : array()
641
		);
642
643
		date_add($current_day_object, date_interval_create_from_date_string('1 day'));
644
	}
645
646
	// Set the previous and the next week's links.
647
	$calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
648
	$calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];
649
650
	loadDatePicker('#calendar_navigation .date_input');
651
	loadDatePair('#calendar_navigation', 'date_input', '');
652
653
	return $calendarGrid;
654
}
655
656
/**
657
 * Returns the information needed to show a list of upcoming events, birthdays, and holidays on the calendar.
658
 *
659
 * @param string $start_date The start of a date range in YYYY-MM-DD format
660
 * @param string $end_date The end of a date range in YYYY-MM-DD format
661
 * @param array $calendarOptions An array of calendar options
662
 * @return array An array of information needed to display a list of upcoming events, etc., on the calendar
663
 */
664
function getCalendarList($start_date, $end_date, $calendarOptions)
665
{
666
	global $modSettings, $user_info, $txt, $context, $sourcedir;
667
	require_once($sourcedir . '/Subs.php');
668
669
	// DateTime objects make life easier
670
	$start_object = date_create($start_date);
671
	$end_object = date_create($end_date);
672
673
	$calendarGrid = array(
674
		'start_date' => timeformat(date_format($start_object, 'U'), get_date_or_time_format('date')),
0 ignored issues
show
Bug introduced by
date_format($start_object, 'U') of type string is incompatible with the type integer expected by parameter $log_time 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

674
		'start_date' => timeformat(/** @scrutinizer ignore-type */ date_format($start_object, 'U'), get_date_or_time_format('date')),
Loading history...
675
		'start_year' => date_format($start_object, 'Y'),
676
		'start_month' => date_format($start_object, 'm'),
677
		'start_day' => date_format($start_object, 'd'),
678
		'end_date' => timeformat(date_format($end_object, 'U'), get_date_or_time_format('date')),
679
		'end_year' => date_format($end_object, 'Y'),
680
		'end_month' => date_format($end_object, 'm'),
681
		'end_day' => date_format($end_object, 'd'),
682
	);
683
684
	$calendarGrid['birthdays'] = $calendarOptions['show_birthdays'] ? getBirthdayRange($start_date, $end_date) : array();
685
	$calendarGrid['holidays'] = $calendarOptions['show_holidays'] ? getHolidayRange($start_date, $end_date) : array();
686
	$calendarGrid['events'] = $calendarOptions['show_events'] ? getEventRange($start_date, $end_date) : array();
687
688
	// Get rid of duplicate events
689
	$temp = array();
690
	foreach ($calendarGrid['events'] as $date => $date_events)
691
	{
692
		foreach ($date_events as $event_key => $event_val)
693
		{
694
			if (in_array($event_val['id'], $temp))
695
				unset($calendarGrid['events'][$date][$event_key]);
696
			else
697
				$temp[] = $event_val['id'];
698
		}
699
	}
700
701
	// Give birthdays and holidays a friendly format, without the year
702
	$date_format = str_replace(array('%Y', '%y', '%G', '%g', '%C', '%c', '%D'), array('', '', '', '', '', '%b %d', '%m/%d'), get_date_or_time_format('date'));
703
704
	foreach (array('birthdays', 'holidays') as $type)
705
	{
706
		foreach ($calendarGrid[$type] as $date => $date_content)
0 ignored issues
show
Bug introduced by
The expression $calendarGrid[$type] of type string is not traversable.
Loading history...
707
		{
708
			// Make sure to apply no offsets
709
			$date_local = preg_replace('~(?<=\s)0+(\d)~', '$1', trim(timeformat(strtotime($date), $date_format, true), " \t\n\r\0\x0B,./;:<>()[]{}\\|-_=+"));
710
711
			$calendarGrid[$type][$date]['date_local'] = $date_local;
712
		}
713
	}
714
715
	loadDatePicker('#calendar_range .date_input');
716
	loadDatePair('#calendar_range', 'date_input', '');
717
718
	return $calendarGrid;
719
}
720
721
/**
722
 * Loads the necessary JavaScript and CSS to create a datepicker.
723
 *
724
 * @param string $selector A CSS selector for the input field(s) that the datepicker should be attached to.
725
 * @param string $date_format The date format to use, in strftime() format.
726
 */
727
function loadDatePicker($selector = 'input.date_input', $date_format = '')
728
{
729
	global $modSettings, $txt, $context, $user_info, $options;
730
731
	if (empty($date_format))
732
		$date_format = get_date_or_time_format('date');
733
734
	// Convert to format used by datepicker
735
	$date_format = strtr($date_format, array(
736
		// Day
737
		'%a' => 'D', '%A' => 'DD', '%e' => 'd', '%d' => 'dd', '%j' => 'oo', '%u' => '', '%w' => '',
738
		// Week
739
		'%U' => '', '%V' => '', '%W' => '',
740
		// Month
741
		'%b' => 'M', '%B' => 'MM', '%h' => 'M', '%m' => 'mm',
742
		// Year
743
		'%C' => '', '%g' => 'y', '%G' => 'yy', '%y' => 'y', '%Y' => 'yy',
744
		// Time (we remove all of these)
745
		'%H' => '', '%k' => '', '%I' => '', '%l' => '', '%M' => '', '%p' => '', '%P' => '',
746
		'%r' => '', '%R' => '', '%S' => '', '%T' => '', '%X' => '', '%z' => '', '%Z' => '',
747
		// Time and Date Stamps
748
		'%c' => 'D, d M yy', '%D' => 'mm/dd/y', '%F' => 'yy-mm-dd', '%s' => '@', '%x' => 'D, d M yy',
749
		// Miscellaneous
750
		'%n' => ' ', '%t' => ' ', '%%' => '%',
751
	));
752
753
	loadCSSFile('jquery-ui.datepicker.css', array(), 'smf_datepicker');
754
	loadJavaScriptFile('jquery-ui.datepicker.min.js', array('defer' => true), 'smf_datepicker');
755
	addInlineJavaScript('
756
	$("' . $selector . '").datepicker({
757
		dateFormat: "' . $date_format . '",
758
		autoSize: true,
759
		isRTL: ' . ($context['right_to_left'] ? 'true' : 'false') . ',
760
		constrainInput: true,
761
		showAnim: "",
762
		showButtonPanel: false,
763
		yearRange: "' . $modSettings['cal_minyear'] . ':' . $modSettings['cal_maxyear'] . '",
764
		hideIfNoPrevNext: true,
765
		monthNames: ["' . implode('", "', $txt['months_titles']) . '"],
766
		monthNamesShort: ["' . implode('", "', $txt['months_short']) . '"],
767
		dayNames: ["' . implode('", "', $txt['days']) . '"],
768
		dayNamesShort: ["' . implode('", "', $txt['days_short']) . '"],
769
		dayNamesMin: ["' . implode('", "', $txt['days_short']) . '"],
770
		prevText: "' . $txt['prev_month'] . '",
771
		nextText: "' . $txt['next_month'] . '",
772
		firstDay: ' . (!empty($options['calendar_start_day']) ? $options['calendar_start_day'] : 0) . ',
773
	});', true);
774
}
775
776
/**
777
 * Loads the necessary JavaScript and CSS to create a timepicker.
778
 *
779
 * @param string $selector A CSS selector for the input field(s) that the timepicker should be attached to.
780
 * @param string $time_format A time format in strftime format
781
 */
782
function loadTimePicker($selector = 'input.time_input', $time_format = '')
783
{
784
	global $modSettings, $txt, $context;
785
786
	if (empty($time_format))
787
		$time_format = get_date_or_time_format('time');
788
789
	// Format used for timepicker
790
	$time_format = strtr($time_format, array(
791
		'%H' => 'H',
792
		'%k' => 'G',
793
		'%I' => 'h',
794
		'%l' => 'g',
795
		'%M' => 'i',
796
		'%p' => 'A',
797
		'%P' => 'a',
798
		'%r' => 'h:i:s A',
799
		'%R' => 'H:i',
800
		'%S' => 's',
801
		'%T' => 'H:i:s',
802
		'%X' => 'H:i:s',
803
	));
804
805
	loadCSSFile('jquery.timepicker.css', array(), 'smf_timepicker');
806
	loadJavaScriptFile('jquery.timepicker.min.js', array('defer' => true), 'smf_timepicker');
807
	addInlineJavaScript('
808
	$("' . $selector . '").timepicker({
809
		timeFormat: "' . $time_format . '",
810
		showDuration: true,
811
		maxTime: "23:59:59",
812
		lang: {
813
			am: "' . strtolower($txt['time_am']) . '",
814
			pm: "' . strtolower($txt['time_pm']) . '",
815
			AM: "' . strtoupper($txt['time_am']) . '",
816
			PM: "' . strtoupper($txt['time_pm']) . '",
817
			decimal: "' . $txt['decimal_sign'] . '",
818
			mins: "' . $txt['minutes_short'] . '",
819
			hr: "' . $txt['hour_short'] . '",
820
		}
821
	});', true);
822
}
823
824
/**
825
 * Loads the necessary JavaScript for Datepair.js.
826
 *
827
 * Datepair.js helps to keep date ranges sane in the UI.
828
 *
829
 * @param string $container CSS selector for the containing element of the date/time inputs to be paired.
830
 * @param string $date_class The CSS class of the date inputs to be paired.
831
 * @param string $time_class The CSS class of the time inputs to be paired.
832
 */
833
function loadDatePair($container, $date_class = '', $time_class = '')
834
{
835
	global $modSettings, $txt, $context;
836
837
	$container = (string) $container;
838
	$date_class = (string) $date_class;
839
	$time_class = (string) $time_class;
840
841
	if ($container == '')
842
		return;
843
844
	loadJavaScriptFile('jquery.datepair.min.js', array('defer' => true), 'smf_datepair');
845
846
	$datepair_options = '';
847
848
	// If we're not using a date input, we might as well disable these.
849
	if ($date_class == '')
850
	{
851
		$datepair_options .= '
852
		parseDate: function (el) {},
853
		updateDate: function (el, v) {},';
854
	}
855
	else
856
	{
857
		$datepair_options .= '
858
		dateClass: "' . $date_class . '",';
859
860
		// Customize Datepair to work with jQuery UI's datepicker.
861
		$datepair_options .= '
862
		parseDate: function (el) {
863
			var val = $(el).datepicker("getDate");
864
			if (!val) {
865
				return null;
866
			}
867
			var utc = new Date(val);
868
			return utc && new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
869
		},
870
		updateDate: function (el, v) {
871
			$(el).datepicker("setDate", new Date(v.getTime() - (v.getTimezoneOffset() * 60000)));
872
		},';
873
	}
874
875
	// If not using a time input, disable time functions.
876
	if ($time_class == '')
877
	{
878
		$datepair_options .= '
879
		parseTime: function(input){},
880
		updateTime: function(input, dateObj){},
881
		setMinTime: function(input, dateObj){},';
882
	}
883
	else
884
	{
885
		$datepair_options .= '
886
		timeClass: "' . $time_class . '",';
887
	}
888
889
	addInlineJavaScript('
890
	$("' . $container . '").datepair({' . $datepair_options . "\n\t});", true);
891
892
}
893
894
/**
895
 * Retrieve all events for the given days, independently of the users offset.
896
 * cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
897
 * widens the search range by an extra 24 hours to support time offset shifts.
898
 * used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
899
 *
900
 * @param array $eventOptions With the keys 'num_days_shown', 'include_holidays', 'include_birthdays' and 'include_events'
901
 * @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
902
 */
903
function cache_getOffsetIndependentEvents($eventOptions)
904
{
905
	$days_to_index = $eventOptions['num_days_shown'];
906
907
	$low_date = strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
908
	$high_date = strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);
909
910
	return array(
911
		'data' => array(
912
			'holidays' => (!empty($eventOptions['include_holidays']) ? getHolidayRange($low_date, $high_date) : array()),
913
			'birthdays' => (!empty($eventOptions['include_birthdays']) ? getBirthdayRange($low_date, $high_date) : array()),
914
			'events' => (!empty($eventOptions['include_events']) ? getEventRange($low_date, $high_date, false) : array()),
915
		),
916
		'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
917
		'expires' => time() + 3600,
918
	);
919
}
920
921
/**
922
 * cache callback function used to retrieve the upcoming birthdays, holidays, and events within the given period, taking into account the users time offset.
923
 * Called from the BoardIndex to display the current day's events on the board index
924
 * used by the board index and SSI to show the upcoming events.
925
 *
926
 * @param array $eventOptions An array of event options.
927
 * @return array An array containing the info that was cached as well as a few other relevant things
928
 */
929
function cache_getRecentEvents($eventOptions)
930
{
931
	// With the 'static' cached data we can calculate the user-specific data.
932
	$cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions));
933
934
	// Get the information about today (from user perspective).
935
	$today = getTodayInfo();
936
937
	$return_data = array(
938
		'calendar_holidays' => array(),
939
		'calendar_birthdays' => array(),
940
		'calendar_events' => array(),
941
	);
942
943
	// Set the event span to be shown in seconds.
944
	$days_for_index = $eventOptions['num_days_shown'] * 86400;
945
946
	// Get the current member time/date.
947
	$now = forum_time();
948
949
	if (!empty($eventOptions['include_holidays']))
950
	{
951
		// Holidays between now and now + days.
952
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
953
		{
954
			if (isset($cached_data['holidays'][strftime('%Y-%m-%d', $i)]))
955
				$return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][strftime('%Y-%m-%d', $i)]);
956
		}
957
	}
958
959
	if (!empty($eventOptions['include_birthdays']))
960
	{
961
		// Happy Birthday, guys and gals!
962
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
963
		{
964
			$loop_date = strftime('%Y-%m-%d', $i);
965
			if (isset($cached_data['birthdays'][$loop_date]))
966
			{
967
				foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
968
					$cached_data['birthdays'][strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
969
				$return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
970
			}
971
		}
972
	}
973
974
	if (!empty($eventOptions['include_events']))
975
	{
976
		$duplicates = array();
977
		for ($i = $now; $i < $now + $days_for_index; $i += 86400)
978
		{
979
			// Determine the date of the current loop step.
980
			$loop_date = strftime('%Y-%m-%d', $i);
981
982
			// No events today? Check the next day.
983
			if (empty($cached_data['events'][$loop_date]))
984
				continue;
985
986
			// Loop through all events to add a few last-minute values.
987
			foreach ($cached_data['events'][$loop_date] as $ev => $event)
988
			{
989
				// Create a shortcut variable for easier access.
990
				$this_event = &$cached_data['events'][$loop_date][$ev];
991
992
				// Skip duplicates.
993
				if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
994
				{
995
					unset($cached_data['events'][$loop_date][$ev]);
996
					continue;
997
				}
998
				else
999
					$duplicates[$this_event['topic'] . $this_event['title']] = true;
1000
1001
				// Might be set to true afterwards, depending on the permissions.
1002
				$this_event['can_edit'] = false;
1003
				$this_event['is_today'] = $loop_date === $today['date'];
1004
				$this_event['date'] = $loop_date;
1005
			}
1006
1007
			if (!empty($cached_data['events'][$loop_date]))
1008
				$return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
1009
		}
1010
	}
1011
1012
	// Mark the last item so that a list separator can be used in the template.
1013
	for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
1014
		$return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
1015
	for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
1016
		$return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
1017
1018
	return array(
1019
		'data' => $return_data,
1020
		'expires' => time() + 3600,
1021
		'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
1022
		'post_retri_eval' => '
1023
			global $context, $scripturl, $user_info;
1024
1025
			foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
1026
			{
1027
				// Remove events that the user may not see or wants to ignore.
1028
				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\']))
1029
					unset($cache_block[\'data\'][\'calendar_events\'][$k]);
1030
				else
1031
				{
1032
					// Whether the event can be edited depends on the permissions.
1033
					$cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));
1034
1035
					// The added session code makes this URL not cachable.
1036
					$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\'];
1037
				}
1038
			}
1039
1040
			if (empty($params[0][\'include_holidays\']))
1041
				$cache_block[\'data\'][\'calendar_holidays\'] = array();
1042
			if (empty($params[0][\'include_birthdays\']))
1043
				$cache_block[\'data\'][\'calendar_birthdays\'] = array();
1044
			if (empty($params[0][\'include_events\']))
1045
				$cache_block[\'data\'][\'calendar_events\'] = array();
1046
1047
			$cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
1048
	);
1049
}
1050
1051
/**
1052
 * Makes sure the calendar post is valid.
1053
 */
1054
function validateEventPost()
1055
{
1056
	global $modSettings, $smcFunc;
1057
1058
	if (!isset($_POST['deleteevent']))
1059
	{
1060
		// The 2.1 way
1061
		if (isset($_POST['start_date']))
1062
		{
1063
			$d = date_parse(convertDateToEnglish($_POST['start_date']));
1064
			if (!empty($d['error_count']) || !empty($d['warning_count']))
1065
				fatal_lang_error('invalid_date', false);
1066
			if (empty($d['year']))
1067
				fatal_lang_error('event_year_missing', false);
1068
			if (empty($d['month']))
1069
				fatal_lang_error('event_month_missing', false);
1070
		}
1071
		elseif (isset($_POST['start_datetime']))
1072
		{
1073
			$d = date_parse(convertDateToEnglish($_POST['start_datetime']));
1074
			if (!empty($d['error_count']) || !empty($d['warning_count']))
1075
				fatal_lang_error('invalid_date', false);
1076
			if (empty($d['year']))
1077
				fatal_lang_error('event_year_missing', false);
1078
			if (empty($d['month']))
1079
				fatal_lang_error('event_month_missing', false);
1080
		}
1081
		// The 2.0 way
1082
		else
1083
		{
1084
			// No month?  No year?
1085
			if (!isset($_POST['month']))
1086
				fatal_lang_error('event_month_missing', false);
1087
			if (!isset($_POST['year']))
1088
				fatal_lang_error('event_year_missing', false);
1089
1090
			// Check the month and year...
1091
			if ($_POST['month'] < 1 || $_POST['month'] > 12)
1092
				fatal_lang_error('invalid_month', false);
1093
			if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
1094
				fatal_lang_error('invalid_year', false);
1095
		}
1096
	}
1097
1098
	// Make sure they're allowed to post...
1099
	isAllowedTo('calendar_post');
1100
1101
	// If they want to us to calculate an end date, make sure it will fit in an acceptable range.
1102
	if (isset($_POST['span']))
1103
	{
1104
		if (($_POST['span'] < 1) || (!empty($modSettings['cal_maxspan']) && $_POST['span'] > $modSettings['cal_maxspan']))
1105
			fatal_lang_error('invalid_days_numb', false);
1106
	}
1107
1108
	// There is no need to validate the following values if we are just deleting the event.
1109
	if (!isset($_POST['deleteevent']))
1110
	{
1111
		// If we're doing things the 2.0 way, check the day
1112
		if (empty($_POST['start_date']) && empty($_POST['start_datetime']))
1113
		{
1114
			// No day?
1115
			if (!isset($_POST['day']))
1116
				fatal_lang_error('event_day_missing', false);
1117
1118
			// Bad day?
1119
			if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
1120
				fatal_lang_error('invalid_date', false);
1121
		}
1122
1123
		if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
1124
			fatal_lang_error('event_title_missing', false);
1125
		elseif (!isset($_POST['evtitle']))
1126
			$_POST['evtitle'] = $_POST['subject'];
1127
1128
		// No title?
1129
		if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
1130
			fatal_lang_error('no_event_title', false);
1131
		if ($smcFunc['strlen']($_POST['evtitle']) > 100)
1132
			$_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 100);
1133
		$_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
1134
	}
1135
}
1136
1137
/**
1138
 * Get the event's poster.
1139
 *
1140
 * @param int $event_id The ID of the event
1141
 * @return int|bool The ID of the poster or false if the event was not found
1142
 */
1143
function getEventPoster($event_id)
1144
{
1145
	global $smcFunc;
1146
1147
	// A simple database query, how hard can that be?
1148
	$request = $smcFunc['db_query']('', '
1149
		SELECT id_member
1150
		FROM {db_prefix}calendar
1151
		WHERE id_event = {int:id_event}
1152
		LIMIT 1',
1153
		array(
1154
			'id_event' => $event_id,
1155
		)
1156
	);
1157
1158
	// No results, return false.
1159
	if ($smcFunc['db_num_rows'] === 0)
1160
		return false;
1161
1162
	// Grab the results and return.
1163
	list ($poster) = $smcFunc['db_fetch_row']($request);
1164
	$smcFunc['db_free_result']($request);
1165
	return (int) $poster;
1166
}
1167
1168
/**
1169
 * Consolidating the various INSERT statements into this function.
1170
 * Inserts the passed event information into the calendar table.
1171
 * Allows to either set a time span (in days) or an end_date.
1172
 * Does not check any permissions of any sort.
1173
 *
1174
 * @param array $eventOptions An array of event options ('title', 'span', 'start_date', 'end_date', etc.)
1175
 */
1176
function insertEvent(&$eventOptions)
1177
{
1178
	global $smcFunc, $context;
1179
1180
	// Add special chars to the title.
1181
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
1182
1183
	$eventOptions['location'] = isset($eventOptions['location']) ? $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES) : '';
1184
1185
	// Set the start and end dates and times
1186
	list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);
1187
1188
	// If no topic and board are given, they are not linked to a topic.
1189
	$eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
1190
	$eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;
1191
1192
	$event_columns = array(
1193
		'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
1194
		'start_date' => 'date', 'end_date' => 'date', 'location' => 'string-255',
1195
	);
1196
	$event_parameters = array(
1197
		$eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
1198
		$start_date, $end_date, $eventOptions['location'],
1199
	);
1200
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
0 ignored issues
show
Bug introduced by
timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

1200
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, /** @scrutinizer ignore-type */ timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
Loading history...
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1201
	{
1202
		$event_columns['start_time'] = 'time';
1203
		$event_parameters[] = $start_time;
1204
		$event_columns['end_time'] = 'time';
1205
		$event_parameters[] = $end_time;
1206
		$event_columns['timezone'] = 'string';
1207
		$event_parameters[] = $tz;
1208
	}
1209
1210
	call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));
1211
1212
	// Insert the event!
1213
	$eventOptions['id'] = $smcFunc['db_insert']('',
1214
		'{db_prefix}calendar',
1215
		$event_columns,
1216
		$event_parameters,
1217
		array('id_event'),
1218
		1
1219
	);
1220
1221
	// If this isn't tied to a topic, we need to notify people about it.
1222
	if (empty($eventOptions['topic']))
1223
	{
1224
		$smcFunc['db_insert']('insert',
1225
			'{db_prefix}background_tasks',
1226
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
1227
			array('$sourcedir/tasks/EventNew-Notify.php', 'EventNew_Notify_Background', $smcFunc['json_encode'](array(
1228
				'event_title' => $eventOptions['title'],
1229
				'event_id' => $eventOptions['id'],
1230
				'sender_id' => $eventOptions['member'],
1231
				'sender_name' => $eventOptions['member'] == $context['user']['id'] ? $context['user']['name'] : '',
1232
				'time' => time(),
1233
			)), 0),
1234
			array('id_task')
1235
		);
1236
	}
1237
1238
	// Update the settings to show something calendar-ish was updated.
1239
	updateSettings(array(
1240
		'calendar_updated' => time(),
1241
	));
1242
}
1243
1244
/**
1245
 * modifies an event.
1246
 * allows to either set a time span (in days) or an end_date.
1247
 * does not check any permissions of any sort.
1248
 *
1249
 * @param int $event_id The ID of the event
1250
 * @param array $eventOptions An array of event information
1251
 */
1252
function modifyEvent($event_id, &$eventOptions)
1253
{
1254
	global $smcFunc;
1255
1256
	// Properly sanitize the title and location
1257
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
1258
	$eventOptions['location'] = $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES);
1259
1260
	// Set the new start and end dates and times
1261
	list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);
1262
1263
	$event_columns = array(
1264
		'start_date' => '{date:start_date}',
1265
		'end_date' => '{date:end_date}',
1266
		'title' => 'SUBSTRING({string:title}, 1, 60)',
1267
		'id_board' => '{int:id_board}',
1268
		'id_topic' => '{int:id_topic}',
1269
		'location' => 'SUBSTRING({string:location}, 1, 255)',
1270
	);
1271
	$event_parameters = array(
1272
		'start_date' => $start_date,
1273
		'end_date' => $end_date,
1274
		'title' => $eventOptions['title'],
1275
		'location' => $eventOptions['location'],
1276
		'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
1277
		'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
1278
	);
1279
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
0 ignored issues
show
Bug introduced by
timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

1279
	if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, /** @scrutinizer ignore-type */ timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
Loading history...
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1280
	{
1281
		$event_columns['start_time'] = '{time:start_time}';
1282
		$event_parameters['start_time'] = $start_time;
1283
		$event_columns['end_time'] = '{time:end_time}';
1284
		$event_parameters['end_time'] = $end_time;
1285
		$event_columns['timezone'] = '{string:timezone}';
1286
		$event_parameters['timezone'] = $tz;
1287
	}
1288
1289
	// This is to prevent hooks to modify the id of the event
1290
	$real_event_id = $event_id;
1291
	call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns, &$event_parameters));
1292
1293
	$column_clauses = array();
1294
	foreach ($event_columns as $col => $crit)
1295
		$column_clauses[] = $col . ' = ' . $crit;
1296
1297
	$smcFunc['db_query']('', '
1298
		UPDATE {db_prefix}calendar
1299
		SET
1300
			' . implode(', ', $column_clauses) . '
1301
		WHERE id_event = {int:id_event}',
1302
		array_merge(
1303
			$event_parameters,
1304
			array(
1305
				'id_event' => $real_event_id
1306
			)
1307
		)
1308
	);
1309
1310
	if (empty($start_time) || empty($end_time) || empty($tz) || !in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
0 ignored issues
show
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1311
	{
1312
		$smcFunc['db_query']('', '
1313
			UPDATE {db_prefix}calendar
1314
			SET start_time = NULL, end_time = NULL, timezone = NULL
1315
			WHERE id_event = {int:id_event}',
1316
			array(
1317
				'id_event' => $real_event_id
1318
			)
1319
		);
1320
	}
1321
1322
	updateSettings(array(
1323
		'calendar_updated' => time(),
1324
	));
1325
}
1326
1327
/**
1328
 * Remove an event
1329
 * removes an event.
1330
 * does no permission checks.
1331
 *
1332
 * @param int $event_id The ID of the event to remove
1333
 */
1334
function removeEvent($event_id)
1335
{
1336
	global $smcFunc;
1337
1338
	$smcFunc['db_query']('', '
1339
		DELETE FROM {db_prefix}calendar
1340
		WHERE id_event = {int:id_event}',
1341
		array(
1342
			'id_event' => $event_id,
1343
		)
1344
	);
1345
1346
	call_integration_hook('integrate_remove_event', array($event_id));
1347
1348
	updateSettings(array(
1349
		'calendar_updated' => time(),
1350
	));
1351
}
1352
1353
/**
1354
 * Gets all the events properties
1355
 *
1356
 * @param int $event_id The ID of the event
1357
 * @return array An array of event information
1358
 */
1359
function getEventProperties($event_id)
1360
{
1361
	global $smcFunc;
1362
1363
	$request = $smcFunc['db_query']('', '
1364
		SELECT
1365
			c.id_event, c.id_board, c.id_topic, c.id_member, c.title,
1366
			c.start_date, c.end_date, c.start_time, c.end_time, c.timezone, c.location,
1367
			t.id_first_msg, t.id_member_started,
1368
			mb.real_name, m.modified_time
1369
		FROM {db_prefix}calendar AS c
1370
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
1371
			LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
1372
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg  = t.id_first_msg)
1373
		WHERE c.id_event = {int:id_event}',
1374
		array(
1375
			'id_event' => $event_id,
1376
		)
1377
	);
1378
1379
	// If nothing returned, we are in poo, poo.
1380
	if ($smcFunc['db_num_rows']($request) === 0)
1381
		return false;
1382
1383
	$row = $smcFunc['db_fetch_assoc']($request);
1384
	$smcFunc['db_free_result']($request);
1385
1386
	list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
1387
1388
	// Sanity check
1389
	if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
1390
		return false;
1391
1392
	$return_value = array(
1393
		'boards' => array(),
1394
		'board' => $row['id_board'],
1395
		'new' => 0,
1396
		'eventid' => $event_id,
1397
		'year' => $start['year'],
1398
		'month' => $start['month'],
1399
		'day' => $start['day'],
1400
		'hour' => !$allday ? $start['hour'] : null,
1401
		'minute' => !$allday ? $start['minute'] : null,
1402
		'second' => !$allday ? $start['second'] : null,
1403
		'start_date' => $row['start_date'],
1404
		'start_date_local' => $start['date_local'],
1405
		'start_date_orig' => $start['date_orig'],
1406
		'start_time' => !$allday ? $row['start_time'] : null,
1407
		'start_time_local' => !$allday ? $start['time_local'] : null,
1408
		'start_time_orig' => !$allday ? $start['time_orig'] : null,
1409
		'start_timestamp' => $start['timestamp'],
1410
		'start_datetime' => $start['datetime'],
1411
		'start_iso_gmdate' => $start['iso_gmdate'],
1412
		'end_year' => $end['year'],
1413
		'end_month' => $end['month'],
1414
		'end_day' => $end['day'],
1415
		'end_hour' => !$allday ? $end['hour'] : null,
1416
		'end_minute' => !$allday ? $end['minute'] : null,
1417
		'end_second' => !$allday ? $end['second'] : null,
1418
		'end_date' => $row['end_date'],
1419
		'end_date_local' => $end['date_local'],
1420
		'end_date_orig' => $end['date_orig'],
1421
		'end_time' => !$allday ? $row['end_time'] : null,
1422
		'end_time_local' => !$allday ? $end['time_local'] : null,
1423
		'end_time_orig' => !$allday ? $end['time_orig'] : null,
1424
		'end_timestamp' => $end['timestamp'],
1425
		'end_datetime' => $end['datetime'],
1426
		'end_iso_gmdate' => $end['iso_gmdate'],
1427
		'allday' => $allday,
1428
		'tz' => !$allday ? $tz : null,
1429
		'tz_abbrev' => !$allday ? $tz_abbrev : null,
1430
		'span' => $span,
1431
		'title' => $row['title'],
1432
		'location' => $row['location'],
1433
		'member' => $row['id_member'],
1434
		'realname' => $row['real_name'],
1435
		'sequence' => $row['modified_time'],
1436
		'topic' => array(
1437
			'id' => $row['id_topic'],
1438
			'member_started' => $row['id_member_started'],
1439
			'first_msg' => $row['id_first_msg'],
1440
		),
1441
	);
1442
1443
	$return_value['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $return_value['month'] == 12 ? 1 : $return_value['month'] + 1, 0, $return_value['month'] == 12 ? $return_value['year'] + 1 : $return_value['year']));
1444
1445
	return $return_value;
1446
}
1447
1448
/**
1449
 * Gets an initial set of date and time values for creating a new event.
1450
 *
1451
 * @return array An array containing an initial set of date and time values for an event.
1452
 */
1453
function getNewEventDatetimes()
1454
{
1455
	// Ensure setEventStartEnd() has something to work with
1456
	$now = date_create();
1457
	$tz = getUserTimezone();
1458
	date_timezone_set($now, timezone_open($tz));
1459
1460
	$_POST['year'] = !empty($_POST['year']) ? $_POST['year'] : date_format($now, 'Y');
1461
	$_POST['month'] = !empty($_POST['month']) ? $_POST['month'] : date_format($now, 'm');
1462
	$_POST['day'] = !empty($_POST['day']) ? $_POST['day'] : date_format($now, 'd');
1463
	$_POST['hour'] = !empty($_POST['hour']) ? $_POST['hour'] : date_format($now, 'H');
1464
	$_POST['minute'] = !empty($_POST['minute']) ? $_POST['minute'] : date_format($now, 'i');
1465
	$_POST['second'] = !empty($_POST['second']) ? $_POST['second'] : date_format($now, 's');
1466
1467
	// Set the basic values for the new event
1468
	$row_keys = array('start_date', 'end_date', 'start_time', 'end_time', 'timezone');
1469
	$row = array_combine($row_keys, setEventStartEnd());
1470
1471
	// And now set the full suite of values
1472
	list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
1473
1474
	// Default theme only uses some of this info, but others might want it all
1475
	$eventProperties = array(
1476
		'year' => $start['year'],
1477
		'month' => $start['month'],
1478
		'day' => $start['day'],
1479
		'hour' => !$allday ? $start['hour'] : null,
1480
		'minute' => !$allday ? $start['minute'] : null,
1481
		'second' => !$allday ? $start['second'] : null,
1482
		'start_date' => $row['start_date'],
1483
		'start_date_local' => $start['date_local'],
1484
		'start_date_orig' => $start['date_orig'],
1485
		'start_time' => !$allday ? $row['start_time'] : null,
1486
		'start_time_local' => !$allday ? $start['time_local'] : null,
1487
		'start_time_orig' => !$allday ? $start['time_orig'] : null,
1488
		'start_timestamp' => $start['timestamp'],
1489
		'start_datetime' => $start['datetime'],
1490
		'start_iso_gmdate' => $start['iso_gmdate'],
1491
		'end_year' => $end['year'],
1492
		'end_month' => $end['month'],
1493
		'end_day' => $end['day'],
1494
		'end_hour' => !$allday ? $end['hour'] : null,
1495
		'end_minute' => !$allday ? $end['minute'] : null,
1496
		'end_second' => !$allday ? $end['second'] : null,
1497
		'end_date' => $row['end_date'],
1498
		'end_date_local' => $end['date_local'],
1499
		'end_date_orig' => $end['date_orig'],
1500
		'end_time' => !$allday ? $row['end_time'] : null,
1501
		'end_time_local' => !$allday ? $end['time_local'] : null,
1502
		'end_time_orig' => !$allday ? $end['time_orig'] : null,
1503
		'end_timestamp' => $end['timestamp'],
1504
		'end_datetime' => $end['datetime'],
1505
		'end_iso_gmdate' => $end['iso_gmdate'],
1506
		'allday' => $allday,
1507
		'tz' => !$allday ? $tz : null,
1508
		'tz_abbrev' => !$allday ? $tz_abbrev : null,
1509
		'span' => $span,
1510
	);
1511
1512
	return $eventProperties;
1513
}
1514
1515
/**
1516
 * Set the start and end dates and times for a posted event for insertion into the database.
1517
 * Validates all date and times given to it.
1518
 * Makes sure events do not exceed the maximum allowed duration (if any).
1519
 * If passed an array that defines any time or date parameters, they will be used. Otherwise, gets the values from $_POST.
1520
 *
1521
 * @param array $eventOptions An array of optional time and date parameters (span, start_year, end_month, etc., etc.)
1522
 * @return array An array containing $start_date, $end_date, $start_time, $end_time
1523
 */
1524
function setEventStartEnd($eventOptions = array())
1525
{
1526
	global $modSettings;
1527
1528
	// Set $span, in case we need it
1529
	$span = isset($eventOptions['span']) ? $eventOptions['span'] : (isset($_POST['span']) ? $_POST['span'] : 0);
1530
	if ($span > 0)
1531
		$span = !empty($modSettings['cal_maxspan']) ? min($modSettings['cal_maxspan'], $span - 1) : $span - 1;
1532
1533
	// Define the timezone for this event, falling back to the default if not provided
1534
	if (!empty($eventOptions['tz']) && in_array($eventOptions['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
0 ignored issues
show
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

1534
	if (!empty($eventOptions['tz']) && in_array($eventOptions['tz'], /** @scrutinizer ignore-type */ timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
Loading history...
1535
		$tz = $eventOptions['tz'];
1536
	elseif (!empty($_POST['tz']) && in_array($_POST['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
0 ignored issues
show
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1537
		$tz = $_POST['tz'];
1538
	else
1539
		$tz = getUserTimezone();
1540
1541
	// Is this supposed to be an all day event, or should it have specific start and end times?
1542
	if (isset($eventOptions['allday']))
1543
		$allday = $eventOptions['allday'];
1544
	elseif (empty($_POST['allday']))
1545
		$allday = false;
1546
	else
1547
		$allday = true;
1548
1549
	// Input might come as individual parameters...
1550
	$start_year = isset($eventOptions['year']) ? $eventOptions['year'] : (isset($_POST['year']) ? $_POST['year'] : null);
1551
	$start_month = isset($eventOptions['month']) ? $eventOptions['month'] : (isset($_POST['month']) ? $_POST['month'] : null);
1552
	$start_day = isset($eventOptions['day']) ? $eventOptions['day'] : (isset($_POST['day']) ? $_POST['day'] : null);
1553
	$start_hour = isset($eventOptions['hour']) ? $eventOptions['hour'] : (isset($_POST['hour']) ? $_POST['hour'] : null);
1554
	$start_minute = isset($eventOptions['minute']) ? $eventOptions['minute'] : (isset($_POST['minute']) ? $_POST['minute'] : null);
1555
	$start_second = isset($eventOptions['second']) ? $eventOptions['second'] : (isset($_POST['second']) ? $_POST['second'] : null);
1556
	$end_year = isset($eventOptions['end_year']) ? $eventOptions['end_year'] : (isset($_POST['end_year']) ? $_POST['end_year'] : null);
1557
	$end_month = isset($eventOptions['end_month']) ? $eventOptions['end_month'] : (isset($_POST['end_month']) ? $_POST['end_month'] : null);
1558
	$end_day = isset($eventOptions['end_day']) ? $eventOptions['end_day'] : (isset($_POST['end_day']) ? $_POST['end_day'] : null);
1559
	$end_hour = isset($eventOptions['end_hour']) ? $eventOptions['end_hour'] : (isset($_POST['end_hour']) ? $_POST['end_hour'] : null);
1560
	$end_minute = isset($eventOptions['end_minute']) ? $eventOptions['end_minute'] : (isset($_POST['end_minute']) ? $_POST['end_minute'] : null);
1561
	$end_second = isset($eventOptions['end_second']) ? $eventOptions['end_second'] : (isset($_POST['end_second']) ? $_POST['end_second'] : null);
1562
1563
	// ... or as datetime strings ...
1564
	$start_string = isset($eventOptions['start_datetime']) ? $eventOptions['start_datetime'] : (isset($_POST['start_datetime']) ? $_POST['start_datetime'] : null);
1565
	$end_string = isset($eventOptions['end_datetime']) ? $eventOptions['end_datetime'] : (isset($_POST['end_datetime']) ? $_POST['end_datetime'] : null);
1566
1567
	// ... or as date strings and time strings.
1568
	$start_date_string = isset($eventOptions['start_date']) ? $eventOptions['start_date'] : (isset($_POST['start_date']) ? $_POST['start_date'] : null);
1569
	$start_time_string = isset($eventOptions['start_time']) ? $eventOptions['start_time'] : (isset($_POST['start_time']) ? $_POST['start_time'] : null);
1570
	$end_date_string = isset($eventOptions['end_date']) ? $eventOptions['end_date'] : (isset($_POST['end_date']) ? $_POST['end_date'] : null);
1571
	$end_time_string = isset($eventOptions['end_time']) ? $eventOptions['end_time'] : (isset($_POST['end_time']) ? $_POST['end_time'] : null);
1572
1573
	// If the date and time were given in separate strings, combine them
1574
	if (empty($start_string) && isset($start_date_string))
1575
		$start_string = $start_date_string . (isset($start_time_string) ? ' ' . $start_time_string : '');
1576
	if (empty($end_string) && isset($end_date_string))
1577
		$end_string = $end_date_string . (isset($end_time_string) ? ' ' . $end_time_string : '');
1578
1579
	// If some form of string input was given, override individually defined options with it
1580
	if (isset($start_string))
1581
	{
1582
		$start_string_parsed = date_parse(convertDateToEnglish($start_string));
1583
		if (empty($start_string_parsed['error_count']) && empty($start_string_parsed['warning_count']))
1584
		{
1585
			if ($start_string_parsed['year'] != false)
1586
			{
1587
				$start_year = $start_string_parsed['year'];
1588
				$start_month = $start_string_parsed['month'];
1589
				$start_day = $start_string_parsed['day'];
1590
			}
1591
			if ($start_string_parsed['hour'] != false)
1592
			{
1593
				$start_hour = $start_string_parsed['hour'];
1594
				$start_minute = $start_string_parsed['minute'];
1595
				$start_second = $start_string_parsed['second'];
1596
			}
1597
		}
1598
	}
1599
	if (isset($end_string))
1600
	{
1601
		$end_string_parsed = date_parse(convertDateToEnglish($end_string));
1602
		if (empty($end_string_parsed['error_count']) && empty($end_string_parsed['warning_count']))
1603
		{
1604
			if ($end_string_parsed['year'] != false)
1605
			{
1606
				$end_year = $end_string_parsed['year'];
1607
				$end_month = $end_string_parsed['month'];
1608
				$end_day = $end_string_parsed['day'];
1609
			}
1610
			if ($end_string_parsed['hour'] != false)
1611
			{
1612
				$end_hour = $end_string_parsed['hour'];
1613
				$end_minute = $end_string_parsed['minute'];
1614
				$end_second = $end_string_parsed['second'];
1615
			}
1616
		}
1617
	}
1618
1619
	// Validate input
1620
	$start_date_isvalid = checkdate($start_month, $start_day, $start_year);
1621
	$end_date_isvalid = checkdate($end_month, $end_day, $end_year);
1622
1623
	$start_time_isset = (isset($start_hour) && isset($start_minute) && isset($start_second));
1624
	$d = date_parse(sprintf('%02d:%02d:%02d', $start_hour, $start_minute, $start_second));
1625
	$start_time_isvalid = ($d['error_count'] == 0 && $d['warning_count'] == 0) ? true : false;
1626
1627
	$end_time_isset = (isset($end_hour) && isset($end_minute) && isset($end_second));
1628
	$d = date_parse(sprintf('%02d:%02d:%02d', $end_hour, $end_minute, $end_second));
1629
	$end_time_isvalid = ($d['error_count'] == 0 && $d['warning_count'] == 0) ? true : false;
1630
1631
	// Uh-oh...
1632
	if ($start_date_isvalid === false)
1633
	{
1634
		fatal_lang_error('invalid_date', false);
1635
	}
1636
1637
	// Make sure we use valid values for everything
1638
	if ($end_date_isvalid === false)
1639
	{
1640
		$end_year = $start_year;
1641
		$end_month = $start_month;
1642
		$end_day = $start_day;
1643
	}
1644
1645
	if ($allday === true || $start_time_isset === false || $start_time_isvalid === false)
1646
	{
1647
		$allday = true;
1648
		$start_hour = 0;
1649
		$start_minute = 0;
1650
		$start_second = 0;
1651
	}
1652
1653
	if ($allday === true || $end_time_isvalid === false || $end_time_isset === false)
1654
	{
1655
		$end_hour = $start_hour;
1656
		$end_minute = $start_minute;
1657
		$end_second = $start_second;
1658
	}
1659
1660
	// Now create our datetime objects
1661
	$start_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1662
	$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $end_year, $end_month, $end_day, $end_hour, $end_minute, $end_second) . ' ' . $tz);
1663
1664
	// Is $end_object too early?
1665
	if ($start_object >= $end_object)
1666
	{
1667
		$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1668
		if ($span > 0)
1669
			date_add($end_object, date_interval_create_from_date_string($span . ' days'));
1670
		else
1671
			date_add($end_object, date_interval_create_from_date_string('1 hour'));
1672
	}
1673
1674
	// Is $end_object too late?
1675
	if (!empty($modSettings['cal_maxspan']))
1676
	{
1677
		$date_diff = date_diff($start_object, $end_object);
1678
		if ($date_diff->days > $modSettings['cal_maxspan'])
1679
		{
1680
			if ($modSettings['cal_maxspan'] > 1)
1681
			{
1682
				$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
1683
				date_add($end_object, date_interval_create_from_date_string($modSettings['cal_maxspan'] . ' days'));
1684
			}
1685
			else
1686
				$end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, '11', '59', '59') . ' ' . $tz);
1687
		}
1688
	}
1689
1690
	// Finally, make our strings
1691
	$start_date = date_format($start_object, 'Y-m-d');
1692
	$end_date = date_format($end_object, 'Y-m-d');
1693
1694
	if ($allday == true)
1695
	{
1696
		$start_time = null;
1697
		$end_time = null;
1698
		$tz = null;
1699
	}
1700
	else
1701
	{
1702
		$start_time = date_format($start_object, 'H:i:s');
1703
		$end_time = date_format($end_object, 'H:i:s');
1704
	}
1705
1706
	return array($start_date, $end_date, $start_time, $end_time, $tz);
1707
}
1708
1709
/**
1710
 * Helper function for getEventRange, getEventProperties, getNewEventDatetimes, etc.
1711
 *
1712
 * @param array $row A database row representing an event from the calendar table
1713
 * @return array An array containing the start and end date and time properties for the event
1714
 */
1715
function buildEventDatetimes($row)
1716
{
1717
	global $sourcedir, $user_info, $txt;
1718
	static $date_format = '', $time_format = '';
1719
1720
	require_once($sourcedir . '/Subs.php');
1721
	static $timezone_array = array();
1722
1723
	loadLanguage('Timezones');
1724
1725
	// First, try to create a better date format, ignoring the "time" elements.
1726
	if (empty($date_format))
1727
		$date_format = get_date_or_time_format('date');
1728
1729
	// We want a fairly compact version of the time, but as close as possible to the user's settings.
1730
	if (empty($time_format))
1731
		$time_format = strtr(get_date_or_time_format('time'), array(
1732
			'%I' => '%l',
1733
			'%H' => '%k',
1734
			'%S' => '',
1735
			'%r' => '%l:%M %p',
1736
			'%R' => '%k:%M',
1737
			'%T' => '%l:%M',
1738
		));
1739
1740
	// Should this be an all day event?
1741
	$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;
0 ignored issues
show
Bug introduced by
timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

1741
	$allday = (empty($row['start_time']) || empty($row['end_time']) || empty($row['timezone']) || !in_array($row['timezone'], /** @scrutinizer ignore-type */ timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))) ? true : false;
Loading history...
Bug introduced by
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1742
1743
	// How many days does this event span?
1744
	$span = 1 + date_interval_format(date_diff(date_create($row['start_date']), date_create($row['end_date'])), '%d');
1745
1746
	// We need to have a defined timezone in the steps below
1747
	if (empty($row['timezone']))
1748
		$row['timezone'] = getUserTimezone();
1749
1750
	if (empty($timezone_array[$row['timezone']]))
1751
		$timezone_array[$row['timezone']] = timezone_open($row['timezone']);
1752
1753
	// Get most of the standard date information for the start and end datetimes
1754
	$start = date_parse($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''));
1755
	$end = date_parse($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''));
1756
1757
	// But we also want more info, so make some DateTime objects we can use
1758
	$start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$row['timezone']]);
1759
	$end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$row['timezone']]);
1760
1761
	// Unix timestamps are good
1762
	$start['timestamp'] = date_format($start_object, 'U');
1763
	$end['timestamp'] = date_format($end_object, 'U');
1764
1765
	// Datetime string without timezone  (e.g. '2016-12-28 22:45:30')
1766
	$start['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1767
	$end['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1768
1769
	// ISO formatted datetime string, relative to UTC (e.g. '2016-12-29T05:45:30+00:00')
1770
	$start['iso_gmdate'] = gmdate('c', $start['timestamp']);
1771
	$end['iso_gmdate'] = gmdate('c', $end['timestamp']);
1772
1773
	// Strings showing the datetimes in the user's preferred format, relative to the user's time zone
1774
	list($start['date_local'], $start['time_local']) = explode(' § ', timeformat($start['timestamp'], $date_format . ' § ' . $time_format));
1775
	list($end['date_local'], $end['time_local']) = explode(' § ', timeformat($end['timestamp'], $date_format . ' § ' . $time_format));
1776
1777
	// Strings showing the datetimes in the user's preferred format, relative to the event's time zone
1778
	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'));
1779
	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'));
1780
1781
	// The time zone identifier (e.g. 'Europe/London') and abbreviation (e.g. 'GMT')
1782
	$tz = date_format($start_object, 'e');
1783
	$tz_abbrev = date_format($start_object, 'T');
1784
1785
	// If the abbreviation is just a numerical offset from UTC, make that clear.
1786
	if (strspn($tz_abbrev, '+-') > 0)
1787
		$tz_abbrev = 'UTC' . $tz_abbrev;
1788
1789
	return array($start, $end, $allday, $span, $tz, $tz_abbrev);
1790
}
1791
1792
/**
1793
 * Gets all of the holidays for the listing
1794
 *
1795
 * @param int $start The item to start with (for pagination purposes)
1796
 * @param int $items_per_page How many items to show on each page
1797
 * @param string $sort A string indicating how to sort the results
1798
 * @return array An array of holidays, each of which is an array containing the id, year, month, day and title of the holiday
1799
 */
1800
function list_getHolidays($start, $items_per_page, $sort)
1801
{
1802
	global $smcFunc;
1803
1804
	$request = $smcFunc['db_query']('', '
1805
		SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
1806
		FROM {db_prefix}calendar_holidays
1807
		ORDER BY {raw:sort}
1808
		LIMIT {int:start}, {int:max}',
1809
		array(
1810
			'sort' => $sort,
1811
			'start' => $start,
1812
			'max' => $items_per_page,
1813
		)
1814
	);
1815
	$holidays = array();
1816
	while ($row = $smcFunc['db_fetch_assoc']($request))
1817
		$holidays[] = $row;
1818
	$smcFunc['db_free_result']($request);
1819
1820
	return $holidays;
1821
}
1822
1823
/**
1824
 * Helper function to get the total number of holidays
1825
 *
1826
 * @return int The total number of holidays
1827
 */
1828
function list_getNumHolidays()
1829
{
1830
	global $smcFunc;
1831
1832
	$request = $smcFunc['db_query']('', '
1833
		SELECT COUNT(*)
1834
		FROM {db_prefix}calendar_holidays',
1835
		array(
1836
		)
1837
	);
1838
	list($num_items) = $smcFunc['db_fetch_row']($request);
1839
	$smcFunc['db_free_result']($request);
1840
1841
	return (int) $num_items;
1842
}
1843
1844
/**
1845
 * Remove a holiday from the calendar
1846
 *
1847
 * @param array $holiday_ids An array of IDs of holidays to delete
1848
 */
1849
function removeHolidays($holiday_ids)
1850
{
1851
	global $smcFunc;
1852
1853
	$smcFunc['db_query']('', '
1854
		DELETE FROM {db_prefix}calendar_holidays
1855
		WHERE id_holiday IN ({array_int:id_holiday})',
1856
		array(
1857
			'id_holiday' => $holiday_ids,
1858
		)
1859
	);
1860
1861
	updateSettings(array(
1862
		'calendar_updated' => time(),
1863
	));
1864
}
1865
1866
/**
1867
 * Helper function to convert date string to english
1868
 * so that date_parse can parse the date
1869
 *
1870
 * @param string $date A localized date string
1871
 * @return string English date string
1872
 */
1873
function convertDateToEnglish($date)
1874
{
1875
	global $txt, $context;
1876
1877
	if ($context['user']['language'] == 'english')
1878
		return $date;
1879
1880
	$replacements = array_combine(array_map('strtolower', $txt['months_titles']), array(
1881
		'January', 'February', 'March', 'April', 'May', 'June',
1882
		'July', 'August', 'September', 'October', 'November', 'December'
1883
	));
1884
	$replacements += array_combine(array_map('strtolower', $txt['months_short']), array(
1885
		'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
1886
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
1887
	));
1888
	$replacements += array_combine(array_map('strtolower', $txt['days']), array(
1889
		'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
1890
	));
1891
	$replacements += array_combine(array_map('strtolower', $txt['days_short']), array(
1892
		'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
1893
	));
1894
	$replacements[strtolower($txt['time_am'])] = 'AM';
1895
	$replacements[strtolower($txt['time_pm'])] = 'PM';
1896
1897
	$replacements = array_map('strtolower', $replacements);
1898
1899
	return strtr(strtolower($date), $replacements);
1900
}
1901
1902
?>