]> git.mxchange.org Git - friendica.git/blob - mod/events.php
Avoid a notice
[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 {
25         if (!local_user()) {
26                 return;
27         }
28
29         // If it's a json request abort here because we don't
30         // need the widget data
31         if ($a->argc > 1 && $a->argv[1] === 'json') {
32                 return;
33         }
34
35         if (empty($a->page['aside'])) {
36                 $a->page['aside'] = '';
37         }
38
39         $cal_widget = CalendarExport::getHTML();
40
41         $a->page['aside'] .= $cal_widget;
42
43         return;
44 }
45
46 function events_post(App $a)
47 {
48
49         logger('post: ' . print_r($_REQUEST, true), LOGGER_DATA);
50
51         if (!local_user()) {
52                 return;
53         }
54
55         $event_id = !empty($_POST['event_id']) ? intval($_POST['event_id']) : 0;
56         $cid = !empty($_POST['cid']) ? intval($_POST['cid']) : 0;
57         $uid = local_user();
58
59         $start_text  = escape_tags(defaults($_REQUEST, 'start_text', ''));
60         $finish_text = escape_tags(defaults($_REQUEST, 'finish_text', ''));
61
62         $adjust   = intval(defaults($_POST, 'adjust', 0));
63         $nofinish = intval(defaults($_POST, 'nofinish', 0));
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(defaults($_POST, 'summary', '')));
97         $desc     = escape_tags(trim(defaults($_POST, 'desc', '')));
98         $location = escape_tags(trim(defaults($_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(defaults($_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         $o = '';
235         $tabs = '';
236         // tabs
237         if ($a->theme_events_in_profile) {
238                 $tabs = Profile::getTabs($a, true);
239         }
240
241         $mode = 'view';
242         $y = 0;
243         $m = 0;
244         $ignored = !empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0;
245
246         if ($a->argc > 1) {
247                 if ($a->argc > 2 && $a->argv[1] == 'event') {
248                         $mode = 'edit';
249                         $event_id = intval($a->argv[2]);
250                 }
251                 if ($a->argc > 2 && $a->argv[1] == 'drop') {
252                         $mode = 'drop';
253                         $event_id = intval($a->argv[2]);
254                 }
255                 if ($a->argc > 2 && $a->argv[1] == 'copy') {
256                         $mode = 'copy';
257                         $event_id = intval($a->argv[2]);
258                 }
259                 if ($a->argv[1] === 'new') {
260                         $mode = 'new';
261                         $event_id = 0;
262                 }
263                 if ($a->argc > 2 && intval($a->argv[1]) && intval($a->argv[2])) {
264                         $mode = 'view';
265                         $y = intval($a->argv[1]);
266                         $m = intval($a->argv[2]);
267                 }
268         }
269
270         // The view mode part is similiar to /mod/cal.php
271         if ($mode == 'view') {
272                 $thisyear  = DateTimeFormat::localNow('Y');
273                 $thismonth = DateTimeFormat::localNow('m');
274                 if (!$y) {
275                         $y = intval($thisyear);
276                 }
277                 if (!$m) {
278                         $m = intval($thismonth);
279                 }
280
281                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
282                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
283
284                 if ($y < 1901) {
285                         $y = 1900;
286                 }
287                 if ($y > 2099) {
288                         $y = 2100;
289                 }
290
291                 $nextyear = $y;
292                 $nextmonth = $m + 1;
293                 if ($nextmonth > 12) {
294                         $nextmonth = 1;
295                         $nextyear ++;
296                 }
297
298                 $prevyear = $y;
299                 if ($m > 1) {
300                         $prevmonth = $m - 1;
301                 } else {
302                         $prevmonth = 12;
303                         $prevyear --;
304                 }
305
306                 $dim    = Temporal::getDaysInMonth($y, $m);
307                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
308                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
309
310                 if ($a->argc > 1 && $a->argv[1] === 'json') {
311                         if (!empty($_GET['start'])) {
312                                 $start = $_GET['start'];
313                         }
314                         if (!empty($_GET['end'])) {
315                                 $finish = $_GET['end'];
316                         }
317                 }
318
319                 $start  = DateTimeFormat::utc($start);
320                 $finish = DateTimeFormat::utc($finish);
321
322                 $adjust_start  = DateTimeFormat::local($start);
323                 $adjust_finish = DateTimeFormat::local($finish);
324
325                 // put the event parametes in an array so we can better transmit them
326                 $event_params = [
327                         'event_id'      => intval(defaults($_GET, 'id', 0)),
328                         'start'         => $start,
329                         'finish'        => $finish,
330                         'adjust_start'  => $adjust_start,
331                         'adjust_finish' => $adjust_finish,
332                         'ignore'        => $ignored,
333                 ];
334
335                 // get events by id or by date
336                 if ($event_params['event_id']) {
337                         $r = Event::getListById(local_user(), $event_params['event_id']);
338                 } else {
339                         $r = Event::getListByDate(local_user(), $event_params);
340                 }
341
342                 $links = [];
343
344                 if (DBA::isResult($r)) {
345                         $r = Event::sortByDate($r);
346                         foreach ($r as $rr) {
347                                 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
348                                 if (empty($links[$j])) {
349                                         $links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
350                                 }
351                         }
352                 }
353
354                 $events = [];
355
356                 // transform the event in a usable array
357                 if (DBA::isResult($r)) {
358                         $r = Event::sortByDate($r);
359                         $events = Event::prepareListForTemplate($r);
360                 }
361
362                 if ($a->argc > 1 && $a->argv[1] === 'json') {
363                         echo json_encode($events);
364                         killme();
365                 }
366
367                 if (!empty($_GET['id'])) {
368                         $tpl = get_markup_template("event.tpl");
369                 } else {
370                         $tpl = get_markup_template("events_js.tpl");
371                 }
372
373                 // Get rid of dashes in key names, Smarty3 can't handle them
374                 foreach ($events as $key => $event) {
375                         $event_item = [];
376                         foreach ($event['item'] as $k => $v) {
377                                 $k = str_replace('-', '_', $k);
378                                 $event_item[$k] = $v;
379                         }
380                         $events[$key]['item'] = $event_item;
381                 }
382
383                 $o = replace_macros($tpl, [
384                         '$baseurl'   => System::baseUrl(),
385                         '$tabs'      => $tabs,
386                         '$title'     => L10n::t('Events'),
387                         '$view'      => L10n::t('View'),
388                         '$new_event' => [System::baseUrl() . '/events/new', L10n::t('Create New Event'), '', ''],
389                         '$previous'  => [System::baseUrl() . '/events/$prevyear/$prevmonth', L10n::t('Previous'), '', ''],
390                         '$next'      => [System::baseUrl() . '/events/$nextyear/$nextmonth', L10n::t('Next'), '', ''],
391                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
392
393                         '$events'    => $events,
394
395                         '$today' => L10n::t('today'),
396                         '$month' => L10n::t('month'),
397                         '$week'  => L10n::t('week'),
398                         '$day'   => L10n::t('day'),
399                         '$list'  => L10n::t('list'),
400                 ]);
401
402                 if (!empty($_GET['id'])) {
403                         echo $o;
404                         killme();
405                 }
406
407                 return $o;
408         }
409
410         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
411                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
412                         intval($event_id),
413                         intval(local_user())
414                 );
415                 if (DBA::isResult($r)) {
416                         $orig_event = $r[0];
417                 }
418         }
419
420         // Passed parameters overrides anything found in the DB
421         if (in_array($mode, ['edit', 'new', 'copy'])) {
422                 if (empty($orig_event)) {
423                         $orig_event = [];
424                 }
425
426                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
427                 if (!empty($_REQUEST['nofinish']))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
428                 if (!empty($_REQUEST['adjust']))      {$orig_event['adjust']      = $_REQUEST['adjust'];}
429                 if (!empty($_REQUEST['summary']))     {$orig_event['summary']     = $_REQUEST['summary'];}
430                 if (!empty($_REQUEST['description'])) {$orig_event['description'] = $_REQUEST['description'];}
431                 if (!empty($_REQUEST['location']))    {$orig_event['location']    = $_REQUEST['location'];}
432                 if (!empty($_REQUEST['start']))       {$orig_event['start']       = $_REQUEST['start'];}
433                 if (!empty($_REQUEST['finish']))      {$orig_event['finish']      = $_REQUEST['finish'];}
434
435                 $n_checked = (!empty($orig_event['nofinish']) ? ' checked="checked" ' : '');
436                 $a_checked = (!empty($orig_event['adjust'])   ? ' checked="checked" ' : '');
437
438                 $t_orig = !empty($orig_event) ? $orig_event['summary']  : '';
439                 $d_orig = !empty($orig_event) ? $orig_event['desc']     : '';
440                 $l_orig = !empty($orig_event) ? $orig_event['location'] : '';
441                 $eid = !empty($orig_event) ? $orig_event['id']  : 0;
442                 $cid = !empty($orig_event) ? $orig_event['cid'] : 0;
443                 $uri = !empty($orig_event) ? $orig_event['uri'] : '';
444
445                 $sh_disabled = '';
446                 $sh_checked = '';
447
448                 if (!empty($orig_event)
449                         && ($orig_event['allow_cid'] !== '<' . local_user() . '>'
450                         || $orig_event['allow_gid']
451                         || $orig_event['deny_cid']
452                         || $orig_event['deny_gid']))
453                 {
454                         $sh_checked = ' checked="checked" ';
455                 }
456
457                 if ($cid || $mode === 'edit') {
458                         $sh_disabled = 'disabled="disabled"';
459                 }
460
461                 $sdt = !empty($orig_event) ? $orig_event['start']  : 'now';
462                 $fdt = !empty($orig_event) ? $orig_event['finish'] : 'now';
463
464                 $tz = date_default_timezone_get();
465                 if (!empty($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   = !empty($orig_event) ? DateTimeFormat::convert($sdt, $tz, 'UTC', 'H') : '00';
474                 $sminute = !empty($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   = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'H') : '00';
481                 $fminute = !empty($orig_event) ? DateTimeFormat::convert($fdt, $tz, 'UTC', 'i') : '00';
482
483                 $perms = ACL::getDefaultUserPermissions($orig_event);
484
485                 if (!$cid && in_array($mode, ['new', 'copy'])) {
486                         $acl = ACL::getFullSelectorHTML($a->user, false, $orig_event);
487                 } else {
488                         $acl = '';
489                 }
490
491                 // If we copy an old event, we need to remove the ID and URI
492                 // from the original event.
493                 if ($mode === 'copy') {
494                         $eid = 0;
495                         $uri = '';
496                 }
497
498                 $tpl = get_markup_template('event_form.tpl');
499
500                 $o .= replace_macros($tpl, [
501                         '$post' => System::baseUrl() . '/events',
502                         '$eid'  => $eid,
503                         '$cid'  => $cid,
504                         '$uri'  => $uri,
505
506                         '$allow_cid' => json_encode($perms['allow_cid']),
507                         '$allow_gid' => json_encode($perms['allow_gid']),
508                         '$deny_cid'  => json_encode($perms['deny_cid']),
509                         '$deny_gid'  => json_encode($perms['deny_gid']),
510
511                         '$title' => L10n::t('Event details'),
512                         '$desc' => L10n::t('Starting date and Title are required.'),
513                         '$s_text' => L10n::t('Event Starts:') . ' <span class="required" title="' . L10n::t('Required') . '">*</span>',
514                         '$s_dsel' => Temporal::getDateTimeField(
515                                 new DateTime(),
516                                 DateTime::createFromFormat('Y', $syear+5),
517                                 DateTime::createFromFormat('Y-m-d H:i', "$syear-$smonth-$sday $shour:$sminute"),
518                                 L10n::t('Event Starts:'),
519                                 'start_text',
520                                 true,
521                                 true,
522                                 '',
523                                 '',
524                                 true
525                         ),
526                         '$n_text' => L10n::t('Finish date/time is not known or not relevant'),
527                         '$n_checked' => $n_checked,
528                         '$f_text' => L10n::t('Event Finishes:'),
529                         '$f_dsel' => Temporal::getDateTimeField(
530                                 new DateTime(),
531                                 DateTime::createFromFormat('Y', $fyear+5),
532                                 DateTime::createFromFormat('Y-m-d H:i', "$fyear-$fmonth-$fday $fhour:$fminute"),
533                                 L10n::t('Event Finishes:'),
534                                 'finish_text',
535                                 true,
536                                 true,
537                                 'start_text'
538                         ),
539                         '$a_text' => L10n::t('Adjust for viewer timezone'),
540                         '$a_checked' => $a_checked,
541                         '$d_text' => L10n::t('Description:'),
542                         '$d_orig' => $d_orig,
543                         '$l_text' => L10n::t('Location:'),
544                         '$l_orig' => $l_orig,
545                         '$t_text' => L10n::t('Title:') . ' <span class="required" title="' . L10n::t('Required') . '">*</span>',
546                         '$t_orig' => $t_orig,
547                         '$summary' => ['summary', L10n::t('Title:'), $t_orig, '', '*'],
548                         '$sh_text' => L10n::t('Share this event'),
549                         '$share' => ['share', L10n::t('Share this event'), $sh_checked, '', $sh_disabled],
550                         '$sh_checked' => $sh_checked,
551                         '$nofinish' => ['nofinish', L10n::t('Finish date/time is not known or not relevant'), $n_checked],
552                         '$adjust' => ['adjust', L10n::t('Adjust for viewer timezone'), $a_checked],
553                         '$preview' => L10n::t('Preview'),
554                         '$acl' => $acl,
555                         '$submit' => L10n::t('Submit'),
556                         '$basic' => L10n::t('Basic'),
557                         '$advanced' => L10n::t('Advanced'),
558                         '$permissions' => L10n::t('Permissions'),
559                 ]);
560
561                 return $o;
562         }
563
564         // Remove an event from the calendar and its related items
565         if ($mode === 'drop' && $event_id) {
566                 $ev = Event::getListById(local_user(), $event_id);
567
568                 // Delete only real events (no birthdays)
569                 if (DBA::isResult($ev) && $ev[0]['type'] == 'event') {
570                         Item::deleteForUser(['id' => $ev[0]['itemid']], local_user());
571                 }
572
573                 if (Item::exists(['id' => $ev[0]['itemid']])) {
574                         notice(L10n::t('Failed to remove event') . EOL);
575                 } else {
576                         info(L10n::t('Event removed') . EOL);
577                 }
578
579                 goaway(System::baseUrl() . '/events');
580         }
581 }