]> git.mxchange.org Git - friendica.git/blob - mod/events.php
Merge pull request #1 from friendica/develop
[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\BaseObject;
9 use Friendica\Content\Nav;
10 use Friendica\Content\Widget\CalendarExport;
11 use Friendica\Core\ACL;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Event;
19 use Friendica\Model\Item;
20 use Friendica\Model\Profile;
21 use Friendica\Module\Login;
22 use Friendica\Util\ACLFormatter;
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($a->page['aside'])) {
41                 $a->page['aside'] = '';
42         }
43
44         $cal_widget = CalendarExport::getHTML();
45
46         $a->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                 $a->internalRedirect($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                 $a->internalRedirect($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                 /** @var ACLFormatter $aclFormatter */
153                 $aclFormatter = BaseObject::getClass(ACLFormatter::class);
154
155                 $str_group_allow   = $aclFormatter->toString($_POST['group_allow'] ?? '');
156                 $str_contact_allow = $aclFormatter->toString($_POST['contact_allow'] ?? '');
157                 $str_group_deny    = $aclFormatter->toString($_POST['group_deny'] ?? '');
158                 $str_contact_deny  = $aclFormatter->toString($_POST['contact_deny'] ?? '');
159
160                 // Undo the pseudo-contact of self, since there are real contacts now
161                 if (strpos($str_contact_allow, '<' . $self . '>') !== false) {
162                         $str_contact_allow = str_replace('<' . $self . '>', '', $str_contact_allow);
163                 }
164                 // Make sure to set the `private` field as true. This is necessary to
165                 // have the posts show up correctly in Diaspora if an event is created
166                 // as visible only to self at first, but then edited to display to others.
167                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
168                         $private_event = true;
169                 }
170         } else {
171                 // Note: do not set `private` field for self-only events. It will
172                 // keep even you from seeing them!
173                 $str_contact_allow = '<' . $self . '>';
174                 $str_group_allow = $str_contact_deny = $str_group_deny = '';
175         }
176
177
178         $datarray = [];
179         $datarray['start']     = $start;
180         $datarray['finish']    = $finish;
181         $datarray['summary']   = $summary;
182         $datarray['desc']      = $desc;
183         $datarray['location']  = $location;
184         $datarray['type']      = $type;
185         $datarray['adjust']    = $adjust;
186         $datarray['nofinish']  = $nofinish;
187         $datarray['uid']       = $uid;
188         $datarray['cid']       = $cid;
189         $datarray['allow_cid'] = $str_contact_allow;
190         $datarray['allow_gid'] = $str_group_allow;
191         $datarray['deny_cid']  = $str_contact_deny;
192         $datarray['deny_gid']  = $str_group_deny;
193         $datarray['private']   = $private_event;
194         $datarray['id']        = $event_id;
195
196         if (intval($_REQUEST['preview'])) {
197                 $html = Event::getHTML($datarray);
198                 echo $html;
199                 exit();
200         }
201
202         $item_id = Event::store($datarray);
203
204         if (!$cid) {
205                 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $item_id);
206         }
207
208         $a->internalRedirect('events');
209 }
210
211 function events_content(App $a)
212 {
213         if (!local_user()) {
214                 notice(L10n::t('Permission denied.') . EOL);
215                 return Login::form();
216         }
217
218         if ($a->argc == 1) {
219                 $_SESSION['return_path'] = $a->cmd;
220         }
221
222         if (($a->argc > 2) && ($a->argv[1] === 'ignore') && intval($a->argv[2])) {
223                 q("UPDATE `event` SET `ignore` = 1 WHERE `id` = %d AND `uid` = %d",
224                         intval($a->argv[2]),
225                         intval(local_user())
226                 );
227         }
228
229         if (($a->argc > 2) && ($a->argv[1] === 'unignore') && intval($a->argv[2])) {
230                 q("UPDATE `event` SET `ignore` = 0 WHERE `id` = %d AND `uid` = %d",
231                         intval($a->argv[2]),
232                         intval(local_user())
233                 );
234         }
235
236         if ($a->theme_events_in_profile) {
237                 Nav::setSelected('home');
238         } else {
239                 Nav::setSelected('events');
240         }
241
242         // get the translation strings for the callendar
243         $i18n = Event::getStrings();
244
245         $htpl = Renderer::getMarkupTemplate('event_head.tpl');
246         $a->page['htmlhead'] .= Renderer::replaceMacros($htpl, [
247                 '$module_url' => '/events',
248                 '$modparams' => 1,
249                 '$i18n' => $i18n,
250         ]);
251
252         $o = '';
253         $tabs = '';
254         // tabs
255         if ($a->theme_events_in_profile) {
256                 $tabs = Profile::getTabs($a, 'events', true);
257         }
258
259         $mode = 'view';
260         $y = 0;
261         $m = 0;
262         $ignored = !empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0;
263
264         if ($a->argc > 1) {
265                 if ($a->argc > 2 && $a->argv[1] == 'event') {
266                         $mode = 'edit';
267                         $event_id = intval($a->argv[2]);
268                 }
269                 if ($a->argc > 2 && $a->argv[1] == 'drop') {
270                         $mode = 'drop';
271                         $event_id = intval($a->argv[2]);
272                 }
273                 if ($a->argc > 2 && $a->argv[1] == 'copy') {
274                         $mode = 'copy';
275                         $event_id = intval($a->argv[2]);
276                 }
277                 if ($a->argv[1] === 'new') {
278                         $mode = 'new';
279                         $event_id = 0;
280                 }
281                 if ($a->argc > 2 && intval($a->argv[1]) && intval($a->argv[2])) {
282                         $mode = 'view';
283                         $y = intval($a->argv[1]);
284                         $m = intval($a->argv[2]);
285                 }
286         }
287
288         // The view mode part is similiar to /mod/cal.php
289         if ($mode == 'view') {
290                 $thisyear  = DateTimeFormat::localNow('Y');
291                 $thismonth = DateTimeFormat::localNow('m');
292                 if (!$y) {
293                         $y = intval($thisyear);
294                 }
295                 if (!$m) {
296                         $m = intval($thismonth);
297                 }
298
299                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
300                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
301
302                 if ($y < 1901) {
303                         $y = 1900;
304                 }
305                 if ($y > 2099) {
306                         $y = 2100;
307                 }
308
309                 $dim    = Temporal::getDaysInMonth($y, $m);
310                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
311                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
312
313                 if ($a->argc > 1 && $a->argv[1] === 'json') {
314                         if (!empty($_GET['start'])) {
315                                 $start = $_GET['start'];
316                         }
317                         if (!empty($_GET['end'])) {
318                                 $finish = $_GET['end'];
319                         }
320                 }
321
322                 $start  = DateTimeFormat::utc($start);
323                 $finish = DateTimeFormat::utc($finish);
324
325                 $adjust_start  = DateTimeFormat::local($start);
326                 $adjust_finish = DateTimeFormat::local($finish);
327
328                 // put the event parametes in an array so we can better transmit them
329                 $event_params = [
330                         'event_id'      => intval($_GET['id'] ?? 0),
331                         'start'         => $start,
332                         'finish'        => $finish,
333                         'adjust_start'  => $adjust_start,
334                         'adjust_finish' => $adjust_finish,
335                         'ignore'        => $ignored,
336                 ];
337
338                 // get events by id or by date
339                 if ($event_params['event_id']) {
340                         $r = Event::getListById(local_user(), $event_params['event_id']);
341                 } else {
342                         $r = Event::getListByDate(local_user(), $event_params);
343                 }
344
345                 $links = [];
346
347                 if (DBA::isResult($r)) {
348                         $r = Event::sortByDate($r);
349                         foreach ($r as $rr) {
350                                 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
351                                 if (empty($links[$j])) {
352                                         $links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
353                                 }
354                         }
355                 }
356
357                 $events = [];
358
359                 // transform the event in a usable array
360                 if (DBA::isResult($r)) {
361                         $r = Event::sortByDate($r);
362                         $events = Event::prepareListForTemplate($r);
363                 }
364
365                 if ($a->argc > 1 && $a->argv[1] === 'json') {
366                         header('Content-Type: application/json');
367                         echo json_encode($events);
368                         exit();
369                 }
370
371                 if (!empty($_GET['id'])) {
372                         $tpl = Renderer::getMarkupTemplate("event.tpl");
373                 } else {
374                         $tpl = Renderer::getMarkupTemplate("events_js.tpl");
375                 }
376
377                 // Get rid of dashes in key names, Smarty3 can't handle them
378                 foreach ($events as $key => $event) {
379                         $event_item = [];
380                         foreach ($event['item'] as $k => $v) {
381                                 $k = str_replace('-', '_', $k);
382                                 $event_item[$k] = $v;
383                         }
384                         $events[$key]['item'] = $event_item;
385                 }
386
387                 $o = Renderer::replaceMacros($tpl, [
388                         '$tabs'      => $tabs,
389                         '$title'     => L10n::t('Events'),
390                         '$view'      => L10n::t('View'),
391                         '$new_event' => [System::baseUrl() . '/events/new', L10n::t('Create New Event'), '', ''],
392                         '$previous'  => [System::baseUrl() . '/events/$prevyear/$prevmonth', L10n::t('Previous'), '', ''],
393                         '$next'      => [System::baseUrl() . '/events/$nextyear/$nextmonth', L10n::t('Next'), '', ''],
394                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
395
396                         '$events'    => $events,
397
398                         '$today' => L10n::t('today'),
399                         '$month' => L10n::t('month'),
400                         '$week'  => L10n::t('week'),
401                         '$day'   => L10n::t('day'),
402                         '$list'  => L10n::t('list'),
403                 ]);
404
405                 if (!empty($_GET['id'])) {
406                         echo $o;
407                         exit();
408                 }
409
410                 return $o;
411         }
412
413         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
414                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
415                         intval($event_id),
416                         intval(local_user())
417                 );
418                 if (DBA::isResult($r)) {
419                         $orig_event = $r[0];
420                 }
421         }
422
423         // Passed parameters overrides anything found in the DB
424         if (in_array($mode, ['edit', 'new', 'copy'])) {
425                 if (empty($orig_event)) {
426                         $orig_event = [];
427                 }
428
429                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
430                 if (!empty($_REQUEST['nofinish']))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
431                 if (!empty($_REQUEST['adjust']))      {$orig_event['adjust']      = $_REQUEST['adjust'];}
432                 if (!empty($_REQUEST['summary']))     {$orig_event['summary']     = $_REQUEST['summary'];}
433                 if (!empty($_REQUEST['description'])) {$orig_event['description'] = $_REQUEST['description'];}
434                 if (!empty($_REQUEST['location']))    {$orig_event['location']    = $_REQUEST['location'];}
435                 if (!empty($_REQUEST['start']))       {$orig_event['start']       = $_REQUEST['start'];}
436                 if (!empty($_REQUEST['finish']))      {$orig_event['finish']      = $_REQUEST['finish'];}
437
438                 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
439                 $a_checked = (!empty($orig_event['adjust'])   ? ' checked="checked" ' : '');
440
441                 $t_orig = !empty($orig_event) ? $orig_event['summary']  : '';
442                 $d_orig = !empty($orig_event) ? $orig_event['desc']     : '';
443                 $l_orig = !empty($orig_event) ? $orig_event['location'] : '';
444                 $eid = !empty($orig_event) ? $orig_event['id']  : 0;
445                 $cid = !empty($orig_event) ? $orig_event['cid'] : 0;
446                 $uri = !empty($orig_event) ? $orig_event['uri'] : '';
447
448                 $sh_disabled = '';
449                 $sh_checked = '';
450
451                 if (!empty($orig_event)
452                         && ($orig_event['allow_cid'] !== '<' . local_user() . '>'
453                         || $orig_event['allow_gid']
454                         || $orig_event['deny_cid']
455                         || $orig_event['deny_gid']))
456                 {
457                         $sh_checked = ' checked="checked" ';
458                 }
459
460                 if ($cid || $mode === 'edit') {
461                         $sh_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                 $perms = ACL::getDefaultUserPermissions($orig_event);
487
488                 if (!$cid && in_array($mode, ['new', 'copy'])) {
489                         $acl = ACL::getFullSelectorHTML($a->user, false, $orig_event);
490                 } else {
491                         $acl = '';
492                 }
493
494                 // If we copy an old event, we need to remove the ID and URI
495                 // from the original event.
496                 if ($mode === 'copy') {
497                         $eid = 0;
498                         $uri = '';
499                 }
500
501                 $tpl = Renderer::getMarkupTemplate('event_form.tpl');
502
503                 $o .= Renderer::replaceMacros($tpl, [
504                         '$post' => System::baseUrl() . '/events',
505                         '$eid'  => $eid,
506                         '$cid'  => $cid,
507                         '$uri'  => $uri,
508
509                         '$allow_cid' => json_encode($perms['allow_cid']),
510                         '$allow_gid' => json_encode($perms['allow_gid']),
511                         '$deny_cid'  => json_encode($perms['deny_cid']),
512                         '$deny_gid'  => json_encode($perms['deny_gid']),
513
514                         '$title' => L10n::t('Event details'),
515                         '$desc' => L10n::t('Starting date and Title are required.'),
516                         '$s_text' => L10n::t('Event Starts:') . ' <span class="required" title="' . L10n::t('Required') . '">*</span>',
517                         '$s_dsel' => Temporal::getDateTimeField(
518                                 new DateTime(),
519                                 DateTime::createFromFormat('Y', intval($syear) + 5),
520                                 DateTime::createFromFormat('Y-m-d H:i', "$syear-$smonth-$sday $shour:$sminute"),
521                                 L10n::t('Event Starts:'),
522                                 'start_text',
523                                 true,
524                                 true,
525                                 '',
526                                 '',
527                                 true
528                         ),
529                         '$n_text' => L10n::t('Finish date/time is not known or not relevant'),
530                         '$n_checked' => $n_checked,
531                         '$f_text' => L10n::t('Event Finishes:'),
532                         '$f_dsel' => Temporal::getDateTimeField(
533                                 new DateTime(),
534                                 DateTime::createFromFormat('Y', intval($fyear) + 5),
535                                 DateTime::createFromFormat('Y-m-d H:i', "$fyear-$fmonth-$fday $fhour:$fminute"),
536                                 L10n::t('Event Finishes:'),
537                                 'finish_text',
538                                 true,
539                                 true,
540                                 'start_text'
541                         ),
542                         '$a_text' => L10n::t('Adjust for viewer timezone'),
543                         '$a_checked' => $a_checked,
544                         '$d_text' => L10n::t('Description:'),
545                         '$d_orig' => $d_orig,
546                         '$l_text' => L10n::t('Location:'),
547                         '$l_orig' => $l_orig,
548                         '$t_text' => L10n::t('Title:') . ' <span class="required" title="' . L10n::t('Required') . '">*</span>',
549                         '$t_orig' => $t_orig,
550                         '$summary' => ['summary', L10n::t('Title:'), $t_orig, '', '*'],
551                         '$sh_text' => L10n::t('Share this event'),
552                         '$share' => ['share', L10n::t('Share this event'), $sh_checked, '', $sh_disabled],
553                         '$sh_checked' => $sh_checked,
554                         '$nofinish' => ['nofinish', L10n::t('Finish date/time is not known or not relevant'), $n_checked],
555                         '$adjust' => ['adjust', L10n::t('Adjust for viewer timezone'), $a_checked],
556                         '$preview' => L10n::t('Preview'),
557                         '$acl' => $acl,
558                         '$submit' => L10n::t('Submit'),
559                         '$basic' => L10n::t('Basic'),
560                         '$advanced' => L10n::t('Advanced'),
561                         '$permissions' => L10n::t('Permissions'),
562                 ]);
563
564                 return $o;
565         }
566
567         // Remove an event from the calendar and its related items
568         if ($mode === 'drop' && $event_id) {
569                 $ev = Event::getListById(local_user(), $event_id);
570
571                 // Delete only real events (no birthdays)
572                 if (DBA::isResult($ev) && $ev[0]['type'] == 'event') {
573                         Item::deleteForUser(['id' => $ev[0]['itemid']], local_user());
574                 }
575
576                 if (Item::exists(['id' => $ev[0]['itemid']])) {
577                         notice(L10n::t('Failed to remove event') . EOL);
578                 } else {
579                         info(L10n::t('Event removed') . EOL);
580                 }
581
582                 $a->internalRedirect('events');
583         }
584 }