]> git.mxchange.org Git - friendica.git/blob - mod/events.php
Avoid warning "Undefined namespace prefix"
[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 (!local_user()) {
50                 return;
51         }
52
53         if (empty(DI::page()['aside'])) {
54                 DI::page()['aside'] = '';
55         }
56
57         $cal_widget = CalendarExport::getHTML(local_user());
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 (!local_user()) {
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 = local_user();
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                 notice(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                 notice(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         $datarray['start']     = $start;
178         $datarray['finish']    = $finish;
179         $datarray['summary']   = $summary;
180         $datarray['desc']      = $desc;
181         $datarray['location']  = $location;
182         $datarray['type']      = $type;
183         $datarray['nofinish']  = $nofinish;
184         $datarray['uid']       = $uid;
185         $datarray['cid']       = $cid;
186         $datarray['allow_cid'] = $str_contact_allow;
187         $datarray['allow_gid'] = $str_group_allow;
188         $datarray['deny_cid']  = $str_contact_deny;
189         $datarray['deny_gid']  = $str_group_deny;
190         $datarray['private']   = $private_event;
191         $datarray['id']        = $event_id;
192
193         if (intval($_REQUEST['preview'])) {
194                 System::httpExit(Event::getHTML($datarray));
195         }
196
197         $event_id = Event::store($datarray);
198
199         $item = ['network' => Protocol::DFRN, 'protocol' => Conversation::PARCEL_DIRECT, 'direction' => Conversation::PUSH];    
200         $item = Event::getItemArrayForId($event_id, $item);
201         if (Item::insert($item)) {
202                 $uri_id = $item['uri-id'];
203         } else {
204                 $uri_id = 0;
205         }
206
207         if (!$cid && $uri_id) {
208                 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$uri_id, (int)$uid);
209         }
210
211         DI::baseUrl()->redirect('events');
212 }
213
214 function events_content(App $a)
215 {
216         if (!local_user()) {
217                 notice(DI::l10n()->t('Permission denied.'));
218                 return Login::form();
219         }
220
221         if (DI::args()->getArgc() == 1) {
222                 $_SESSION['return_path'] = DI::args()->getCommand();
223         }
224
225         if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'ignore') && intval(DI::args()->getArgv()[2])) {
226                 DBA::update('event', ['ignore' => true], ['id' => DI::args()->getArgv()[2], 'uid' => local_user()]);
227         }
228
229         if ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[1] === 'unignore') && intval(DI::args()->getArgv()[2])) {
230                 DBA::update('event', ['ignore' => false], ['id' => DI::args()->getArgv()[2], 'uid' => local_user()]);
231         }
232
233         if ($a->getThemeInfoValue('events_in_profile')) {
234                 Nav::setSelected('home');
235         } else {
236                 Nav::setSelected('events');
237         }
238
239         // get the translation strings for the callendar
240         $i18n = Event::getStrings();
241
242         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.min.css');
243         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.print.min.css', 'print');
244         DI::page()->registerFooterScript('view/asset/moment/min/moment-with-locales.min.js');
245         DI::page()->registerFooterScript('view/asset/fullcalendar/dist/fullcalendar.min.js');
246
247         $htpl = Renderer::getMarkupTemplate('event_head.tpl');
248         DI::page()['htmlhead'] .= Renderer::replaceMacros($htpl, [
249                 '$module_url' => '/events',
250                 '$modparams' => 1,
251                 '$i18n' => $i18n,
252         ]);
253
254         $o = '';
255         $tabs = '';
256         // tabs
257         if ($a->getThemeInfoValue('events_in_profile')) {
258                 $tabs = BaseProfile::getTabsHTML($a, 'events', true, $a->getLoggedInUserNickname(), false);
259         }
260
261         $mode = 'view';
262         $y = 0;
263         $m = 0;
264         $ignored = !empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0;
265
266         if (DI::args()->getArgc() > 1) {
267                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'event') {
268                         $mode = 'edit';
269                         $event_id = intval(DI::args()->getArgv()[2]);
270                 }
271                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'drop') {
272                         $mode = 'drop';
273                         $event_id = intval(DI::args()->getArgv()[2]);
274                 }
275                 if (DI::args()->getArgc() > 2 && DI::args()->getArgv()[1] == 'copy') {
276                         $mode = 'copy';
277                         $event_id = intval(DI::args()->getArgv()[2]);
278                 }
279                 if (DI::args()->getArgv()[1] === 'new') {
280                         $mode = 'new';
281                         $event_id = 0;
282                 }
283                 if (DI::args()->getArgc() > 2 && intval(DI::args()->getArgv()[1]) && intval(DI::args()->getArgv()[2])) {
284                         $mode = 'view';
285                         $y = intval(DI::args()->getArgv()[1]);
286                         $m = intval(DI::args()->getArgv()[2]);
287                 }
288         }
289
290         // The view mode part is similiar to /mod/cal.php
291         if ($mode == 'view') {
292                 $thisyear  = DateTimeFormat::localNow('Y');
293                 $thismonth = DateTimeFormat::localNow('m');
294                 if (!$y) {
295                         $y = intval($thisyear);
296                 }
297                 if (!$m) {
298                         $m = intval($thismonth);
299                 }
300
301                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
302                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
303
304                 if ($y < 1901) {
305                         $y = 1900;
306                 }
307                 if ($y > 2099) {
308                         $y = 2100;
309                 }
310
311                 $dim    = Temporal::getDaysInMonth($y, $m);
312                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
313                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
314
315                 // put the event parametes in an array so we can better transmit them
316                 $event_params = [
317                         'event_id'      => intval($_GET['id'] ?? 0),
318                         'start'         => $start,
319                         'finish'        => $finish,
320                         'ignore'        => $ignored,
321                 ];
322
323                 // get events by id or by date
324                 if ($event_params['event_id']) {
325                         $r = Event::getListById(local_user(), $event_params['event_id']);
326                 } else {
327                         $r = Event::getListByDate(local_user(), $event_params);
328                 }
329
330                 $links = [];
331
332                 if (DBA::isResult($r)) {
333                         $r = Event::sortByDate($r);
334                         foreach ($r as $rr) {
335                                 $j = DateTimeFormat::local($rr['start'], 'j');
336                                 if (empty($links[$j])) {
337                                         $links[$j] = DI::baseUrl() . '/' . DI::args()->getCommand() . '#link-' . $j;
338                                 }
339                         }
340                 }
341
342                 $events = [];
343
344                 // transform the event in a usable array
345                 if (DBA::isResult($r)) {
346                         $r = Event::sortByDate($r);
347                         $events = Event::prepareListForTemplate($r);
348                 }
349
350                 if (!empty($_GET['id'])) {
351                         $tpl = Renderer::getMarkupTemplate("event.tpl");
352                 } else {
353                         $tpl = Renderer::getMarkupTemplate("events_js.tpl");
354                 }
355
356                 // Get rid of dashes in key names, Smarty3 can't handle them
357                 foreach ($events as $key => $event) {
358                         $event_item = [];
359                         foreach ($event['item'] as $k => $v) {
360                                 $k = str_replace('-', '_', $k);
361                                 $event_item[$k] = $v;
362                         }
363                         $events[$key]['item'] = $event_item;
364                 }
365
366                 // ACL blocks are loaded in modals in frio
367                 DI::page()->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
368                 DI::page()->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
369                 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
370                 DI::page()->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
371
372                 $o = Renderer::replaceMacros($tpl, [
373                         '$tabs'      => $tabs,
374                         '$title'     => DI::l10n()->t('Events'),
375                         '$view'      => DI::l10n()->t('View'),
376                         '$new_event' => [DI::baseUrl() . '/events/new', DI::l10n()->t('Create New Event'), '', ''],
377                         '$previous'  => [DI::baseUrl() . '/events/$prevyear/$prevmonth', DI::l10n()->t('Previous'), '', ''],
378                         '$next'      => [DI::baseUrl() . '/events/$nextyear/$nextmonth', DI::l10n()->t('Next'), '', ''],
379                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
380
381                         '$events'    => $events,
382
383                         '$today' => DI::l10n()->t('today'),
384                         '$month' => DI::l10n()->t('month'),
385                         '$week'  => DI::l10n()->t('week'),
386                         '$day'   => DI::l10n()->t('day'),
387                         '$list'  => DI::l10n()->t('list'),
388                 ]);
389
390                 if (!empty($_GET['id'])) {
391                         System::httpExit($o);
392                 }
393
394                 return $o;
395         }
396
397         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
398                 $orig_event = DBA::selectFirst('event', [], ['id' => $event_id, 'uid' => local_user()]);
399         }
400
401         // Passed parameters overrides anything found in the DB
402         if (in_array($mode, ['edit', 'new', 'copy'])) {
403                 $share_checked = '';
404                 $share_disabled = '';
405
406                 if (empty($orig_event)) {
407                         $orig_event = User::getById(local_user(), ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);;
408                 } elseif ($orig_event['allow_cid'] !== '<' . local_user() . '>'
409                         || $orig_event['allow_gid']
410                         || $orig_event['deny_cid']
411                         || $orig_event['deny_gid']) {
412                         $share_checked = ' checked="checked" ';
413                 }
414
415                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
416                 if (!empty($_REQUEST['nofinish']))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
417                 if (!empty($_REQUEST['summary']))     {$orig_event['summary']     = $_REQUEST['summary'];}
418                 if (!empty($_REQUEST['desc']))        {$orig_event['desc']        = $_REQUEST['desc'];}
419                 if (!empty($_REQUEST['location']))    {$orig_event['location']    = $_REQUEST['location'];}
420                 if (!empty($_REQUEST['start']))       {$orig_event['start']       = $_REQUEST['start'];}
421                 if (!empty($_REQUEST['finish']))      {$orig_event['finish']      = $_REQUEST['finish'];}
422
423                 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
424
425                 $t_orig = $orig_event['summary']  ?? '';
426                 $d_orig = $orig_event['desc']     ?? '';
427                 $l_orig = $orig_event['location'] ?? '';
428                 $eid = $orig_event['id'] ?? 0;
429                 $cid = $orig_event['cid'] ?? 0;
430                 $uri = $orig_event['uri'] ?? '';
431
432                 if ($cid || $mode === 'edit') {
433                         $share_disabled = 'disabled="disabled"';
434                 }
435
436                 $sdt = $orig_event['start'] ?? 'now';
437                 $fdt = $orig_event['finish'] ?? 'now';
438
439                 $syear  = DateTimeFormat::local($sdt, 'Y');
440                 $smonth = DateTimeFormat::local($sdt, 'm');
441                 $sday   = DateTimeFormat::local($sdt, 'd');
442
443                 $shour   = !empty($orig_event) ? DateTimeFormat::local($sdt, 'H') : '00';
444                 $sminute = !empty($orig_event) ? DateTimeFormat::local($sdt, 'i') : '00';
445
446                 $fyear  = DateTimeFormat::local($fdt, 'Y');
447                 $fmonth = DateTimeFormat::local($fdt, 'm');
448                 $fday   = DateTimeFormat::local($fdt, 'd');
449
450                 $fhour   = !empty($orig_event) ? DateTimeFormat::local($fdt, 'H') : '00';
451                 $fminute = !empty($orig_event) ? DateTimeFormat::local($fdt, 'i') : '00';
452
453                 if (!$cid && in_array($mode, ['new', 'copy'])) {
454                         $acl = ACL::getFullSelectorHTML(DI::page(), $a->getLoggedInUserId(), false, ACL::getDefaultUserPermissions($orig_event));
455                 } else {
456                         $acl = '';
457                 }
458
459                 // If we copy an old event, we need to remove the ID and URI
460                 // from the original event.
461                 if ($mode === 'copy') {
462                         $eid = 0;
463                         $uri = '';
464                 }
465
466                 $tpl = Renderer::getMarkupTemplate('event_form.tpl');
467
468                 $o .= Renderer::replaceMacros($tpl, [
469                         '$post' => DI::baseUrl() . '/events',
470                         '$eid'  => $eid,
471                         '$cid'  => $cid,
472                         '$uri'  => $uri,
473
474                         '$title' => DI::l10n()->t('Event details'),
475                         '$desc' => DI::l10n()->t('Starting date and Title are required.'),
476                         '$s_text' => DI::l10n()->t('Event Starts:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
477                         '$s_dsel' => Temporal::getDateTimeField(
478                                 new DateTime(),
479                                 DateTime::createFromFormat('Y', intval($syear) + 5),
480                                 DateTime::createFromFormat('Y-m-d H:i', "$syear-$smonth-$sday $shour:$sminute"),
481                                 DI::l10n()->t('Event Starts:'),
482                                 'start_text',
483                                 true,
484                                 true,
485                                 '',
486                                 '',
487                                 true
488                         ),
489                         '$n_text' => DI::l10n()->t('Finish date/time is not known or not relevant'),
490                         '$n_checked' => $n_checked,
491                         '$f_text' => DI::l10n()->t('Event Finishes:'),
492                         '$f_dsel' => Temporal::getDateTimeField(
493                                 new DateTime(),
494                                 DateTime::createFromFormat('Y', intval($fyear) + 5),
495                                 DateTime::createFromFormat('Y-m-d H:i', "$fyear-$fmonth-$fday $fhour:$fminute"),
496                                 DI::l10n()->t('Event Finishes:'),
497                                 'finish_text',
498                                 true,
499                                 true,
500                                 'start_text'
501                         ),
502                         '$d_text' => DI::l10n()->t('Description:'),
503                         '$d_orig' => $d_orig,
504                         '$l_text' => DI::l10n()->t('Location:'),
505                         '$l_orig' => $l_orig,
506                         '$t_text' => DI::l10n()->t('Title:') . ' <span class="required" title="' . DI::l10n()->t('Required') . '">*</span>',
507                         '$t_orig' => $t_orig,
508                         '$summary' => ['summary', DI::l10n()->t('Title:'), $t_orig, '', '*'],
509                         '$sh_text' => DI::l10n()->t('Share this event'),
510                         '$share' => ['share', DI::l10n()->t('Share this event'), $share_checked, '', $share_disabled],
511                         '$sh_checked' => $share_checked,
512                         '$nofinish' => ['nofinish', DI::l10n()->t('Finish date/time is not known or not relevant'), $n_checked],
513                         '$preview' => DI::l10n()->t('Preview'),
514                         '$acl' => $acl,
515                         '$submit' => DI::l10n()->t('Submit'),
516                         '$basic' => DI::l10n()->t('Basic'),
517                         '$advanced' => DI::l10n()->t('Advanced'),
518                         '$permissions' => DI::l10n()->t('Permissions'),
519                 ]);
520
521                 return $o;
522         }
523
524         // Remove an event from the calendar and its related items
525         if ($mode === 'drop' && $event_id) {
526                 $ev = Event::getListById(local_user(), $event_id);
527
528                 // Delete only real events (no birthdays)
529                 if (DBA::isResult($ev) && $ev[0]['type'] == 'event') {
530                         Item::deleteForUser(['id' => $ev[0]['itemid']], local_user());
531                 }
532
533                 if (Post::exists(['id' => $ev[0]['itemid']])) {
534                         notice(DI::l10n()->t('Failed to remove event'));
535                 }
536
537                 DI::baseUrl()->redirect('events');
538         }
539 }