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