3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 use Friendica\Content\Nav;
25 use Friendica\Content\Widget\CalendarExport;
26 use Friendica\Core\ACL;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Theme;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\User;
39 use Friendica\Module\BaseProfile;
40 use Friendica\Module\Security\Login;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use Friendica\Worker\Delivery;
46 function events_init(App $a)
52 // If it's a json request abort here because we don't
53 // need the widget data
54 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] === 'json') {
58 if (empty(DI::page()['aside'])) {
59 DI::page()['aside'] = '';
62 $cal_widget = CalendarExport::getHTML(local_user());
64 DI::page()['aside'] .= $cal_widget;
69 function events_post(App $a)
71 Logger::debug('post', ['request' => $_REQUEST]);
76 $event_id = !empty($_POST['event_id']) ? intval($_POST['event_id']) : 0;
77 $cid = !empty($_POST['cid']) ? intval($_POST['cid']) : 0;
80 $start_text = Strings::escapeHtml($_REQUEST['start_text'] ?? '');
81 $finish_text = Strings::escapeHtml($_REQUEST['finish_text'] ?? '');
83 $adjust = intval($_POST['adjust'] ?? 0);
84 $nofinish = intval($_POST['nofinish'] ?? 0);
86 $share = intval($_POST['share'] ?? 0);
88 // The default setting for the `private` field in event_store() is false, so mirror that
89 $private_event = false;
91 $start = DBA::NULL_DATETIME;
92 $finish = DBA::NULL_DATETIME;
99 $finish = $finish_text;
103 $start = DateTimeFormat::convert($start, 'UTC', date_default_timezone_get());
105 $finish = DateTimeFormat::convert($finish, 'UTC', date_default_timezone_get());
108 $start = DateTimeFormat::utc($start);
110 $finish = DateTimeFormat::utc($finish);
114 // Don't allow the event to finish before it begins.
115 // It won't hurt anything, but somebody will file a bug report
116 // and we'll waste a bunch of time responding to it. Time that
117 // could've been spent doing something else.
119 $summary = trim($_POST['summary'] ?? '');
120 $desc = trim($_POST['desc'] ?? '');
121 $location = trim($_POST['location'] ?? '');
125 'summary' => $summary,
126 'description' => $desc,
127 'location' => $location,
128 'start' => $start_text,
129 'finish' => $finish_text,
131 'nofinish' => $nofinish,
134 $action = ($event_id == '') ? 'new' : 'event/' . $event_id;
135 $onerror_path = 'events/' . $action . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
137 if (strcmp($finish, $start) < 0 && !$nofinish) {
138 notice(DI::l10n()->t('Event can not end before it has started.'));
139 if (intval($_REQUEST['preview'])) {
140 echo DI::l10n()->t('Event can not end before it has started.');
143 DI::baseUrl()->redirect($onerror_path);
146 if (!$summary || ($start === DBA::NULL_DATETIME)) {
147 notice(DI::l10n()->t('Event title and start time are required.'));
148 if (intval($_REQUEST['preview'])) {
149 echo DI::l10n()->t('Event title and start time are required.');
152 DI::baseUrl()->redirect($onerror_path);
155 $self = \Friendica\Model\Contact::getPublicIdByUserId($uid);
157 $aclFormatter = DI::aclFormatter();
160 $user = User::getById($uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
161 if (!DBA::isResult($user)) {
165 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
166 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
167 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
168 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
170 $visibility = $_REQUEST['visibility'] ?? '';
171 if ($visibility === 'public') {
172 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
173 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
174 } else if ($visibility === 'custom') {
175 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
176 // case that would make it public. So we always append the author's contact id to the allowed contacts.
177 // See https://github.com/friendica/friendica/issues/9672
178 $str_contact_allow .= $aclFormatter->toString($self);
181 $str_contact_allow = $aclFormatter->toString($self);
182 $str_group_allow = $str_contact_deny = $str_group_deny = '';
185 // Make sure to set the `private` field as true. This is necessary to
186 // have the posts show up correctly in Diaspora if an event is created
187 // as visible only to self at first, but then edited to display to others.
188 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
189 $private_event = true;
193 $datarray['start'] = $start;
194 $datarray['finish'] = $finish;
195 $datarray['summary'] = $summary;
196 $datarray['desc'] = $desc;
197 $datarray['location'] = $location;
198 $datarray['type'] = $type;
199 $datarray['adjust'] = $adjust;
200 $datarray['nofinish'] = $nofinish;
201 $datarray['uid'] = $uid;
202 $datarray['cid'] = $cid;
203 $datarray['allow_cid'] = $str_contact_allow;
204 $datarray['allow_gid'] = $str_group_allow;
205 $datarray['deny_cid'] = $str_contact_deny;
206 $datarray['deny_gid'] = $str_group_deny;
207 $datarray['private'] = $private_event;
208 $datarray['id'] = $event_id;
210 if (intval($_REQUEST['preview'])) {
211 $html = Event::getHTML($datarray);
216 $event_id = Event::store($datarray);
218 $item = ['network' => Protocol::DFRN, 'protocol' => Conversation::PARCEL_DIRECT, 'direction' => Conversation::PUSH];
219 $item = Event::getItemArrayForId($event_id, $item);
220 if (Item::insert($item)) {
221 $uri_id = $item['uri-id'];
226 if (!$cid && $uri_id) {
227 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$uri_id, (int)$uid);
230 DI::baseUrl()->redirect('events');
233 function events_content(App $a)
236 notice(DI::l10n()->t('Permission denied.'));
237 return Login::form();
240 if (DI::args()->getArgc() == 1) {
241 $_SESSION['return_path'] = DI::args()->getCommand();
244 if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'ignore') && intval(DI::args()->getArgv()[2])) {
245 q("UPDATE `event` SET `ignore` = 1 WHERE `id` = %d AND `uid` = %d",
246 intval(DI::args()->getArgv()[2]),
251 if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'unignore') && intval(DI::args()->getArgv()[2])) {
252 q("UPDATE `event` SET `ignore` = 0 WHERE `id` = %d AND `uid` = %d",
253 intval(DI::args()->getArgv()[2]),
258 if ($a->getThemeInfoValue('events_in_profile')) {
259 Nav::setSelected('home');
261 Nav::setSelected('events');
264 // get the translation strings for the callendar
265 $i18n = Event::getStrings();
267 DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.min.css');
268 DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.print.min.css', 'print');
269 DI::page()->registerFooterScript('view/asset/moment/min/moment-with-locales.min.js');
270 DI::page()->registerFooterScript('view/asset/fullcalendar/dist/fullcalendar.min.js');
272 $htpl = Renderer::getMarkupTemplate('event_head.tpl');
273 DI::page()['htmlhead'] .= Renderer::replaceMacros($htpl, [
274 '$module_url' => '/events',
282 if ($a->getThemeInfoValue('events_in_profile')) {
283 $tabs = BaseProfile::getTabsHTML($a, 'events', true, $a->getLoggedInUserNickname(), false);
289 $ignored = !empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0;
291 if (DI::args()->getArgc() > 1) {
292 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'event') {
294 $event_id = intval(DI::args()->getArgv()[2]);
296 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'drop') {
298 $event_id = intval(DI::args()->getArgv()[2]);
300 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'copy') {
302 $event_id = intval(DI::args()->getArgv()[2]);
304 if (DI::args()->getArgv()[1] === 'new') {
308 if (DI::args()->getArgc() > 2 && intval(DI::args()->getArgv()[1]) && intval(DI::args()->getArgv()[2])) {
310 $y = intval(DI::args()->getArgv()[1]);
311 $m = intval(DI::args()->getArgv()[2]);
315 // The view mode part is similiar to /mod/cal.php
316 if ($mode == 'view') {
317 $thisyear = DateTimeFormat::localNow('Y');
318 $thismonth = DateTimeFormat::localNow('m');
320 $y = intval($thisyear);
323 $m = intval($thismonth);
326 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
327 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
336 $dim = Temporal::getDaysInMonth($y, $m);
337 $start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
338 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
340 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] === 'json') {
341 if (!empty($_GET['start'])) {
342 $start = $_GET['start'];
344 if (!empty($_GET['end'])) {
345 $finish = $_GET['end'];
349 $start = DateTimeFormat::utc($start);
350 $finish = DateTimeFormat::utc($finish);
352 $adjust_start = DateTimeFormat::local($start);
353 $adjust_finish = DateTimeFormat::local($finish);
355 // put the event parametes in an array so we can better transmit them
357 'event_id' => intval($_GET['id'] ?? 0),
360 'adjust_start' => $adjust_start,
361 'adjust_finish' => $adjust_finish,
362 'ignore' => $ignored,
365 // get events by id or by date
366 if ($event_params['event_id']) {
367 $r = Event::getListById(local_user(), $event_params['event_id']);
369 $r = Event::getListByDate(local_user(), $event_params);
374 if (DBA::isResult($r)) {
375 $r = Event::sortByDate($r);
376 foreach ($r as $rr) {
377 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
378 if (empty($links[$j])) {
379 $links[$j] = DI::baseUrl() . '/' . DI::args()->getCommand() . '#link-' . $j;
386 // transform the event in a usable array
387 if (DBA::isResult($r)) {
388 $r = Event::sortByDate($r);
389 $events = Event::prepareListForTemplate($r);
392 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] === 'json') {
393 header('Content-Type: application/json');
394 echo json_encode($events);
398 if (!empty($_GET['id'])) {
399 $tpl = Renderer::getMarkupTemplate("event.tpl");
401 $tpl = Renderer::getMarkupTemplate("events_js.tpl");
404 // Get rid of dashes in key names, Smarty3 can't handle them
405 foreach ($events as $key => $event) {
407 foreach ($event['item'] as $k => $v) {
408 $k = str_replace('-', '_', $k);
409 $event_item[$k] = $v;
411 $events[$key]['item'] = $event_item;
414 // ACL blocks are loaded in modals in frio
415 DI::page()->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
416 DI::page()->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
417 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
418 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
420 $o = Renderer::replaceMacros($tpl, [
422 '$title' => DI::l10n()->t('Events'),
423 '$view' => DI::l10n()->t('View'),
424 '$new_event' => [DI::baseUrl() . '/events/new', DI::l10n()->t('Create New Event'), '', ''],
425 '$previous' => [DI::baseUrl() . '/events/$prevyear/$prevmonth', DI::l10n()->t('Previous'), '', ''],
426 '$next' => [DI::baseUrl() . '/events/$nextyear/$nextmonth', DI::l10n()->t('Next'), '', ''],
427 '$calendar' => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
429 '$events' => $events,
431 '$today' => DI::l10n()->t('today'),
432 '$month' => DI::l10n()->t('month'),
433 '$week' => DI::l10n()->t('week'),
434 '$day' => DI::l10n()->t('day'),
435 '$list' => DI::l10n()->t('list'),
438 if (!empty($_GET['id'])) {
446 if (($mode === 'edit' || $mode === 'copy') && $event_id) {
447 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
451 if (DBA::isResult($r)) {
456 // Passed parameters overrides anything found in the DB
457 if (in_array($mode, ['edit', 'new', 'copy'])) {
459 $share_disabled = '';
461 if (empty($orig_event)) {
462 $orig_event = User::getById(local_user(), ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);;
463 } elseif ($orig_event['allow_cid'] !== '<' . local_user() . '>'
464 || $orig_event['allow_gid']
465 || $orig_event['deny_cid']
466 || $orig_event['deny_gid']) {
467 $share_checked = ' checked="checked" ';
470 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
471 if (!empty($_REQUEST['nofinish'])) {$orig_event['nofinish'] = $_REQUEST['nofinish'];}
472 if (!empty($_REQUEST['adjust'])) {$orig_event['adjust'] = $_REQUEST['adjust'];}
473 if (!empty($_REQUEST['summary'])) {$orig_event['summary'] = $_REQUEST['summary'];}
474 if (!empty($_REQUEST['desc'])) {$orig_event['desc'] = $_REQUEST['desc'];}
475 if (!empty($_REQUEST['location'])) {$orig_event['location'] = $_REQUEST['location'];}
476 if (!empty($_REQUEST['start'])) {$orig_event['start'] = $_REQUEST['start'];}
477 if (!empty($_REQUEST['finish'])) {$orig_event['finish'] = $_REQUEST['finish'];}
479 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
480 $a_checked = (!empty($orig_event['adjust']) ? ' checked="checked" ' : '');
482 $t_orig = $orig_event['summary'] ?? '';
483 $d_orig = $orig_event['desc'] ?? '';
484 $l_orig = $orig_event['location'] ?? '';
485 $eid = $orig_event['id'] ?? 0;
486 $cid = $orig_event['cid'] ?? 0;
487 $uri = $orig_event['uri'] ?? '';
489 if ($cid || $mode === 'edit') {
490 $share_disabled = 'disabled="disabled"';
493 $sdt = $orig_event['start'] ?? 'now';
494 $fdt = $orig_event['finish'] ?? 'now';
496 $tz = date_default_timezone_get();
497 if (isset($orig_event['adjust'])) {
498 $tz = ($orig_event['adjust'] ? date_default_timezone_get() : 'UTC');
501 $syear = DateTimeFormat::convert($sdt, $tz, 'UTC', 'Y');
502 $smonth = DateTimeFormat::convert($sdt, $tz, 'UTC', 'm');
503 $sday = DateTimeFormat::convert($sdt, $tz, 'UTC', 'd');
505 $shour = !empty($orig_event) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'H') : '00';
506 $sminute = !empty($orig_event) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'i') : '00';
508 $fyear = DateTimeFormat::convert($fdt, $tz, 'UTC', 'Y');
509 $fmonth = DateTimeFormat::convert($fdt, $tz, 'UTC', 'm');
510 $fday = DateTimeFormat::convert($fdt, $tz, 'UTC', 'd');
512 $fhour = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'H') : '00';
513 $fminute = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'i') : '00';
515 if (!$cid && in_array($mode, ['new', 'copy'])) {
516 $acl = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($orig_event));
521 // If we copy an old event, we need to remove the ID and URI
522 // from the original event.
523 if ($mode === 'copy') {
528 $tpl = Renderer::getMarkupTemplate('event_form.tpl');
530 $o .= Renderer::replaceMacros($tpl, [
531 '$post' => DI::baseUrl() . '/events',
536 '$title' => DI::l10n()->t('Event details'),
537 '$desc' => DI::l10n()->t('Starting date and Title are required.'),
538 '$s_text' => DI::l10n()->t('Event Starts:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
539 '$s_dsel' => Temporal::getDateTimeField(
541 DateTime::createFromFormat('Y', intval($syear) + 5),
542 DateTime::createFromFormat('Y-m-d H:i', "$syear-$smonth-$sday $shour:$sminute"),
543 DI::l10n()->t('Event Starts:'),
551 '$n_text' => DI::l10n()->t('Finish date/time is not known or not relevant'),
552 '$n_checked' => $n_checked,
553 '$f_text' => DI::l10n()->t('Event Finishes:'),
554 '$f_dsel' => Temporal::getDateTimeField(
556 DateTime::createFromFormat('Y', intval($fyear) + 5),
557 DateTime::createFromFormat('Y-m-d H:i', "$fyear-$fmonth-$fday $fhour:$fminute"),
558 DI::l10n()->t('Event Finishes:'),
564 '$a_text' => DI::l10n()->t('Adjust for viewer timezone'),
565 '$a_checked' => $a_checked,
566 '$d_text' => DI::l10n()->t('Description:'),
567 '$d_orig' => $d_orig,
568 '$l_text' => DI::l10n()->t('Location:'),
569 '$l_orig' => $l_orig,
570 '$t_text' => DI::l10n()->t('Title:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
571 '$t_orig' => $t_orig,
572 '$summary' => ['summary', DI::l10n()->t('Title:'), $t_orig, '', '*'],
573 '$sh_text' => DI::l10n()->t('Share this event'),
574 '$share' => ['share', DI::l10n()->t('Share this event'), $share_checked, '', $share_disabled],
575 '$sh_checked' => $share_checked,
576 '$nofinish' => ['nofinish', DI::l10n()->t('Finish date/time is not known or not relevant'), $n_checked],
577 '$adjust' => ['adjust', DI::l10n()->t('Adjust for viewer timezone'), $a_checked],
578 '$preview' => DI::l10n()->t('Preview'),
580 '$submit' => DI::l10n()->t('Submit'),
581 '$basic' => DI::l10n()->t('Basic'),
582 '$advanced' => DI::l10n()->t('Advanced'),
583 '$permissions' => DI::l10n()->t('Permissions'),
589 // Remove an event from the calendar and its related items
590 if ($mode === 'drop' && $event_id) {
591 $ev = Event::getListById(local_user(), $event_id);
593 // Delete only real events (no birthdays)
594 if (DBA::isResult($ev) && $ev[0]['type'] == 'event') {
595 Item::deleteForUser(['id' => $ev[0]['itemid']], local_user());
598 if (Post::exists(['id' => $ev[0]['itemid']])) {
599 notice(DI::l10n()->t('Failed to remove event'));
602 DI::baseUrl()->redirect('events');