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