Passed
Pull Request — release-2.1 (#6569)
by
unknown
05:18
created

getCalendarList()   D

Complexity

Conditions 11
Paths 384

Size

Total Lines 64
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 38
c 1
b 0
f 0
nc 384
nop 3
dl 0
loc 64
rs 4.1833

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @return array A large array containing all the information needed to show a calendar grid for the given month
399
 */
400
function getCalendarGrid($selected_date, $calendarOptions, $is_previous = false)
401
{
402
	global $scripturl, $modSettings;
403
404
	$selected_object = date_create($selected_date);
405
406
	$next_object = date_create($selected_date);
407
	date_add($next_object, date_interval_create_from_date_string('1 month'));
408
409
	$prev_object = date_create($selected_date);
410
	date_sub($prev_object, date_interval_create_from_date_string('1 month'));
411
412
	// Eventually this is what we'll be returning.
413
	$calendarGrid = array(
414
		'week_days' => array(),
415
		'weeks' => array(),
416
		'short_day_titles' => !empty($calendarOptions['short_day_titles']),
417
		'short_month_titles' => !empty($calendarOptions['short_month_titles']),
418
		'current_month' => date_format($selected_object, 'n'),
419
		'current_year' => date_format($selected_object, 'Y'),
420
		'current_day' => date_format($selected_object, 'd'),
421
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
422
		'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
423
		'previous_calendar' => array(
424
			'year' => date_format($prev_object, 'Y'),
425
			'month' => date_format($prev_object, 'n'),
426
			'day' => date_format($prev_object, 'd'),
427
			'start_date' => date_format($prev_object, 'Y-m-d'),
428
			'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
429
		),
430
		'next_calendar' => array(
431
			'year' => date_format($next_object, 'Y'),
432
			'month' => date_format($next_object, 'n'),
433
			'day' => date_format($next_object, 'd'),
434
			'start_date' => date_format($next_object, 'Y-m-d'),
435
			'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
436
		),
437
		'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

437
		'start_date' => timeformat(/** @scrutinizer ignore-type */ date_format($selected_object, 'U'), get_date_or_time_format('date')),
Loading history...
Bug introduced by
get_date_or_time_format('date') of type string is incompatible with the type boolean expected by parameter $show_today 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

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

603
		'start_date' => timeformat(date_format($selected_object, 'U'), /** @scrutinizer ignore-type */ get_date_or_time_format('date')),
Loading history...
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

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

670
		'start_date' => timeformat(date_format($start_object, 'U'), /** @scrutinizer ignore-type */ get_date_or_time_format('date')),
Loading history...
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

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

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

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

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

1737
	$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...
1738
1739
	// How many days does this event span?
1740
	$span = 1 + date_interval_format(date_diff(date_create($row['start_date']), date_create($row['end_date'])), '%d');
1741
1742
	// We need to have a defined timezone in the steps below
1743
	if (empty($row['timezone']))
1744
		$row['timezone'] = getUserTimezone();
1745
1746
	if (empty($timezone_array[$row['timezone']]))
1747
		$timezone_array[$row['timezone']] = timezone_open($row['timezone']);
1748
1749
	// Get most of the standard date information for the start and end datetimes
1750
	$start = date_parse($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''));
1751
	$end = date_parse($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''));
1752
1753
	// But we also want more info, so make some DateTime objects we can use
1754
	$start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$row['timezone']]);
1755
	$end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$row['timezone']]);
1756
1757
	// Unix timestamps are good
1758
	$start['timestamp'] = date_format($start_object, 'U');
1759
	$end['timestamp'] = date_format($end_object, 'U');
1760
1761
	// Datetime string without timezone  (e.g. '2016-12-28 22:45:30')
1762
	$start['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1763
	$end['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
1764
1765
	// ISO formatted datetime string, relative to UTC (e.g. '2016-12-29T05:45:30+00:00')
1766
	$start['iso_gmdate'] = gmdate('c', $start['timestamp']);
1767
	$end['iso_gmdate'] = gmdate('c', $end['timestamp']);
1768
1769
	// Strings showing the datetimes in the user's preferred format, relative to the user's time zone
1770
	list($start['date_local'], $start['time_local']) = explode(' § ', timeformat($start['timestamp'], $date_format . ' § ' . $time_format));
0 ignored issues
show
Bug introduced by
$date_format . ' § ' . $time_format of type string is incompatible with the type boolean expected by parameter $show_today 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

1770
	list($start['date_local'], $start['time_local']) = explode(' § ', timeformat($start['timestamp'], /** @scrutinizer ignore-type */ $date_format . ' § ' . $time_format));
Loading history...
1771
	list($end['date_local'], $end['time_local']) = explode(' § ', timeformat($end['timestamp'], $date_format . ' § ' . $time_format));
1772
1773
	// Strings showing the datetimes in the user's preferred format, relative to the event's time zone
1774
	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'));
1775
	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'));
1776
1777
	// The time zone identifier (e.g. 'Europe/London') and abbreviation (e.g. 'GMT')
1778
	$tz = date_format($start_object, 'e');
1779
	$tz_abbrev = date_format($start_object, 'T');
1780
1781
	// If the abbreviation is just a numerical offset from UTC, make that clear.
1782
	if (strspn($tz_abbrev, '+-') > 0)
1783
		$tz_abbrev = 'UTC' . $tz_abbrev;
1784
1785
	return array($start, $end, $allday, $span, $tz, $tz_abbrev);
1786
}
1787
1788
/**
1789
 * Gets all of the holidays for the listing
1790
 *
1791
 * @param int $start The item to start with (for pagination purposes)
1792
 * @param int $items_per_page How many items to show on each page
1793
 * @param string $sort A string indicating how to sort the results
1794
 * @return array An array of holidays, each of which is an array containing the id, year, month, day and title of the holiday
1795
 */
1796
function list_getHolidays($start, $items_per_page, $sort)
1797
{
1798
	global $smcFunc;
1799
1800
	$request = $smcFunc['db_query']('', '
1801
		SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
1802
		FROM {db_prefix}calendar_holidays
1803
		ORDER BY {raw:sort}
1804
		LIMIT {int:start}, {int:max}',
1805
		array(
1806
			'sort' => $sort,
1807
			'start' => $start,
1808
			'max' => $items_per_page,
1809
		)
1810
	);
1811
	$holidays = array();
1812
	while ($row = $smcFunc['db_fetch_assoc']($request))
1813
		$holidays[] = $row;
1814
	$smcFunc['db_free_result']($request);
1815
1816
	return $holidays;
1817
}
1818
1819
/**
1820
 * Helper function to get the total number of holidays
1821
 *
1822
 * @return int The total number of holidays
1823
 */
1824
function list_getNumHolidays()
1825
{
1826
	global $smcFunc;
1827
1828
	$request = $smcFunc['db_query']('', '
1829
		SELECT COUNT(*)
1830
		FROM {db_prefix}calendar_holidays',
1831
		array(
1832
		)
1833
	);
1834
	list($num_items) = $smcFunc['db_fetch_row']($request);
1835
	$smcFunc['db_free_result']($request);
1836
1837
	return (int) $num_items;
1838
}
1839
1840
/**
1841
 * Remove a holiday from the calendar
1842
 *
1843
 * @param array $holiday_ids An array of IDs of holidays to delete
1844
 */
1845
function removeHolidays($holiday_ids)
1846
{
1847
	global $smcFunc;
1848
1849
	$smcFunc['db_query']('', '
1850
		DELETE FROM {db_prefix}calendar_holidays
1851
		WHERE id_holiday IN ({array_int:id_holiday})',
1852
		array(
1853
			'id_holiday' => $holiday_ids,
1854
		)
1855
	);
1856
1857
	updateSettings(array(
1858
		'calendar_updated' => time(),
1859
	));
1860
}
1861
1862
?>