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