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