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