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