]> git.mxchange.org Git - friendica.git/blob - mod/events.php
Move mod/receive to src/Module/Diaspora/receive
[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 use Friendica\Worker\Delivery;
25
26 function events_init(App $a)
27 {
28         if (!local_user()) {
29                 return;
30         }
31
32         // If it's a json request abort here because we don't
33         // need the widget data
34         if ($a->argc > 1 && $a->argv[1] === 'json') {
35                 return;
36         }
37
38         if (empty($a->page['aside'])) {
39                 $a->page['aside'] = '';
40         }
41
42         $cal_widget = CalendarExport::getHTML();
43
44         $a->page['aside'] .= $cal_widget;
45
46         return;
47 }
48
49 function events_post(App $a)
50 {
51
52         Logger::log('post: ' . print_r($_REQUEST, true), Logger::DATA);
53
54         if (!local_user()) {
55                 return;
56         }
57
58         $event_id = !empty($_POST['event_id']) ? intval($_POST['event_id']) : 0;
59         $cid = !empty($_POST['cid']) ? intval($_POST['cid']) : 0;
60         $uid = local_user();
61
62         $start_text  = Strings::escapeHtml($_REQUEST['start_text'] ?? '');
63         $finish_text = Strings::escapeHtml($_REQUEST['finish_text'] ?? '');
64
65         $adjust   = intval($_POST['adjust'] ?? 0);
66         $nofinish = intval($_POST['nofinish'] ?? 0);
67
68         // The default setting for the `private` field in event_store() is false, so mirror that
69         $private_event = false;
70
71         $start  = DBA::NULL_DATETIME;
72         $finish = DBA::NULL_DATETIME;
73
74         if ($start_text) {
75                 $start = $start_text;
76         }
77
78         if ($finish_text) {
79                 $finish = $finish_text;
80         }
81
82         if ($adjust) {
83                 $start = DateTimeFormat::convert($start, 'UTC', date_default_timezone_get());
84                 if (!$nofinish) {
85                         $finish = DateTimeFormat::convert($finish, 'UTC', date_default_timezone_get());
86                 }
87         } else {
88                 $start = DateTimeFormat::utc($start);
89                 if (!$nofinish) {
90                         $finish = DateTimeFormat::utc($finish);
91                 }
92         }
93
94         // Don't allow the event to finish before it begins.
95         // It won't hurt anything, but somebody will file a bug report
96         // and we'll waste a bunch of time responding to it. Time that
97         // could've been spent doing something else.
98
99         $summary  = trim($_POST['summary']  ?? '');
100         $desc     = trim($_POST['desc']     ?? '');
101         $location = trim($_POST['location'] ?? '');
102         $type     = 'event';
103
104         $params = [
105                 'summary'     => $summary,
106                 'description' => $desc,
107                 'location'    => $location,
108                 'start'       => $start_text,
109                 'finish'      => $finish_text,
110                 'adjust'      => $adjust,
111                 'nofinish'    => $nofinish,
112         ];
113
114         $action = ($event_id == '') ? 'new' : 'event/' . $event_id;
115         $onerror_path = 'events/' . $action . '?' . http_build_query($params, null, null, PHP_QUERY_RFC3986);
116
117         if (strcmp($finish, $start) < 0 && !$nofinish) {
118                 notice(L10n::t('Event can not end before it has started.') . EOL);
119                 if (intval($_REQUEST['preview'])) {
120                         echo L10n::t('Event can not end before it has started.');
121                         exit();
122                 }
123                 $a->internalRedirect($onerror_path);
124         }
125
126         if (!$summary || ($start === DBA::NULL_DATETIME)) {
127                 notice(L10n::t('Event title and start time are required.') . EOL);
128                 if (intval($_REQUEST['preview'])) {
129                         echo L10n::t('Event title and start time are required.');
130                         exit();
131                 }
132                 $a->internalRedirect($onerror_path);
133         }
134
135         $share = intval($_POST['share'] ?? 0);
136
137         $c = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
138                 intval(local_user())
139         );
140
141         if (DBA::isResult($c)) {
142                 $self = $c[0]['id'];
143         } else {
144                 $self = 0;
145         }
146
147
148         if ($share) {
149                 $str_group_allow   = perms2str($_POST['group_allow']   ?? '');
150                 $str_contact_allow = perms2str($_POST['contact_allow'] ?? '');
151                 $str_group_deny    = perms2str($_POST['group_deny']    ?? '');
152                 $str_contact_deny  = perms2str($_POST['contact_deny']  ?? '');
153
154                 // Undo the pseudo-contact of self, since there are real contacts now
155                 if (strpos($str_contact_allow, '<' . $self . '>') !== false) {
156                         $str_contact_allow = str_replace('<' . $self . '>', '', $str_contact_allow);
157                 }
158                 // Make sure to set the `private` field as true. This is necessary to
159                 // have the posts show up correctly in Diaspora if an event is created
160                 // as visible only to self at first, but then edited to display to others.
161                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
162                         $private_event = true;
163                 }
164         } else {
165                 // Note: do not set `private` field for self-only events. It will
166                 // keep even you from seeing them!
167                 $str_contact_allow = '<' . $self . '>';
168                 $str_group_allow = $str_contact_deny = $str_group_deny = '';
169         }
170
171
172         $datarray = [];
173         $datarray['start']     = $start;
174         $datarray['finish']    = $finish;
175         $datarray['summary']   = $summary;
176         $datarray['desc']      = $desc;
177         $datarray['location']  = $location;
178         $datarray['type']      = $type;
179         $datarray['adjust']    = $adjust;
180         $datarray['nofinish']  = $nofinish;
181         $datarray['uid']       = $uid;
182         $datarray['cid']       = $cid;
183         $datarray['allow_cid'] = $str_contact_allow;
184         $datarray['allow_gid'] = $str_group_allow;
185         $datarray['deny_cid']  = $str_contact_deny;
186         $datarray['deny_gid']  = $str_group_deny;
187         $datarray['private']   = $private_event;
188         $datarray['id']        = $event_id;
189
190         if (intval($_REQUEST['preview'])) {
191                 $html = Event::getHTML($datarray);
192                 echo $html;
193                 exit();
194         }
195
196         $item_id = Event::store($datarray);
197
198         if (!$cid) {
199                 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $item_id);
200         }
201
202         $a->internalRedirect('events');
203 }
204
205 function events_content(App $a)
206 {
207         if (!local_user()) {
208                 notice(L10n::t('Permission denied.') . EOL);
209                 return Login::form();
210         }
211
212         if ($a->argc == 1) {
213                 $_SESSION['return_path'] = $a->cmd;
214         }
215
216         if (($a->argc > 2) && ($a->argv[1] === 'ignore') && intval($a->argv[2])) {
217                 q("UPDATE `event` SET `ignore` = 1 WHERE `id` = %d AND `uid` = %d",
218                         intval($a->argv[2]),
219                         intval(local_user())
220                 );
221         }
222
223         if (($a->argc > 2) && ($a->argv[1] === 'unignore') && intval($a->argv[2])) {
224                 q("UPDATE `event` SET `ignore` = 0 WHERE `id` = %d AND `uid` = %d",
225                         intval($a->argv[2]),
226                         intval(local_user())
227                 );
228         }
229
230         if ($a->theme_events_in_profile) {
231                 Nav::setSelected('home');
232         } else {
233                 Nav::setSelected('events');
234         }
235
236         // get the translation strings for the callendar
237         $i18n = Event::getStrings();
238
239         $htpl = Renderer::getMarkupTemplate('event_head.tpl');
240         $a->page['htmlhead'] .= Renderer::replaceMacros($htpl, [
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, 'events', 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                 $dim    = Temporal::getDaysInMonth($y, $m);
304                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
305                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
306
307                 if ($a->argc > 1 && $a->argv[1] === 'json') {
308                         if (!empty($_GET['start'])) {
309                                 $start = $_GET['start'];
310                         }
311                         if (!empty($_GET['end'])) {
312                                 $finish = $_GET['end'];
313                         }
314                 }
315
316                 $start  = DateTimeFormat::utc($start);
317                 $finish = DateTimeFormat::utc($finish);
318
319                 $adjust_start  = DateTimeFormat::local($start);
320                 $adjust_finish = DateTimeFormat::local($finish);
321
322                 // put the event parametes in an array so we can better transmit them
323                 $event_params = [
324                         'event_id'      => intval($_GET['id'] ?? 0),
325                         'start'         => $start,
326                         'finish'        => $finish,
327                         'adjust_start'  => $adjust_start,
328                         'adjust_finish' => $adjust_finish,
329                         'ignore'        => $ignored,
330                 ];
331
332                 // get events by id or by date
333                 if ($event_params['event_id']) {
334                         $r = Event::getListById(local_user(), $event_params['event_id']);
335                 } else {
336                         $r = Event::getListByDate(local_user(), $event_params);
337                 }
338
339                 $links = [];
340
341                 if (DBA::isResult($r)) {
342                         $r = Event::sortByDate($r);
343                         foreach ($r as $rr) {
344                                 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
345                                 if (empty($links[$j])) {
346                                         $links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
347                                 }
348                         }
349                 }
350
351                 $events = [];
352
353                 // transform the event in a usable array
354                 if (DBA::isResult($r)) {
355                         $r = Event::sortByDate($r);
356                         $events = Event::prepareListForTemplate($r);
357                 }
358
359                 if ($a->argc > 1 && $a->argv[1] === 'json') {
360                         header('Content-Type: application/json');
361                         echo json_encode($events);
362                         exit();
363                 }
364
365                 if (!empty($_GET['id'])) {
366                         $tpl = Renderer::getMarkupTemplate("event.tpl");
367                 } else {
368                         $tpl = Renderer::getMarkupTemplate("events_js.tpl");
369                 }
370
371                 // Get rid of dashes in key names, Smarty3 can't handle them
372                 foreach ($events as $key => $event) {
373                         $event_item = [];
374                         foreach ($event['item'] as $k => $v) {
375                                 $k = str_replace('-', '_', $k);
376                                 $event_item[$k] = $v;
377                         }
378                         $events[$key]['item'] = $event_item;
379                 }
380
381                 $o = Renderer::replaceMacros($tpl, [
382                         '$tabs'      => $tabs,
383                         '$title'     => L10n::t('Events'),
384                         '$view'      => L10n::t('View'),
385                         '$new_event' => [System::baseUrl() . '/events/new', L10n::t('Create New Event'), '', ''],
386                         '$previous'  => [System::baseUrl() . '/events/$prevyear/$prevmonth', L10n::t('Previous'), '', ''],
387                         '$next'      => [System::baseUrl() . '/events/$nextyear/$nextmonth', L10n::t('Next'), '', ''],
388                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
389
390                         '$events'    => $events,
391
392                         '$today' => L10n::t('today'),
393                         '$month' => L10n::t('month'),
394                         '$week'  => L10n::t('week'),
395                         '$day'   => L10n::t('day'),
396                         '$list'  => L10n::t('list'),
397                 ]);
398
399                 if (!empty($_GET['id'])) {
400                         echo $o;
401                         exit();
402                 }
403
404                 return $o;
405         }
406
407         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
408                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
409                         intval($event_id),
410                         intval(local_user())
411                 );
412                 if (DBA::isResult($r)) {
413                         $orig_event = $r[0];
414                 }
415         }
416
417         // Passed parameters overrides anything found in the DB
418         if (in_array($mode, ['edit', 'new', 'copy'])) {
419                 if (empty($orig_event)) {
420                         $orig_event = [];
421                 }
422
423                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
424                 if (!empty($_REQUEST['nofinish']))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
425                 if (!empty($_REQUEST['adjust']))      {$orig_event['adjust']      = $_REQUEST['adjust'];}
426                 if (!empty($_REQUEST['summary']))     {$orig_event['summary']     = $_REQUEST['summary'];}
427                 if (!empty($_REQUEST['description'])) {$orig_event['description'] = $_REQUEST['description'];}
428                 if (!empty($_REQUEST['location']))    {$orig_event['location']    = $_REQUEST['location'];}
429                 if (!empty($_REQUEST['start']))       {$orig_event['start']       = $_REQUEST['start'];}
430                 if (!empty($_REQUEST['finish']))      {$orig_event['finish']      = $_REQUEST['finish'];}
431
432                 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
433                 $a_checked = (!empty($orig_event['adjust'])   ? ' checked="checked" ' : '');
434
435                 $t_orig = !empty($orig_event) ? $orig_event['summary']  : '';
436                 $d_orig = !empty($orig_event) ? $orig_event['desc']     : '';
437                 $l_orig = !empty($orig_event) ? $orig_event['location'] : '';
438                 $eid = !empty($orig_event) ? $orig_event['id']  : 0;
439                 $cid = !empty($orig_event) ? $orig_event['cid'] : 0;
440                 $uri = !empty($orig_event) ? $orig_event['uri'] : '';
441
442                 $sh_disabled = '';
443                 $sh_checked = '';
444
445                 if (!empty($orig_event)
446                         && ($orig_event['allow_cid'] !== '<' . local_user() . '>'
447                         || $orig_event['allow_gid']
448                         || $orig_event['deny_cid']
449                         || $orig_event['deny_gid']))
450                 {
451                         $sh_checked = ' checked="checked" ';
452                 }
453
454                 if ($cid || $mode === 'edit') {
455                         $sh_disabled = 'disabled="disabled"';
456                 }
457
458                 $sdt = !empty($orig_event) ? $orig_event['start']  : 'now';
459                 $fdt = !empty($orig_event) ? $orig_event['finish'] : 'now';
460
461                 $tz = date_default_timezone_get();
462                 if (!empty($orig_event)) {
463                         $tz = ($orig_event['adjust'] ? date_default_timezone_get() : 'UTC');
464                 }
465
466                 $syear  = DateTimeFormat::convert($sdt, $tz, 'UTC', 'Y');
467                 $smonth = DateTimeFormat::convert($sdt, $tz, 'UTC', 'm');
468                 $sday   = DateTimeFormat::convert($sdt, $tz, 'UTC', 'd');
469
470                 $shour   = !empty($orig_event) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'H') : '00';
471                 $sminute = !empty($orig_event) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'i') : '00';
472
473                 $fyear  = DateTimeFormat::convert($fdt, $tz, 'UTC', 'Y');
474                 $fmonth = DateTimeFormat::convert($fdt, $tz, 'UTC', 'm');
475                 $fday   = DateTimeFormat::convert($fdt, $tz, 'UTC', 'd');
476
477                 $fhour   = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'H') : '00';
478                 $fminute = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'i') : '00';
479
480                 $perms = ACL::getDefaultUserPermissions($orig_event);
481
482                 if (!$cid && in_array($mode, ['new', 'copy'])) {
483                         $acl = ACL::getFullSelectorHTML($a->user, false, $orig_event);
484                 } else {
485                         $acl = '';
486                 }
487
488                 // If we copy an old event, we need to remove the ID and URI
489                 // from the original event.
490                 if ($mode === 'copy') {
491                         $eid = 0;
492                         $uri = '';
493                 }
494
495                 $tpl = Renderer::getMarkupTemplate('event_form.tpl');
496
497                 $o .= Renderer::replaceMacros($tpl, [
498                         '$post' => System::baseUrl() . '/events',
499                         '$eid'  => $eid,
500                         '$cid'  => $cid,
501                         '$uri'  => $uri,
502
503                         '$allow_cid' => json_encode($perms['allow_cid']),
504                         '$allow_gid' => json_encode($perms['allow_gid']),
505                         '$deny_cid'  => json_encode($perms['deny_cid']),
506                         '$deny_gid'  => json_encode($perms['deny_gid']),
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'), $sh_checked, '', $sh_disabled],
547                         '$sh_checked' => $sh_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                 $a->internalRedirect('events');
577         }
578 }