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