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