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