getCalendarWeek()   F
last analyzed

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 126
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 36
eloc 69
nc 124319232
nop 4
dl 0
loc 126
rs 0
c 0
b 0
f 0

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
 * @package   ElkArte Forum
7
 * @copyright ElkArte Forum contributors
8
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause (see accompanying LICENSE.txt file)
9
 *
10
 * This file contains code covered by:
11
 * copyright: 2011 Simple Machines (http://www.simplemachines.org)
12
 *
13
 * @version 2.0 dev
14
 *
15
 */
16
17
use ElkArte\Cache\Cache;
18
use ElkArte\Helper\Util;
19
use ElkArte\User;
20
21
/**
22
 * Get all birthdays within the given time range.
23
 *
24
 * What it does:
25
 *
26
 * - finds all the birthdays in the specified range of days.
27
 * - works with birthdays set for no year, or any other year, and respects month and year boundaries.
28
 *
29
 * @param string $low_date inclusive, YYYY-MM-DD
30
 * @param string $high_date inclusive, YYYY-MM-DD
31
 * @return mixed[] days, each of which an array of birthday information for the context
32
 * @package Calendar
33
 */
34
function getBirthdayRange($low_date, $high_date)
35
{
36
	$db = database();
37
38
	// We need to search for any birthday in this range, and whatever year that birthday is on.
39
	$year_low = (int) substr($low_date, 0, 4);
40
	$year_high = (int) substr($high_date, 0, 4);
41
42
	// Collect all of the birthdays for this month.  I know, it's a painful query.
43
	$result = $db->fetchQuery('
44
		SELECT 
45
			id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
46
		FROM {db_prefix}members
47
		WHERE YEAR(birthdate) != {string:year_one}
48
			AND MONTH(birthdate) != {int:no_month}
49
			AND DAYOFMONTH(birthdate) != {int:no_day}
50
			AND YEAR(birthdate) <= {int:max_year}
51
			AND (
52
				DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
53
				OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
54
			)
55
			AND is_activated = {int:is_activated}',
56
		array(
57
			'is_activated' => 1,
58
			'no_month' => 0,
59
			'no_day' => 0,
60
			'year_one' => '0001',
61
			'year_low' => $year_low . '-%m-%d',
62
			'year_high' => $year_high . '-%m-%d',
63
			'low_date' => $low_date,
64
			'high_date' => $high_date,
65
			'max_year' => $year_high,
66
		)
67
	);
68
	$bday = array();
69
	while (($row = $result->fetch_assoc()))
70
	{
71
		if ($year_low != $year_high)
72
		{
73
			$age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
74
		}
75
		else
76
		{
77
			$age_year = $year_low;
78
		}
79
80
		$bday[$age_year . substr($row['birthdate'], 4)][] = array(
81
			'id' => $row['id_member'],
82
			'name' => $row['real_name'],
83
			'age' => $row['birth_year'] > 4 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
84
			'is_last' => false
85
		);
86
	}
87
	$result->free_result();
88
89
	// Set is_last, so the themes know when to stop placing separators.
90
	foreach ($bday as $mday => $array)
91
	{
92
		$bday[$mday][count($array) - 1]['is_last'] = true;
93
	}
94
95
	return $bday;
96
}
97
98
/**
99
 * Get all calendar events within the given time range.
100
 *
101
 * What it does:
102
 *
103
 * - finds all the posted calendar events within a date range.
104
 * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
105
 * - censors the posted event titles.
106
 * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
107
 *
108
 * @param string $low_date
109
 * @param string $high_date
110
 * @param bool $use_permissions = true
111
 * @param int|null $limit
112
 * @return array contextual information if use_permissions is true, and an array of the data needed to build that otherwise
113
 * @package Calendar
114
 */
115
function getEventRange($low_date, $high_date, $use_permissions = true, $limit = null)
116
{
117
	global $modSettings;
118
119
	$db = database();
120
121
	$low_date_time = sscanf($low_date, '%04d-%02d-%02d');
122
	$low_date_time = mktime(0, 0, 0, $low_date_time[1], $low_date_time[2], $low_date_time[0]);
123
	$high_date_time = sscanf($high_date, '%04d-%02d-%02d');
124
	$high_date_time = mktime(0, 0, 0, $high_date_time[1], $high_date_time[2], $high_date_time[0]);
125
126
	// Find all the calendar info...
127
	$result = $db->query('', '
128
		SELECT
129
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
130
			cal.id_board, b.member_groups, t.id_first_msg, t.approved, m.subject, b.id_board
131
		FROM {db_prefix}calendar AS cal
132
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
133
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
134
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
135
		WHERE cal.start_date <= {date:high_date}
136
			AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
137
			AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : '') . (!empty($limit) ? '
138
		LIMIT {int:limit}' : ''),
139
		array(
140
			'high_date' => $high_date,
141
			'low_date' => $low_date,
142
			'no_board_link' => 0,
143
			'limit' => $limit,
144
		)
145
	);
146
	$events = array();
147
	while (($row = $result->fetch_assoc()))
148
	{
149
		// If the attached topic is not approved then for the moment pretend it doesn't exist
150
		if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
151
		{
152
			continue;
153
		}
154
155
		// Force a censor of the title - as often these are used by others.
156
		$row['title'] = censor($row['title'], !$use_permissions);
157
158
		$start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
159
		$start_date = max(mktime(0, 0, 0, $start_date[1], $start_date[2], $start_date[0]), $low_date_time);
160
		$end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
161
		$end_date = min(mktime(0, 0, 0, $end_date[1], $end_date[2], $end_date[0]), $high_date_time);
162
163
		$lastDate = '';
164
		for ($date = $start_date; $date <= $end_date; $date += 86400)
165
		{
166
			// Attempt to avoid DST problems.
167
			// @todo Resolve this properly at some point.
168
			if (Util::strftime('%Y-%m-%d', $date) == $lastDate)
169
			{
170
				$date += 3601;
171
			}
172
			$lastDate = Util::strftime('%Y-%m-%d', $date);
173
			$href = getUrl('topic', ['topic' => $row['id_topic'], 'start' => '0', 'subject' => $row['subject']]);
174
175
			// If we're using permissions (calendar pages?) then just output normal contextual style information.
176
			if ($use_permissions)
177
			{
178
				if ((int) $row['id_board'] === 0)
179
				{
180
					$modify_href = ['action' => 'calendar', 'sa' => 'post', 'eventid' => $row['id_event'], '{session_data}'];
181
				}
182
				else
183
				{
184
					$modify_href = ['action' => 'post', 'msg' => $row['id_first_msg'], 'topic' => $row['id_topic'] . '.0', 'calendar', 'eventid' => $row['id_event'], '{session_data}'];
185
				}
186
187
				$events[Util::strftime('%Y-%m-%d', $date)][] = array(
188
					'id' => $row['id_event'],
189
					'title' => $row['title'],
190
					'start_date' => $row['start_date'],
191
					'end_date' => $row['end_date'],
192
					'is_last' => false,
193
					'id_board' => $row['id_board'],
194
					'id_topic' => $row['id_topic'],
195
					'href' => (int) $row['id_board'] === 0 ? '' : $href,
196
					'link' => (int) $row['id_board'] === 0 ? $row['title'] : '<a href="' . $href . '">' . $row['title'] . '</a>',
197
					'can_edit' => allowedTo('calendar_edit_any') || ((int) $row['id_member'] === User::$info->id && allowedTo('calendar_edit_own')),
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on ElkArte\Helper\ValuesContainer. Since you implemented __get, consider adding a @property annotation.
Loading history...
198
					'modify_href' => getUrl('action', $modify_href),
199
					'can_export' => !empty($modSettings['cal_export']),
200
					'export_href' => getUrl('action', ['action' => 'calendar', 'sa' => 'ical', 'eventid' => $row['id_event'], '{session_data}']),
201
				);
202
			}
203
			// Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
204
			else
205
			{
206
				$events[Util::strftime('%Y-%m-%d', $date)][] = array(
207
					'id' => $row['id_event'],
208
					'title' => $row['title'],
209
					'start_date' => $row['start_date'],
210
					'end_date' => $row['end_date'],
211
					'is_last' => false,
212
					'id_board' => $row['id_board'],
213
					'id_topic' => $row['id_topic'],
214
					'href' => (int) $row['id_topic'] === 0 ? '' : $href,
215
					'link' => (int) $row['id_topic'] === 0 ? $row['title'] : '<a href="' . $href . '">' . $row['title'] . '</a>',
216
					'can_edit' => false,
217
					'can_export' => !empty($modSettings['cal_export']),
218
					'topic' => $row['id_topic'],
219
					'msg' => $row['id_first_msg'],
220
					'poster' => $row['id_member'],
221
					'allowed_groups' => explode(',', (string) $row['member_groups']),
222
				);
223
			}
224
		}
225
	}
226
	$result->free_result();
227
228
	// If we're doing normal contextual data, go through and make things clear to the templates ;).
229
	if ($use_permissions)
230
	{
231
		foreach ($events as $mday => $array)
232
		{
233
			$events[$mday][count($array) - 1]['is_last'] = true;
234
		}
235
	}
236
237
	return $events;
238
}
239
240
/**
241
 * Get all holidays within the given time range.
242
 *
243
 * @param string $low_date YYYY-MM-DD
244
 * @param string $high_date YYYY-MM-DD
245
 * @return array an array of days, which are all arrays of holiday names.
246
 * @package Calendar
247
 */
248
function getHolidayRange($low_date, $high_date)
249
{
250
	$db = database();
251
252
	// Get the lowest and highest dates for "all years".
253
	if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
254
	{
255
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
256
			OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
257
	}
258
	else
259
	{
260
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
261
	}
262
263
	// Find some holidays... ;).
264
	$holidays = array();
265
	$db->fetchQuery('
266
		SELECT 
267
			event_date, YEAR(event_date) AS year, title
268
		FROM {db_prefix}calendar_holidays
269
		WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
270
			OR ' . $allyear_part,
271
		array(
272
			'low_date' => $low_date,
273
			'high_date' => $high_date,
274
			'all_year_low' => '0004' . substr($low_date, 4),
275
			'all_year_high' => '0004' . substr($high_date, 4),
276
			'all_year_jan' => '0004-01-01',
277
			'all_year_dec' => '0004-12-31',
278
		)
279
	)->fetch_callback(
280
		function ($row) use (&$holidays, $low_date, $high_date) {
281
			if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
282
			{
283
				$event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
284
			}
285
			else
286
			{
287
				$event_year = substr($low_date, 0, 4);
288
			}
289
290
			$holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
291
		}
292
	);
293
294
	return $holidays;
295
}
296
297
/**
298
 * Does permission checks to see if an event can be linked to a board/topic.
299
 *
300
 * What it does:
301
 *
302
 * - checks if the current user can link the current topic to the calendar, permissions et al.
303
 * - this requires the calendar_post permission, a forum moderator, or a topic starter.
304
 * - expects the $topic and $board variables to be set.
305
 * - if the user doesn't have proper permissions, an error will be shown.
306
 *
307
 * @package Calendar
308
 * @todo pass $board, $topic and User::$info->id as arguments with fallback for 1.1
309
 * @throws \ElkArte\Exceptions\Exception missing_board_id, missing_topic_id
310
 */
311
function canLinkEvent()
312
{
313
	global $topic, $board;
314
315
	// If you can't post, you can't link.
316
	isAllowedTo('calendar_post');
317
318
	// No board?  No topic?!?
319
	if (empty($board))
320
	{
321
		throw new \ElkArte\Exceptions\Exception('missing_board_id', false);
322
	}
323
324
	if (empty($topic))
325
	{
326
		throw new \ElkArte\Exceptions\Exception('missing_topic_id', false);
327
	}
328
329
	// Administrator, Moderator, or owner.  Period.
330
	if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
331
	{
332
		// Not admin or a moderator of this board. You better be the owner - or else.
333
		$row = topicAttribute($topic, array('id_member_started'));
334
		if (!empty($row))
335
		{
336
			// Not the owner of the topic.
337
			if ($row['id_member_started'] != User::$info->id)
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on ElkArte\Helper\ValuesContainer. Since you implemented __get, consider adding a @property annotation.
Loading history...
338
			{
339
				throw new \ElkArte\Exceptions\Exception('not_your_topic', 'user');
340
			}
341
		}
342
		// Topic/Board doesn't exist.....
343
		else
344
		{
345
			throw new \ElkArte\Exceptions\Exception('calendar_no_topic', 'general');
346
		}
347
	}
348
}
349
350
/**
351
 * Returns date information about 'today' relative to the users time offset.
352
 *
353
 * - returns an array with the current date, day, month, and year.
354
 * takes the users time offset into account.
355
 *
356
 * @package Calendar
357
 */
358
function getTodayInfo()
359
{
360
	return array(
361
		'day' => (int) Util::strftime('%d', forum_time()),
362
		'month' => (int) Util::strftime('%m', forum_time()),
363
		'year' => (int) Util::strftime('%Y', forum_time()),
364
		'date' => Util::strftime('%Y-%m-%d', forum_time()),
365
	);
366
}
367
368
/**
369
 * Provides information (link, month, year) about the previous and next month.
370
 *
371
 * @param int $month
372
 * @param int $year
373
 * @param mixed[] $calendarOptions
374
 * @return array containing all the information needed to show a calendar grid for the given month
375
 * @package Calendar
376
 */
377
function getCalendarGrid($month, $year, $calendarOptions)
378
{
379
	global $modSettings;
380
381
	// Eventually this is what we'll be returning.
382
	$calendarGrid = array(
383
		'week_days' => array(),
384
		'weeks' => array(),
385
		'short_day_titles' => !empty($calendarOptions['short_day_titles']),
386
		'current_month' => $month,
387
		'current_year' => $year,
388
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
389
		'show_week_links' => !empty($calendarOptions['show_week_links']),
390
		'previous_calendar' => array(
391
			'year' => $month == 1 ? $year - 1 : $year,
392
			'month' => $month == 1 ? 12 : $month - 1,
393
			'disabled' => $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
394
		),
395
		'next_calendar' => array(
396
			'year' => $month == 12 ? $year + 1 : $year,
397
			'month' => $month == 12 ? 1 : $month + 1,
398
			'disabled' => date('Y') + $modSettings['cal_limityear'] < ($month == 12 ? $year + 1 : $year),
399
		),
400
		'size' => $calendarOptions['size'] ?? 'large',
401
	);
402
403
	// Get todays date.
404
	$today = getTodayInfo();
405
406
	// Get information about this month.
407
	$month_info = array(
408
		'first_day' => array(
409
			'day_of_week' => (int) Util::strftime('%w', mktime(0, 0, 0, $month, 1, $year)),
410
			'week_num' => (int) Util::strftime('%U', mktime(0, 0, 0, $month, 1, $year)),
411
			'date' => Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month, 1, $year)),
412
		),
413
		'last_day' => array(
414
			'day_of_month' => (int) Util::strftime('%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
415
			'date' => Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
416
		),
417
		'first_day_of_year' => (int) Util::strftime('%w', mktime(0, 0, 0, 1, 1, $year)),
418
		'first_day_of_next_year' => (int) Util::strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1)),
419
	);
420
421
	// The number of days the first row is shifted to the right for the starting day.
422
	$nShift = $month_info['first_day']['day_of_week'];
423
424
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
425
426
	// Starting any day other than Sunday means a shift...
427
	if (!empty($calendarOptions['start_day']))
428
	{
429
		$nShift -= $calendarOptions['start_day'];
430
		if ($nShift < 0)
431
		{
432
			$nShift = 7 + $nShift;
433
		}
434
	}
435
436
	// Number of rows required to fit the month.
437
	$nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
438
	if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
439
	{
440
		$nRows++;
441
	}
442
443
	// Fetch the arrays for birthdays, posted events, and holidays.
444
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
445
	$events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
446
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
447
448
	// Days of the week taking into consideration that they may want it to start on any day.
449
	$count = $calendarOptions['start_day'];
450
	for ($i = 0; $i < 7; $i++)
451
	{
452
		$calendarGrid['week_days'][] = $count;
453
		$count++;
454
		if ($count == 7)
455
		{
456
			$count = 0;
457
		}
458
	}
459
460
	// An adjustment value to apply to all calculated week numbers.
461
	if (!empty($calendarOptions['show_week_num']))
462
	{
463
		// If the first day of the year is a Sunday, then there is no
464
		// adjustment to be made. However, if the first day of the year is not
465
		// a Sunday, then there is a partial week at the start of the year
466
		// that needs to be accounted for.
467
		if ($calendarOptions['start_day'] === 0)
468
		{
469
			$nWeekAdjust = $month_info['first_day_of_year'] === 0 ? 0 : 1;
470
		}
471
		// If we are viewing the weeks, with a starting date other than Sunday,
472
		// then things get complicated! Basically, as PHP is calculating the
473
		// weeks with a Sunday starting date, we need to take this into account
474
		// and offset the whole year dependant on whether the first day in the
475
		// year is above or below our starting date. Note that we offset by
476
		// two, as some of this will get undone quite quickly by the statement
477
		// below.
478
		else
479
		{
480
			$nWeekAdjust = $calendarOptions['start_day'] > $month_info['first_day_of_year'] && $month_info['first_day_of_year'] !== 0 ? 2 : 1;
481
		}
482
483
		// If our week starts on a day greater than the day the month starts
484
		// on, then our week numbers will be one too high. So we need to
485
		// reduce it by one - all these thoughts of offsets makes my head
486
		// hurt...
487
		if ($month_info['first_day']['day_of_week'] < $calendarOptions['start_day'] || $month_info['first_day_of_year'] > 4)
488
		{
489
			$nWeekAdjust--;
490
		}
491
	}
492
	else
493
	{
494
		$nWeekAdjust = 0;
495
	}
496
497
	// Iterate through each week.
498
	$calendarGrid['weeks'] = array();
499
	for ($nRow = 0; $nRow < $nRows; $nRow++)
500
	{
501
		// Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
502
		$calendarGrid['weeks'][$nRow] = array(
503
			'days' => array(),
504
			'number' => $month_info['first_day']['week_num'] + $nRow + $nWeekAdjust
505
		);
506
507
		// Handle the dreaded "week 53", it can happen, but only once in a blue moon ;)
508
		if ($calendarGrid['weeks'][$nRow]['number'] == 53 && $nShift != 4 && $month_info['first_day_of_next_year'] < 4)
509
		{
510
			$calendarGrid['weeks'][$nRow]['number'] = 1;
511
		}
512
513
		// And figure out all the days.
514
		for ($nCol = 0; $nCol < 7; $nCol++)
515
		{
516
			$nDay = ($nRow * 7) + $nCol - $nShift + 1;
517
518
			if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
519
			{
520
				$nDay = 0;
521
			}
522
523
			$date = sprintf('%04d-%02d-%02d', $year, $month, $nDay);
524
525
			$calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
526
				'day' => $nDay,
527
				'date' => $date,
528
				'is_today' => $date == $today['date'],
529
				'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
530
				'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
531
				'events' => !empty($events[$date]) ? $events[$date] : array(),
532
				'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
533
			);
534
		}
535
	}
536
537
	// Set the previous and the next month's links.
538
	$calendarGrid['previous_calendar']['href'] = getUrl('action', ['action' => 'calendar', 'year' => $calendarGrid['previous_calendar']['year'], 'month' => $calendarGrid['previous_calendar']['month']]);
539
	$calendarGrid['next_calendar']['href'] = getUrl('action', ['action' => 'calendar', 'year' => $calendarGrid['next_calendar']['year'], 'month' => $calendarGrid['next_calendar']['month']]);
540
541
	return $calendarGrid;
542
}
543
544
/**
545
 * Returns the information needed to show a calendar for the given week.
546
 *
547
 * @param int $month
548
 * @param int $year
549
 * @param int $day
550
 * @param mixed[] $calendarOptions
551
 * @return array
552
 * @package Calendar
553
 */
554
function getCalendarWeek($month, $year, $day, $calendarOptions)
555
{
556
	global $modSettings;
557
558
	// Get todays date.
559
	$today = getTodayInfo();
560
561
	// What is the actual "start date" for the passed day.
562
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
563
	$day_of_week = (int) Util::strftime('%w', mktime(0, 0, 0, $month, $day, $year));
564
	if ($day_of_week != $calendarOptions['start_day'])
565
	{
566
		// Here we offset accordingly to get things to the real start of a week.
567
		$date_diff = $day_of_week - $calendarOptions['start_day'];
568
		if ($date_diff < 0)
569
		{
570
			$date_diff += 7;
571
		}
572
		$new_timestamp = mktime(0, 0, 0, $month, $day, $year) - $date_diff * 86400;
573
		$day = (int) Util::strftime('%d', $new_timestamp);
574
		$month = (int) Util::strftime('%m', $new_timestamp);
575
		$year = (int) Util::strftime('%Y', $new_timestamp);
576
	}
577
578
	// Now start filling in the calendar grid.
579
	$calendarGrid = array(
580
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
581
		// Previous week is easy - just step back one day.
582
		'previous_week' => array(
583
			'year' => $day == 1 ? ($month == 1 ? $year - 1 : $year) : $year,
584
			'month' => $day == 1 ? ($month == 1 ? 12 : $month - 1) : $month,
585
			'day' => $day == 1 ? 28 : $day - 1,
586
			'disabled' => $day < 7 && $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
587
		),
588
		'next_week' => array(
589
			'disabled' => $day > 25 && date('Y') + $modSettings['cal_limityear'] < ($month == 12 ? $year + 1 : $year),
590
		),
591
	);
592
593
	// The next week calculation requires a bit more work.
594
	$curTimestamp = mktime(0, 0, 0, $month, $day, $year);
595
	$nextWeekTimestamp = $curTimestamp + 604800;
596
	$calendarGrid['next_week']['day'] = (int) Util::strftime('%d', $nextWeekTimestamp);
597
	$calendarGrid['next_week']['month'] = (int) Util::strftime('%m', $nextWeekTimestamp);
598
	$calendarGrid['next_week']['year'] = (int) Util::strftime('%Y', $nextWeekTimestamp);
599
600
	// Fetch the arrays for birthdays, posted events, and holidays.
601
	$startDate = Util::strftime('%Y-%m-%d', $curTimestamp);
602
	$endDate = Util::strftime('%Y-%m-%d', $nextWeekTimestamp);
603
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($startDate, $endDate) : array();
604
	$events = $calendarOptions['show_events'] ? getEventRange($startDate, $endDate) : array();
605
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($startDate, $endDate) : array();
606
607
	// An adjustment value to apply to all calculated week numbers.
608
	if (!empty($calendarOptions['show_week_num']))
609
	{
610
		$first_day_of_year = (int) Util::strftime('%w', mktime(0, 0, 0, 1, 1, $year));
611
		$first_day_of_next_year = (int) Util::strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1));
612
		// this one is not used in its scope
613
		// $last_day_of_last_year = (int) Util::strftime('%w', mktime(0, 0, 0, 12, 31, $year - 1));
614
615
		// All this is as getCalendarGrid.
616
		if ($calendarOptions['start_day'] === 0)
617
		{
618
			$nWeekAdjust = $first_day_of_year === 0 && $first_day_of_year > 3 ? 0 : 1;
619
		}
620
		else
621
		{
622
			$nWeekAdjust = $calendarOptions['start_day'] > $first_day_of_year && $first_day_of_year !== 0 ? 2 : 1;
623
		}
624
625
		$calendarGrid['week_number'] = (int) Util::strftime('%U', mktime(0, 0, 0, $month, $day, $year)) + $nWeekAdjust;
626
627
		// If this crosses a year boundary and includes january it should be week one.
628
		if ((int) Util::strftime('%Y', $curTimestamp + 518400) != $year && $calendarGrid['week_number'] > 53 && $first_day_of_next_year < 5)
629
		{
630
			$calendarGrid['week_number'] = 1;
631
		}
632
	}
633
634
	// This holds all the main data - there is at least one month!
635
	$calendarGrid['months'] = array();
636
	$lastDay = 99;
637
	$curDay = $day;
638
	$curDayOfWeek = $calendarOptions['start_day'];
639
	for ($i = 0; $i < 7; $i++)
640
	{
641
		// Have we gone into a new month (Always happens first cycle too)
642
		if ($lastDay > $curDay)
643
		{
644
			$curMonth = $lastDay == 99 ? $month : ($month == 12 ? 1 : $month + 1);
645
			$curYear = $lastDay == 99 ? $year : ($curMonth == 1 && $month == 12 ? $year + 1 : $year);
646
			$calendarGrid['months'][$curMonth] = array(
647
				'current_month' => $curMonth,
648
				'current_year' => $curYear,
649
				'days' => array(),
650
			);
651
		}
652
653
		// Add todays information to the pile!
654
		$date = sprintf('%04d-%02d-%02d', $curYear, $curMonth, $curDay);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $curMonth does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $curYear does not seem to be defined for all execution paths leading up to this point.
Loading history...
655
656
		$calendarGrid['months'][$curMonth]['days'][$curDay] = array(
657
			'day' => $curDay,
658
			'day_of_week' => $curDayOfWeek,
659
			'date' => $date,
660
			'is_today' => $date == $today['date'],
661
			'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
662
			'events' => !empty($events[$date]) ? $events[$date] : array(),
663
			'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
664
		);
665
666
		// Make the last day what the current day is and work out what the next day is.
667
		$lastDay = $curDay;
668
		$curTimestamp += 86400;
669
		$curDay = (int) Util::strftime('%d', $curTimestamp);
670
671
		// Also increment the current day of the week.
672
		$curDayOfWeek = $curDayOfWeek >= 6 ? 0 : ++$curDayOfWeek;
673
	}
674
675
	// Set the previous and the next week's links.
676
	$calendarGrid['previous_week']['href'] = getUrl('action', ['action' => 'calendar', 'viewweek', 'year' => $calendarGrid['previous_week']['year'], 'month' => $calendarGrid['previous_week']['month'], 'day' => $calendarGrid['previous_week']['day']]);
677
	$calendarGrid['next_week']['href'] = getUrl('action', ['action' => 'calendar', 'viewweek', 'year' => $calendarGrid['next_week']['year'], 'month' => $calendarGrid['next_week']['month'], 'day' => $calendarGrid['next_week']['day']]);
678
679
	return $calendarGrid;
680
}
681
682
/**
683
 * Retrieve all events for the given days, independently of the users offset.
684
 *
685
 * What it does:
686
 *
687
 * - cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
688
 * - widens the search range by an extra 24 hours to support time offset shifts.
689
 * - used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
690
 *
691
 * @param int $days_to_index
692
 * @return array
693
 * @package Calendar
694
 */
695
function cache_getOffsetIndependentEvents($days_to_index)
696
{
697
	$low_date = Util::strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
698
	$high_date = Util::strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);
699
700
	return array(
701
		'data' => array(
702
			'holidays' => getHolidayRange($low_date, $high_date),
703
			'birthdays' => getBirthdayRange($low_date, $high_date),
704
			'events' => getEventRange($low_date, $high_date, false),
705
		),
706
		'refresh_eval' => 'return \'' . Util::strftime('%Y%m%d', forum_time(false)) . '\' != \\ElkArte\\Helper\\Util::strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
707
		'expires' => time() + 3600,
708
	);
709
}
710
711
/**
712
 * cache callback function used to retrieve the upcoming birthdays, holidays, and events
713
 * within the given period, taking into account the users time offset.
714
 *
715
 * - Called from the BoardIndex to display the current day's events on the board index
716
 * - used by the board index and SSI to show the upcoming events.
717
 *
718
 * @param mixed[] $eventOptions
719
 * @return array
720
 * @package Calendar
721
 */
722
function cache_getRecentEvents($eventOptions)
723
{
724
	// With the 'static' cached data we can calculate the user-specific data.
725
	$cached_data = Cache::instance()->quick_get('calendar_index', 'subs/Calendar.subs.php', 'cache_getOffsetIndependentEvents', array($eventOptions['num_days_shown']));
726
727
	// Get the information about today (from user perspective).
728
	$today = getTodayInfo();
729
730
	$return_data = array(
731
		'calendar_holidays' => array(),
732
		'calendar_birthdays' => array(),
733
		'calendar_events' => array(),
734
	);
735
736
	// Set the event span to be shown in seconds.
737
	$days_for_index = $eventOptions['num_days_shown'] * 86400;
738
739
	// Get the current member time/date.
740
	$now = forum_time();
741
742
	// Holidays between now and now + days.
743
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
744
	{
745
		if (isset($cached_data['holidays'][Util::strftime('%Y-%m-%d', $i)]))
746
		{
747
			$return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][Util::strftime('%Y-%m-%d', $i)]);
748
		}
749
	}
750
751
	// Happy Birthday, guys and gals!
752
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
753
	{
754
		$loop_date = Util::strftime('%Y-%m-%d', $i);
755
		if (isset($cached_data['birthdays'][$loop_date]))
756
		{
757
			foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
758
			{
759
				$cached_data['birthdays'][Util::strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
760
			}
761
			$return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
762
		}
763
	}
764
765
	$duplicates = array();
766
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
767
	{
768
		// Determine the date of the current loop step.
769
		$loop_date = Util::strftime('%Y-%m-%d', $i);
770
771
		// No events today? Check the next day.
772
		if (empty($cached_data['events'][$loop_date]))
773
		{
774
			continue;
775
		}
776
777
		// Loop through all events to add a few last-minute values.
778
		foreach ($cached_data['events'][$loop_date] as $ev => $event)
779
		{
780
			// Create a shortcut variable for easier access.
781
			$this_event = &$cached_data['events'][$loop_date][$ev];
782
783
			// Skip duplicates.
784
			if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
785
			{
786
				unset($cached_data['events'][$loop_date][$ev]);
787
				continue;
788
			}
789
			else
790
			{
791
				$duplicates[$this_event['topic'] . $this_event['title']] = true;
792
			}
793
794
			// Might be set to true afterwards, depending on the permissions.
795
			$this_event['can_edit'] = false;
796
			$this_event['is_today'] = $loop_date === $today['date'];
797
			$this_event['date'] = $loop_date;
798
		}
799
800
		if (!empty($cached_data['events'][$loop_date]))
801
		{
802
			$return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
803
		}
804
	}
805
806
	// Mark the last item so that a list separator can be used in the template.
807
	for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
808
	{
809
		$return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
810
	}
811
	for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
812
	{
813
		$return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
814
	}
815
816
	return array(
817
		'data' => $return_data,
818
		'expires' => time() + 3600,
819
		'refresh_eval' => 'return \'' . Util::strftime('%Y%m%d', forum_time(false)) . '\' != \\ElkArte\\Helper\\Util::strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
820
		'post_retri_eval' => '
821
			require_once(SUBSDIR . \'/Calendar.subs.php\');
822
			return cache_getRecentEvents_post_retri_eval($cache_block, $params);',
823
	);
824
}
825
826
/**
827
 * Refines the data retrieved from the cache for the cache_getRecentEvents function.
828
 *
829
 * @param mixed[] $cache_block
830
 * @param mixed[] $params
831
 * @package Calendar
832
 */
833
function cache_getRecentEvents_post_retri_eval(&$cache_block, $params)
834
{
835
	foreach ($cache_block['data']['calendar_events'] as $k => $event)
836
	{
837
		// Remove events that the user may not see or wants to ignore.
838
		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))
0 ignored issues
show
Bug introduced by
It seems like ElkArte\User::info->groups can also be of type null; however, parameter $array of array_intersect() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

838
		if ((count(array_intersect(/** @scrutinizer ignore-type */ User::$info->groups, $event['allowed_groups'])) === 0 && !allowedTo('admin_forum') && !empty($event['id_board'])) || in_array($event['id_board'], User::$info->ignoreboards))
Loading history...
Bug introduced by
It seems like ElkArte\User::info->ignoreboards can also be of type null; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

838
		if ((count(array_intersect(User::$info->groups, $event['allowed_groups'])) === 0 && !allowedTo('admin_forum') && !empty($event['id_board'])) || in_array($event['id_board'], /** @scrutinizer ignore-type */ User::$info->ignoreboards))
Loading history...
Bug Best Practice introduced by
The property ignoreboards does not exist on ElkArte\Helper\ValuesContainer. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property groups does not exist on ElkArte\Helper\ValuesContainer. Since you implemented __get, consider adding a @property annotation.
Loading history...
839
		{
840
			unset($cache_block['data']['calendar_events'][$k]);
841
		}
842
		else
843
		{
844
			// Whether the event can be edited depends on the permissions.
845
			$cache_block['data']['calendar_events'][$k]['can_edit'] = allowedTo('calendar_edit_any') || ($event['poster'] == User::$info->id && allowedTo('calendar_edit_own'));
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on ElkArte\Helper\ValuesContainer. Since you implemented __get, consider adding a @property annotation.
Loading history...
846
847
			if ($event['topic'] == 0)
848
			{
849
				$modify_href = ['action' => 'calendar', 'sa' => 'post', 'eventid' => $event['id'], '{session_data}'];
850
			}
851
			else
852
			{
853
				$modify_href = [
854
					'action' => 'post',
855
					'msg' => $event['msg'],
856
					'topic' => $event['topic'] . '.0',
857
					'calendar',
858
					'eventid' => $event['id'],
859
					'{session_data}'
860
				];
861
			}
862
			// The added session code makes this URL not cachable.
863
			$cache_block['data']['calendar_events'][$k]['modify_href'] = getUrl('action', $modify_href);
864
		}
865
	}
866
867
	if (empty($params[0]['include_holidays']))
868
	{
869
		$cache_block['data']['calendar_holidays'] = array();
870
	}
871
872
	if (empty($params[0]['include_birthdays']))
873
	{
874
		$cache_block['data']['calendar_birthdays'] = array();
875
	}
876
877
	if (empty($params[0]['include_events']))
878
	{
879
		$cache_block['data']['calendar_events'] = array();
880
	}
881
882
	$cache_block['data']['show_calendar'] = !empty($cache_block['data']['calendar_holidays']) || !empty($cache_block['data']['calendar_birthdays']) || !empty($cache_block['data']['calendar_events']);
883
}
884
885
/**
886
 * Get the event's poster.
887
 *
888
 * @param int $event_id
889
 * @return int|bool the id of the poster or false if the event was not found
890
 * @package Calendar
891
 */
892
function getEventPoster($event_id)
893
{
894
	$db = database();
895
896
	// A simple database query, how hard can that be?
897
	$request = $db->query('', '
898
		SELECT 
899
			id_member
900
		FROM {db_prefix}calendar
901
		WHERE id_event = {int:id_event}
902
		LIMIT 1',
903
		array(
904
			'id_event' => $event_id,
905
		)
906
	);
907
908
	// No results, return false.
909
	if ($request->num_rows() === 0)
910
	{
911
		return false;
912
	}
913
914
	// Grab the results and return.
915
	list ($poster) = $request->fetch_row();
916
	$request->free_result();
917
918
	return (int) $poster;
919
}
920
921
/**
922
 * Inserts events in to the calendar
923
 *
924
 * What it does:
925
 *
926
 * - Consolidating the various INSERT statements into this function.
927
 * - inserts the passed event information into the calendar table.
928
 * - allows to either set a time span (in days) or an end_date.
929
 * - does not check any permissions of any sort.
930
 *
931
 * @param mixed[] $eventOptions
932
 * @package Calendar
933
 */
934
function insertEvent(&$eventOptions)
935
{
936
	$db = database();
937
938
	// Add special chars to the title.
939
	$eventOptions['title'] = Util::htmlspecialchars($eventOptions['title'], ENT_QUOTES);
940
941
	// Add some sanity checking to the span.
942
	$eventOptions['span'] = isset($eventOptions['span']) && $eventOptions['span'] > 0 ? (int) $eventOptions['span'] : 0;
943
944
	// Make sure the start date is in ISO order.
945
	$year = '';
946
	$month = '';
947
	$day = '';
948
	if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
0 ignored issues
show
Unused Code introduced by
The assignment to $num_results is dead and can be removed.
Loading history...
949
	{
950
		trigger_error('insertEvent(): invalid start date format given', E_USER_ERROR);
951
	}
952
953
	// Set the end date (if not yet given)
954
	if (!isset($eventOptions['end_date']))
955
	{
956
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
0 ignored issues
show
Bug introduced by
$day of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

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

956
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month, /** @scrutinizer ignore-type */ $day, $year) + $eventOptions['span'] * 86400);
Loading history...
Bug introduced by
$month of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

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

956
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, /** @scrutinizer ignore-type */ $month, $day, $year) + $eventOptions['span'] * 86400);
Loading history...
957
	}
958
959
	// If no topic and board are given, they are not linked to a topic.
960
	$eventOptions['id_board'] = isset($eventOptions['id_board']) ? (int) $eventOptions['id_board'] : 0;
961
	$eventOptions['id_topic'] = isset($eventOptions['id_topic']) ? (int) $eventOptions['id_topic'] : 0;
962
963
	$event_columns = array(
964
		'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
965
		'start_date' => 'date', 'end_date' => 'date',
966
	);
967
	$event_parameters = array(
968
		$eventOptions['id_board'], $eventOptions['id_topic'], $eventOptions['title'], $eventOptions['member'],
969
		$eventOptions['start_date'], $eventOptions['end_date'],
970
	);
971
972
	call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));
973
974
	// Insert the event!
975
	$db->insert('',
976
		'{db_prefix}calendar',
977
		$event_columns,
978
		$event_parameters,
979
		array('id_event')
980
	);
981
982
	// Store the just inserted id_event for future reference.
983
	$eventOptions['id'] = $db->insert_id('{db_prefix}calendar');
984
985
	// Update the settings to show something calendarish was updated.
986
	updateSettings(array(
987
		'calendar_updated' => time(),
988
	));
989
}
990
991
/**
992
 * Modifies an event.
993
 *
994
 * - allows to either set a time span (in days) or an end_date.
995
 * - does not check any permissions of any sort.
996
 *
997
 * @param int $event_id
998
 * @param mixed[] $eventOptions
999
 * @package Calendar
1000
 */
1001
function modifyEvent($event_id, &$eventOptions)
1002
{
1003
	$db = database();
1004
1005
	// Properly sanitize the title.
1006
	$eventOptions['title'] = Util::htmlspecialchars($eventOptions['title'], ENT_QUOTES);
1007
1008
	// Scan the start date for validity and get its components.
1009
	$year = '';
1010
	$month = '';
1011
	$day = '';
1012
	if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
0 ignored issues
show
Unused Code introduced by
The assignment to $num_results is dead and can be removed.
Loading history...
1013
	{
1014
		trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);
1015
	}
1016
1017
	// Default span to 0 days.
1018
	$eventOptions['span'] = isset($eventOptions['span']) ? (int) $eventOptions['span'] : 0;
1019
1020
	// Set the end date to the start date + span (if the end date wasn't already given).
1021
	if (!isset($eventOptions['end_date']))
1022
	{
1023
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
0 ignored issues
show
Bug introduced by
$month of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

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

1023
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, /** @scrutinizer ignore-type */ $month, $day, $year) + $eventOptions['span'] * 86400);
Loading history...
Bug introduced by
$day of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

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

1023
		$eventOptions['end_date'] = Util::strftime('%Y-%m-%d', mktime(0, 0, 0, $month, /** @scrutinizer ignore-type */ $day, $year) + $eventOptions['span'] * 86400);
Loading history...
1024
	}
1025
1026
	$event_columns = array(
1027
		'start_date' => 'start_date = {date:start_date}',
1028
		'end_date' => 'end_date = {date:end_date}',
1029
		'title' => 'title = SUBSTRING({string:title}, 1, 60)',
1030
		'id_board' => 'id_board = {int:id_board}',
1031
		'id_topic' => 'id_topic = {int:id_topic}'
1032
	);
1033
1034
	call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns));
1035
1036
	$eventOptions['id_event'] = $event_id;
1037
1038
	$to_update = array();
1039
	foreach ($event_columns as $key => $value)
1040
	{
1041
		if (isset($eventOptions[$key]))
1042
		{
1043
			$to_update[] = $value;
1044
		}
1045
	}
1046
1047
	if (empty($to_update))
1048
	{
1049
		return;
1050
	}
1051
1052
	$db->query('', '
1053
		UPDATE {db_prefix}calendar
1054
		SET
1055
			' . implode(', ', $to_update) . '
1056
		WHERE id_event = {int:id_event}',
1057
		$eventOptions
1058
	);
1059
1060
	updateSettings(array(
1061
		'calendar_updated' => time(),
1062
	));
1063
}
1064
1065
/**
1066
 * Remove an event
1067
 *
1068
 * - does no permission checks.
1069
 *
1070
 * @param int $event_id
1071
 * @package Calendar
1072
 */
1073
function removeEvent($event_id)
1074
{
1075
	$db = database();
1076
1077
	$db->query('', '
1078
		DELETE FROM {db_prefix}calendar
1079
		WHERE id_event = {int:id_event}',
1080
		array(
1081
			'id_event' => $event_id,
1082
		)
1083
	);
1084
1085
	call_integration_hook('integrate_remove_event', array($event_id));
1086
1087
	updateSettings(array(
1088
		'calendar_updated' => time(),
1089
	));
1090
}
1091
1092
/**
1093
 * Gets all the events properties
1094
 *
1095
 * @param int $event_id
1096
 * @param bool $calendar_only
1097
 * @return mixed[]|bool
1098
 * @package Calendar
1099
 */
1100
function getEventProperties($event_id, $calendar_only = false)
1101
{
1102
	$db = database();
1103
1104
	$request = $db->query('', '
1105
		SELECT
1106
			c.id_event, c.id_board, c.id_topic, MONTH(c.start_date) AS month,
1107
			DAYOFMONTH(c.start_date) AS day, YEAR(c.start_date) AS year,
1108
			(TO_DAYS(c.end_date) - TO_DAYS(c.start_date)) AS span, c.id_member, c.title' . ($calendar_only ? '' : ',
1109
			t.id_first_msg, t.id_member_started,
1110
			mb.real_name, m.modified_time') . '
1111
		FROM {db_prefix}calendar AS c' . ($calendar_only ? '' : '
1112
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
1113
			LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
1114
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg  = t.id_first_msg)') . '
1115
		WHERE c.id_event = {int:id_event}
1116
		LIMIT 1',
1117
		array(
1118
			'id_event' => $event_id,
1119
		)
1120
	);
1121
	// If nothing returned, we are in poo, poo.
1122
	if ($request->num_rows() === 0)
1123
	{
1124
		return false;
1125
	}
1126
	$row = $request->fetch_assoc();
1127
	$request->free_result();
1128
1129
	if ($calendar_only)
1130
	{
1131
		$return_value = $row;
1132
	}
1133
	else
1134
	{
1135
		$return_value = [
1136
			'boards' => [],
1137
			'board' => (int) $row['id_board'],
1138
			'new' => 0,
1139
			'eventid' => (int) $event_id,
1140
			'year' => (int) $row['year'],
1141
			'month' => (int) $row['month'],
1142
			'day' => (int) $row['day'],
1143
			'title' => $row['title'],
1144
			'span' => 1 + $row['span'],
1145
			'member' => (int) $row['id_member'],
1146
			'realname' => $row['real_name'],
1147
			'sequence' => $row['modified_time'],
1148
			'topic' => [
1149
				'id' => (int) $row['id_topic'],
1150
				'member_started' => (int) $row['id_member_started'],
1151
				'first_msg' => (int) $row['id_first_msg'],
1152
			],
1153
		];
1154
1155
		$return_value['last_day'] = (int) Util::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']));
1156
	}
1157
1158
	return $return_value;
1159
}
1160
1161
/**
1162
 * Fetch and event that may be linked to a topic
1163
 *
1164
 * @param int $id_topic
1165
 *
1166
 * @return array
1167
 * @package Calendar
1168
 *
1169
 */
1170
function eventInfoForTopic($id_topic)
1171
{
1172
	$db = database();
1173
1174
	// Get event for this topic. If we have one.
1175
	return $db->fetchQuery('
1176
		SELECT 
1177
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, mem.real_name
1178
		FROM {db_prefix}calendar AS cal
1179
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = cal.id_member)
1180
		WHERE cal.id_topic = {int:current_topic}
1181
		ORDER BY start_date',
1182
		array(
1183
			'current_topic' => $id_topic,
1184
		)
1185
	)->fetch_all();
1186
}
1187
1188
/**
1189
 * Gets all of the holidays for the listing
1190
 *
1191
 * @param int $start The item to start with (for pagination purposes)
1192
 * @param int $items_per_page The number of items to show per page
1193
 * @param string $sort A string indicating how to sort the results
1194
 * @return array
1195
 * @package Calendar
1196
 */
1197
function list_getHolidays($start, $items_per_page, $sort)
1198
{
1199
	$db = database();
1200
1201
	return $db->fetchQuery('
1202
		SELECT 
1203
			id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
1204
		FROM {db_prefix}calendar_holidays
1205
		ORDER BY {raw:sort}
1206
		LIMIT ' . $items_per_page . ' OFFSET ' . $start,
1207
		array(
1208
			'sort' => $sort,
1209
		)
1210
	)->fetch_all();
1211
}
1212
1213
/**
1214
 * Helper function to get the total number of holidays
1215
 *
1216
 * @return int
1217
 * @package Calendar
1218
 */
1219
function list_getNumHolidays()
1220
{
1221
	$db = database();
1222
1223
	$request = $db->query('', '
1224
		SELECT 
1225
			COUNT(*)
1226
		FROM {db_prefix}calendar_holidays',
1227
		array()
1228
	);
1229
	list ($num_items) = $request->fetch_row();
1230
	$request->free_result();
1231
1232
	return (int) $num_items;
1233
}
1234
1235
/**
1236
 * Remove a holiday from the calendar.
1237
 *
1238
 * @param int|int[] $holiday_ids An array of ids for holidays.
1239
 * @package Calendar
1240
 */
1241
function removeHolidays($holiday_ids)
1242
{
1243
	$db = database();
1244
1245
	if (!is_array($holiday_ids))
1246
	{
1247
		$holiday_ids = array($holiday_ids);
1248
	}
1249
1250
	$db->query('', '
1251
		DELETE FROM {db_prefix}calendar_holidays
1252
		WHERE id_holiday IN ({array_int:id_holiday})',
1253
		array(
1254
			'id_holiday' => $holiday_ids,
1255
		)
1256
	);
1257
1258
	updateSettings(array(
1259
		'calendar_updated' => time(),
1260
	));
1261
}
1262
1263
/**
1264
 * Updates a calendar holiday
1265
 *
1266
 * @param int $holiday
1267
 * @param int $date
1268
 * @param string $title
1269
 * @package Calendar
1270
 */
1271
function editHoliday($holiday, $date, $title)
1272
{
1273
	$db = database();
1274
1275
	$db->query('', '
1276
		UPDATE {db_prefix}calendar_holidays
1277
		SET 
1278
			event_date = {date:holiday_date}, title = {string:holiday_title}
1279
		WHERE id_holiday = {int:selected_holiday}',
1280
		array(
1281
			'holiday_date' => $date,
1282
			'selected_holiday' => $holiday,
1283
			'holiday_title' => $title,
1284
		)
1285
	);
1286
1287
	updateSettings(array(
1288
		'calendar_updated' => time(),
1289
	));
1290
}
1291
1292
/**
1293
 * Insert a new holiday
1294
 *
1295
 * @param int $date
1296
 * @param string $title
1297
 * @package Calendar
1298
 */
1299
function insertHoliday($date, $title)
1300
{
1301
	$db = database();
1302
1303
	$db->insert('',
1304
		'{db_prefix}calendar_holidays',
1305
		array(
1306
			'event_date' => 'date', 'title' => 'string-60',
1307
		),
1308
		array(
1309
			$date, $title,
1310
		),
1311
		array('id_holiday')
1312
	);
1313
1314
	updateSettings(array(
1315
		'calendar_updated' => time(),
1316
	));
1317
}
1318
1319
/**
1320
 * Get a specific holiday
1321
 *
1322
 * @param int $id_holiday
1323
 * @return array
1324
 * @package Calendar
1325
 */
1326
function getHoliday($id_holiday)
1327
{
1328
	$db = database();
1329
1330
	$db->fetchQuery('
1331
		SELECT 
1332
			id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
1333
		FROM {db_prefix}calendar_holidays
1334
		WHERE id_holiday = {int:selected_holiday}
1335
		LIMIT 1',
1336
		array(
1337
			'selected_holiday' => $id_holiday,
1338
		)
1339
	)->fetch_callback(
1340
		function ($row) use (&$holiday) {
1341
			$holiday = array(
1342
				'id' => $row['id_holiday'],
1343
				'day' => (int) $row['day'],
1344
				'month' => (int) $row['month'],
1345
				'year' => $row['year'] <= 4 ? 0 : (int) $row['year'],
1346
				'title' => $row['title']
1347
			);
1348
		}
1349
	);
1350
1351
	return $holiday;
1352
}
1353
1354
/**
1355
 * Puts together the content of an ical thing
1356
 *
1357
 * @param mixed[] $event - An array holding event details like:
1358
 *                  - long
1359
 *                  - year
1360
 *                  - month
1361
 *                  - day
1362
 *                  - span
1363
 *                  - realname
1364
 *                  - sequence
1365
 *                  - eventid
1366
 *
1367
 * @return string
1368
 */
1369
function build_ical_content($event)
1370
{
1371
	global $webmaster_email, $mbname;
1372
1373
	// Check the title isn't too long - iCal requires some formatting if so.
1374
	$title = str_split($event['title'], 30);
1375
	foreach ($title as $id => $line)
1376
	{
1377
		if ($id != 0)
1378
		{
1379
			$title[$id] = ' ' . $title[$id];
1380
		}
1381
		$title[$id] .= "\n";
1382
	}
1383
1384
	// Format the dates.
1385
	$datestamp = date('Ymd\THis\Z', time());
1386
	$datestart = $event['year'] . ($event['month'] < 10 ? '0' . $event['month'] : $event['month']) . ($event['day'] < 10 ? '0' . $event['day'] : $event['day']);
1387
1388
	// Do we have a event that spans several days?
1389
	if ($event['span'] > 1)
1390
	{
1391
		$dateend = strtotime($event['year'] . '-' . ($event['month'] < 10 ? '0' . $event['month'] : $event['month']) . '-' . ($event['day'] < 10 ? '0' . $event['day'] : $event['day']));
1392
		$dateend += ($event['span'] - 1) * 86400;
1393
		$dateend = date('Ymd', $dateend);
1394
	}
1395
1396
	// This is what we will be sending later
1397
	$filecontents = 'BEGIN:VCALENDAR' . "\n";
1398
	$filecontents .= 'METHOD:PUBLISH' . "\n";
1399
	$filecontents .= 'PRODID:-//ElkArteCommunity//ElkArte ' . (!defined('FORUM_VERSION') ? 2.0 : strtr(FORUM_VERSION, array('ElkArte ' => ''))) . '//EN' . "\n";
1400
	$filecontents .= 'VERSION:2.0' . "\n";
1401
	$filecontents .= 'BEGIN:VEVENT' . "\n";
1402
	$filecontents .= 'ORGANIZER;CN="' . $event['realname'] . '":MAILTO:' . $webmaster_email . "\n";
1403
	$filecontents .= 'DTSTAMP:' . $datestamp . "\n";
1404
	$filecontents .= 'DTSTART;VALUE=DATE:' . $datestart . "\n";
1405
1406
	// more than one day
1407
	if ($event['span'] > 1)
1408
	{
1409
		$filecontents .= 'DTEND;VALUE=DATE:' . $dateend . "\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dateend does not seem to be defined for all execution paths leading up to this point.
Loading history...
1410
	}
1411
1412
	// event has changed? advance the sequence for this UID
1413
	if ($event['sequence'] > 0)
1414
	{
1415
		$filecontents .= 'SEQUENCE:' . $event['sequence'] . "\n";
1416
	}
1417
1418
	$filecontents .= 'SUMMARY:' . implode('', $title);
0 ignored issues
show
Bug introduced by
It seems like $title can also be of type true; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1418
	$filecontents .= 'SUMMARY:' . implode('', /** @scrutinizer ignore-type */ $title);
Loading history...
1419
	$filecontents .= 'UID:' . $event['eventid'] . '@' . str_replace(' ', '-', $mbname) . "\n";
1420
	$filecontents .= 'END:VEVENT' . "\n";
1421
	$filecontents .= 'END:VCALENDAR';
1422
1423
	return $filecontents;
1424
}
1425