]> git.mxchange.org Git - friendica.git/blob - mod/events.php
6ce322a4df4894ee767e5310c4ad460072986b74
[friendica.git] / mod / events.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * The events module
21  */
22
23 use Friendica\App;
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;
33 use Friendica\DI;
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;
45
46 function events_init(App $a)
47 {
48         if (!local_user()) {
49                 return;
50         }
51
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') {
55                 return;
56         }
57
58         if (empty(DI::page()['aside'])) {
59                 DI::page()['aside'] = '';
60         }
61
62         $cal_widget = CalendarExport::getHTML(local_user());
63
64         DI::page()['aside'] .= $cal_widget;
65
66         return;
67 }
68
69 function events_post(App $a)
70 {
71         Logger::debug('post', ['request' => $_REQUEST]);
72         if (!local_user()) {
73                 return;
74         }
75
76         $event_id = !empty($_POST['event_id']) ? intval($_POST['event_id']) : 0;
77         $cid = !empty($_POST['cid']) ? intval($_POST['cid']) : 0;
78         $uid = local_user();
79
80         $start_text  = Strings::escapeHtml($_REQUEST['start_text'] ?? '');
81         $finish_text = Strings::escapeHtml($_REQUEST['finish_text'] ?? '');
82
83         $nofinish = intval($_POST['nofinish'] ?? 0);
84
85         $share = intval($_POST['share'] ?? 0);
86
87         // The default setting for the `private` field in event_store() is false, so mirror that
88         $private_event = false;
89
90         $start  = DBA::NULL_DATETIME;
91         $finish = DBA::NULL_DATETIME;
92
93         if ($start_text) {
94                 $start = $start_text;
95         }
96
97         if ($finish_text) {
98                 $finish = $finish_text;
99         }
100
101         $start = DateTimeFormat::convert($start, 'UTC', $a->getTimeZone());
102         if (!$nofinish) {
103                 $finish = DateTimeFormat::convert($finish, 'UTC', $a->getTimeZone());
104         }
105
106         // Don't allow the event to finish before it begins.
107         // It won't hurt anything, but somebody will file a bug report
108         // and we'll waste a bunch of time responding to it. Time that
109         // could've been spent doing something else.
110
111         $summary  = trim($_POST['summary']  ?? '');
112         $desc     = trim($_POST['desc']     ?? '');
113         $location = trim($_POST['location'] ?? '');
114         $type     = 'event';
115
116         $params = [
117                 'summary'     => $summary,
118                 'description' => $desc,
119                 'location'    => $location,
120                 'start'       => $start_text,
121                 'finish'      => $finish_text,
122                 'nofinish'    => $nofinish,
123         ];
124
125         $action = ($event_id == '') ? 'new' : 'event/' . $event_id;
126         $onerror_path = 'events/' . $action . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
127
128         if (strcmp($finish, $start) < 0 && !$nofinish) {
129                 notice(DI::l10n()->t('Event can not end before it has started.'));
130                 if (intval($_REQUEST['preview'])) {
131                         echo DI::l10n()->t('Event can not end before it has started.');
132                         exit();
133                 }
134                 DI::baseUrl()->redirect($onerror_path);
135         }
136
137         if (!$summary || ($start === DBA::NULL_DATETIME)) {
138                 notice(DI::l10n()->t('Event title and start time are required.'));
139                 if (intval($_REQUEST['preview'])) {
140                         echo DI::l10n()->t('Event title and start time are required.');
141                         exit();
142                 }
143                 DI::baseUrl()->redirect($onerror_path);
144         }
145
146         $self = \Friendica\Model\Contact::getPublicIdByUserId($uid);
147
148         $aclFormatter = DI::aclFormatter();
149
150         if ($share) {
151                 $user = User::getById($uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
152                 if (!DBA::isResult($user)) {
153                         return;
154                 }
155
156                 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
157                 $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
158                 $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
159                 $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
160
161                 $visibility = $_REQUEST['visibility'] ?? '';
162                 if ($visibility === 'public') {
163                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
164                         $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
165                 } else if ($visibility === 'custom') {
166                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
167                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
168                         // See https://github.com/friendica/friendica/issues/9672
169                         $str_contact_allow .= $aclFormatter->toString($self);
170                 }
171         } else {
172                 $str_contact_allow = $aclFormatter->toString($self);
173                 $str_group_allow = $str_contact_deny = $str_group_deny = '';
174         }
175
176         // Make sure to set the `private` field as true. This is necessary to
177         // have the posts show up correctly in Diaspora if an event is created
178         // as visible only to self at first, but then edited to display to others.
179         if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
180                 $private_event = true;
181         }
182
183         $datarray = [];
184         $datarray['start']     = $start;
185         $datarray['finish']    = $finish;
186         $datarray['summary']   = $summary;
187         $datarray['desc']      = $desc;
188         $datarray['location']  = $location;
189         $datarray['type']      = $type;
190         $datarray['nofinish']  = $nofinish;
191         $datarray['uid']       = $uid;
192         $datarray['cid']       = $cid;
193         $datarray['allow_cid'] = $str_contact_allow;
194         $datarray['allow_gid'] = $str_group_allow;
195         $datarray['deny_cid']  = $str_contact_deny;
196         $datarray['deny_gid']  = $str_group_deny;
197         $datarray['private']   = $private_event;
198         $datarray['id']        = $event_id;
199
200         if (intval($_REQUEST['preview'])) {
201                 $html = Event::getHTML($datarray);
202                 echo $html;
203                 exit();
204         }
205
206         $event_id = Event::store($datarray);
207
208         $item = ['network' => Protocol::DFRN, 'protocol' => Conversation::PARCEL_DIRECT, 'direction' => Conversation::PUSH];    
209         $item = Event::getItemArrayForId($event_id, $item);
210         if (Item::insert($item)) {
211                 $uri_id = $item['uri-id'];
212         } else {
213                 $uri_id = 0;
214         }
215
216         if (!$cid && $uri_id) {
217                 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$uri_id, (int)$uid);
218         }
219
220         DI::baseUrl()->redirect('events');
221 }
222
223 function events_content(App $a)
224 {
225         if (!local_user()) {
226                 notice(DI::l10n()->t('Permission denied.'));
227                 return Login::form();
228         }
229
230         if (DI::args()->getArgc() == 1) {
231                 $_SESSION['return_path'] = DI::args()->getCommand();
232         }
233
234         if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'ignore') && intval(DI::args()->getArgv()[2])) {
235                 DBA::update('event', ['ignore' => true], ['id' => DI::args()->getArgv()[2], 'uid' => local_user()]);
236         }
237
238         if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'unignore') && intval(DI::args()->getArgv()[2])) {
239                 DBA::update('event', ['ignore' => false], ['id' => DI::args()->getArgv()[2], 'uid' => local_user()]);
240         }
241
242         if ($a->getThemeInfoValue('events_in_profile')) {
243                 Nav::setSelected('home');
244         } else {
245                 Nav::setSelected('events');
246         }
247
248         // get the translation strings for the callendar
249         $i18n = Event::getStrings();
250
251         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.min.css');
252         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.print.min.css', 'print');
253         DI::page()->registerFooterScript('view/asset/moment/min/moment-with-locales.min.js');
254         DI::page()->registerFooterScript('view/asset/fullcalendar/dist/fullcalendar.min.js');
255
256         $htpl = Renderer::getMarkupTemplate('event_head.tpl');
257         DI::page()['htmlhead'] .= Renderer::replaceMacros($htpl, [
258                 '$module_url' => '/events',
259                 '$modparams' => 1,
260                 '$i18n' => $i18n,
261         ]);
262
263         $o = '';
264         $tabs = '';
265         // tabs
266         if ($a->getThemeInfoValue('events_in_profile')) {
267                 $tabs = BaseProfile::getTabsHTML($a, 'events', true, $a->getLoggedInUserNickname(), false);
268         }
269
270         $mode = 'view';
271         $y = 0;
272         $m = 0;
273         $ignored = !empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0;
274
275         if (DI::args()->getArgc() > 1) {
276                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'event') {
277                         $mode = 'edit';
278                         $event_id = intval(DI::args()->getArgv()[2]);
279                 }
280                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'drop') {
281                         $mode = 'drop';
282                         $event_id = intval(DI::args()->getArgv()[2]);
283                 }
284                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'copy') {
285                         $mode = 'copy';
286                         $event_id = intval(DI::args()->getArgv()[2]);
287                 }
288                 if (DI::args()->getArgv()[1] === 'new') {
289                         $mode = 'new';
290                         $event_id = 0;
291                 }
292                 if (DI::args()->getArgc() > 2 && intval(DI::args()->getArgv()[1]) && intval(DI::args()->getArgv()[2])) {
293                         $mode = 'view';
294                         $y = intval(DI::args()->getArgv()[1]);
295                         $m = intval(DI::args()->getArgv()[2]);
296                 }
297         }
298
299         // The view mode part is similiar to /mod/cal.php
300         if ($mode == 'view') {
301                 $thisyear  = DateTimeFormat::localNow('Y');
302                 $thismonth = DateTimeFormat::localNow('m');
303                 if (!$y) {
304                         $y = intval($thisyear);
305                 }
306                 if (!$m) {
307                         $m = intval($thismonth);
308                 }
309
310                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
311                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
312
313                 if ($y < 1901) {
314                         $y = 1900;
315                 }
316                 if ($y > 2099) {
317                         $y = 2100;
318                 }
319
320                 $dim    = Temporal::getDaysInMonth($y, $m);
321                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
322                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
323
324                 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] === 'json') {
325                         if (!empty($_GET['start'])) {
326                                 $start = $_GET['start'];
327                         }
328                         if (!empty($_GET['end'])) {
329                                 $finish = $_GET['end'];
330                         }
331                 }
332
333                 $start  = DateTimeFormat::utc($start);
334                 $finish = DateTimeFormat::utc($finish);
335
336
337                 // put the event parametes in an array so we can better transmit them
338                 $event_params = [
339                         'event_id'      => intval($_GET['id'] ?? 0),
340                         'start'         => $start,
341                         'finish'        => $finish,
342                         'ignore'        => $ignored,
343                 ];
344
345                 // get events by id or by date
346                 if ($event_params['event_id']) {
347                         $r = Event::getListById(local_user(), $event_params['event_id']);
348                 } else {
349                         $r = Event::getListByDate(local_user(), $event_params);
350                 }
351
352                 $links = [];
353
354                 if (DBA::isResult($r)) {
355                         $r = Event::sortByDate($r);
356                         foreach ($r as $rr) {
357                                 $j = DateTimeFormat::local($rr['start'], 'j');
358                                 if (empty($links[$j])) {
359                                         $links[$j] = DI::baseUrl() . '/' . DI::args()->getCommand() . '#link-' . $j;
360                                 }
361                         }
362                 }
363
364                 $events = [];
365
366                 // transform the event in a usable array
367                 if (DBA::isResult($r)) {
368                         $r = Event::sortByDate($r);
369                         $events = Event::prepareListForTemplate($r);
370                 }
371
372                 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] === 'json') {
373                         header('Content-Type: application/json');
374                         echo json_encode($events);
375                         exit();
376                 }
377
378                 if (!empty($_GET['id'])) {
379                         $tpl = Renderer::getMarkupTemplate("event.tpl");
380                 } else {
381                         $tpl = Renderer::getMarkupTemplate("events_js.tpl");
382                 }
383
384                 // Get rid of dashes in key names, Smarty3 can't handle them
385                 foreach ($events as $key => $event) {
386                         $event_item = [];
387                         foreach ($event['item'] as $k => $v) {
388                                 $k = str_replace('-', '_', $k);
389                                 $event_item[$k] = $v;
390                         }
391                         $events[$key]['item'] = $event_item;
392                 }
393
394                 // ACL blocks are loaded in modals in frio
395                 DI::page()->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
396                 DI::page()->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
397                 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
398                 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
399
400                 $o = Renderer::replaceMacros($tpl, [
401                         '$tabs'      => $tabs,
402                         '$title'     => DI::l10n()->t('Events'),
403                         '$view'      => DI::l10n()->t('View'),
404                         '$new_event' => [DI::baseUrl() . '/events/new', DI::l10n()->t('Create New Event'), '', ''],
405                         '$previous'  => [DI::baseUrl() . '/events/$prevyear/$prevmonth', DI::l10n()->t('Previous'), '', ''],
406                         '$next'      => [DI::baseUrl() . '/events/$nextyear/$nextmonth', DI::l10n()->t('Next'), '', ''],
407                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
408
409                         '$events'    => $events,
410
411                         '$today' => DI::l10n()->t('today'),
412                         '$month' => DI::l10n()->t('month'),
413                         '$week'  => DI::l10n()->t('week'),
414                         '$day'   => DI::l10n()->t('day'),
415                         '$list'  => DI::l10n()->t('list'),
416                 ]);
417
418                 if (!empty($_GET['id'])) {
419                         echo $o;
420                         exit();
421                 }
422
423                 return $o;
424         }
425
426         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
427                 $orig_event = DBA::selectFirst('event', [], ['id' => $event_id, 'uid' => local_user()]);
428         }
429
430         // Passed parameters overrides anything found in the DB
431         if (in_array($mode, ['edit', 'new', 'copy'])) {
432                 $share_checked = '';
433                 $share_disabled = '';
434
435                 if (empty($orig_event)) {
436                         $orig_event = User::getById(local_user(), ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);;
437                 } elseif ($orig_event['allow_cid'] !== '<' . local_user() . '>'
438                         || $orig_event['allow_gid']
439                         || $orig_event['deny_cid']
440                         || $orig_event['deny_gid']) {
441                         $share_checked = ' checked="checked" ';
442                 }
443
444                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
445                 if (!empty($_REQUEST['nofinish']))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
446                 if (!empty($_REQUEST['summary']))     {$orig_event['summary']     = $_REQUEST['summary'];}
447                 if (!empty($_REQUEST['desc']))        {$orig_event['desc']        = $_REQUEST['desc'];}
448                 if (!empty($_REQUEST['location']))    {$orig_event['location']    = $_REQUEST['location'];}
449                 if (!empty($_REQUEST['start']))       {$orig_event['start']       = $_REQUEST['start'];}
450                 if (!empty($_REQUEST['finish']))      {$orig_event['finish']      = $_REQUEST['finish'];}
451
452                 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
453
454                 $t_orig = $orig_event['summary']  ?? '';
455                 $d_orig = $orig_event['desc']     ?? '';
456                 $l_orig = $orig_event['location'] ?? '';
457                 $eid = $orig_event['id'] ?? 0;
458                 $cid = $orig_event['cid'] ?? 0;
459                 $uri = $orig_event['uri'] ?? '';
460
461                 if ($cid || $mode === 'edit') {
462                         $share_disabled = 'disabled="disabled"';
463                 }
464
465                 $sdt = $orig_event['start'] ?? 'now';
466                 $fdt = $orig_event['finish'] ?? 'now';
467
468                 $syear  = DateTimeFormat::local($sdt, 'Y');
469                 $smonth = DateTimeFormat::local($sdt, 'm');
470                 $sday   = DateTimeFormat::local($sdt, 'd');
471
472                 $shour   = !empty($orig_event) ? DateTimeFormat::local($sdt, 'H') : '00';
473                 $sminute = !empty($orig_event) ? DateTimeFormat::local($sdt, 'i') : '00';
474
475                 $fyear  = DateTimeFormat::local($fdt, 'Y');
476                 $fmonth = DateTimeFormat::local($fdt, 'm');
477                 $fday   = DateTimeFormat::local($fdt, 'd');
478
479                 $fhour   = !empty($orig_event) ? DateTimeFormat::local($fdt, 'H') : '00';
480                 $fminute = !empty($orig_event) ? DateTimeFormat::local($fdt, 'i') : '00';
481
482                 if (!$cid && in_array($mode, ['new', 'copy'])) {
483                         $acl = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($orig_event));
484                 } else {
485                         $acl = '';
486                 }
487
488                 // If we copy an old event, we need to remove the ID and URI
489                 // from the original event.
490                 if ($mode === 'copy') {
491                         $eid = 0;
492                         $uri = '';
493                 }
494
495                 $tpl = Renderer::getMarkupTemplate('event_form.tpl');
496
497                 $o .= Renderer::replaceMacros($tpl, [
498                         '$post' => DI::baseUrl() . '/events',
499                         '$eid'  => $eid,
500                         '$cid'  => $cid,
501                         '$uri'  => $uri,
502
503                         '$title' => DI::l10n()->t('Event details'),
504                         '$desc' => DI::l10n()->t('Starting date and Title are required.'),
505                         '$s_text' => DI::l10n()->t('Event Starts:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
506                         '$s_dsel' => Temporal::getDateTimeField(
507                                 new DateTime(),
508                                 DateTime::createFromFormat('Y', intval($syear) + 5),
509                                 DateTime::createFromFormat('Y-m-d H:i', "$syear-$smonth-$sday $shour:$sminute"),
510                                 DI::l10n()->t('Event Starts:'),
511                                 'start_text',
512                                 true,
513                                 true,
514                                 '',
515                                 '',
516                                 true
517                         ),
518                         '$n_text' => DI::l10n()->t('Finish date/time is not known or not relevant'),
519                         '$n_checked' => $n_checked,
520                         '$f_text' => DI::l10n()->t('Event Finishes:'),
521                         '$f_dsel' => Temporal::getDateTimeField(
522                                 new DateTime(),
523                                 DateTime::createFromFormat('Y', intval($fyear) + 5),
524                                 DateTime::createFromFormat('Y-m-d H:i', "$fyear-$fmonth-$fday $fhour:$fminute"),
525                                 DI::l10n()->t('Event Finishes:'),
526                                 'finish_text',
527                                 true,
528                                 true,
529                                 'start_text'
530                         ),
531                         '$d_text' => DI::l10n()->t('Description:'),
532                         '$d_orig' => $d_orig,
533                         '$l_text' => DI::l10n()->t('Location:'),
534                         '$l_orig' => $l_orig,
535                         '$t_text' => DI::l10n()->t('Title:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
536                         '$t_orig' => $t_orig,
537                         '$summary' => ['summary', DI::l10n()->t('Title:'), $t_orig, '', '*'],
538                         '$sh_text' => DI::l10n()->t('Share this event'),
539                         '$share' => ['share', DI::l10n()->t('Share this event'), $share_checked, '', $share_disabled],
540                         '$sh_checked' => $share_checked,
541                         '$nofinish' => ['nofinish', DI::l10n()->t('Finish date/time is not known or not relevant'), $n_checked],
542                         '$preview' => DI::l10n()->t('Preview'),
543                         '$acl' => $acl,
544                         '$submit' => DI::l10n()->t('Submit'),
545                         '$basic' => DI::l10n()->t('Basic'),
546                         '$advanced' => DI::l10n()->t('Advanced'),
547                         '$permissions' => DI::l10n()->t('Permissions'),
548                 ]);
549
550                 return $o;
551         }
552
553         // Remove an event from the calendar and its related items
554         if ($mode === 'drop' && $event_id) {
555                 $ev = Event::getListById(local_user(), $event_id);
556
557                 // Delete only real events (no birthdays)
558                 if (DBA::isResult($ev) && $ev[0]['type'] == 'event') {
559                         Item::deleteForUser(['id' => $ev[0]['itemid']], local_user());
560                 }
561
562                 if (Post::exists(['id' => $ev[0]['itemid']])) {
563                         notice(DI::l10n()->t('Failed to remove event'));
564                 }
565
566                 DI::baseUrl()->redirect('events');
567         }
568 }