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