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