]> git.mxchange.org Git - friendica.git/blob - mod/events.php
Replace remaining functions in include/datetime by Temporal methods
[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\DateTimeFormat;
16 use Friendica\Util\Temporal;
17
18 require_once 'include/bbcode.php';
19 require_once 'include/datetime.php';
20 require_once 'include/event.php';
21 require_once 'include/items.php';
22
23 function events_init(App $a) {
24         if (! local_user()) {
25                 return;
26         }
27
28         if ($a->argc > 1) {
29                 // If it's a json request abort here because we don't
30                 // need the widget data
31                 if ($a->argv[1] === 'json') {
32                         return;
33                 }
34
35                 $cal_widget = widget_events();
36
37                 if (! x($a->page,'aside')) {
38                         $a->page['aside'] = '';
39                 }
40
41                 $a->page['aside'] .= $cal_widget;
42         }
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         if (count($c)) {
128                 $self = $c[0]['id'];
129         } else {
130                 $self = 0;
131         }
132
133
134         if ($share) {
135                 $str_group_allow   = perms2str($_POST['group_allow']);
136                 $str_contact_allow = perms2str($_POST['contact_allow']);
137                 $str_group_deny    = perms2str($_POST['group_deny']);
138                 $str_contact_deny  = perms2str($_POST['contact_deny']);
139
140                 // Undo the pseudo-contact of self, since there are real contacts now
141                 if (strpos($str_contact_allow, '<' . $self . '>') !== false ) {
142                         $str_contact_allow = str_replace('<' . $self . '>', '', $str_contact_allow);
143                 }
144                 // Make sure to set the `private` field as true. This is necessary to
145                 // have the posts show up correctly in Diaspora if an event is created
146                 // as visible only to self at first, but then edited to display to others.
147                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
148                         $private_event = true;
149                 }
150         } else {
151                 // Note: do not set `private` field for self-only events. It will
152                 // keep even you from seeing them!
153                 $str_contact_allow = '<' . $self . '>';
154                 $str_group_allow = $str_contact_deny = $str_group_deny = '';
155         }
156
157
158         $datarray = [];
159         $datarray['guid']      = get_guid(32);
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) ? 1 : 0);
175         $datarray['id']        = $event_id;
176         $datarray['created']   = $created;
177         $datarray['edited']    = $edited;
178
179         if (intval($_REQUEST['preview'])) {
180                 $html = format_event_html($datarray);
181                 echo $html;
182                 killme();
183         }
184
185         $item_id = event_store($datarray);
186
187         if (! $cid) {
188                 Worker::add(PRIORITY_HIGH, "Notifier", "event", $item_id);
189         }
190
191         goaway($_SESSION['return_url']);
192 }
193
194 function events_content(App $a) {
195
196         if (! local_user()) {
197                 notice(L10n::t('Permission denied.') . EOL);
198                 return;
199         }
200
201         if ($a->argc == 1) {
202                 $_SESSION['return_url'] = System::baseUrl() . '/' . $a->cmd;
203         }
204
205         if (($a->argc > 2) && ($a->argv[1] === 'ignore') && intval($a->argv[2])) {
206                 $r = q("UPDATE `event` SET `ignore` = 1 WHERE `id` = %d AND `uid` = %d",
207                         intval($a->argv[2]),
208                         intval(local_user())
209                 );
210         }
211
212         if (($a->argc > 2) && ($a->argv[1] === 'unignore') && intval($a->argv[2])) {
213                 $r = q("UPDATE `event` SET `ignore` = 0 WHERE `id` = %d AND `uid` = %d",
214                         intval($a->argv[2]),
215                         intval(local_user())
216                 );
217         }
218
219         if ($a->theme_events_in_profile) {
220                 Nav::setSelected('home');
221         } else {
222                 Nav::setSelected('events');
223         }
224
225         // get the translation strings for the callendar
226         $i18n = get_event_strings();
227
228         $htpl = get_markup_template('event_head.tpl');
229         $a->page['htmlhead'] .= replace_macros($htpl, [
230                 '$baseurl' => System::baseUrl(),
231                 '$module_url' => '/events',
232                 '$modparams' => 1,
233                 '$i18n' => $i18n,
234         ]);
235
236         $etpl = get_markup_template('event_end.tpl');
237         $a->page['end'] .= replace_macros($etpl, [
238                 '$baseurl' => System::baseUrl(),
239         ]);
240
241         $o = '';
242         $tabs = '';
243         // tabs
244         if ($a->theme_events_in_profile) {
245                 $tabs = Profile::getTabs($a, true);
246         }
247
248         $mode = 'view';
249         $y = 0;
250         $m = 0;
251         $ignored = ((x($_REQUEST, 'ignored')) ? intval($_REQUEST['ignored']) : 0);
252
253         if ($a->argc > 1) {
254                 if ($a->argc > 2 && $a->argv[1] == 'event') {
255                         $mode = 'edit';
256                         $event_id = intval($a->argv[2]);
257                 }
258                 if ($a->argc > 2 && $a->argv[1] == 'drop') {
259                         $mode = 'drop';
260                         $event_id = intval($a->argv[2]);
261                 }
262                 if ($a->argc > 2 && $a->argv[1] == 'copy') {
263                         $mode = 'copy';
264                         $event_id = intval($a->argv[2]);
265                 }
266                 if ($a->argv[1] === 'new') {
267                         $mode = 'new';
268                         $event_id = 0;
269                 }
270                 if ($a->argc > 2 && intval($a->argv[1]) && intval($a->argv[2])) {
271                         $mode = 'view';
272                         $y = intval($a->argv[1]);
273                         $m = intval($a->argv[2]);
274                 }
275         }
276
277         // The view mode part is similiar to /mod/cal.php
278         if ($mode == 'view') {
279
280                 $thisyear  = DateTimeFormat::localNow('Y');
281                 $thismonth = DateTimeFormat::localNow('m');
282                 if (! $y) {
283                         $y = intval($thisyear);
284                 }
285                 if (! $m) {
286                         $m = intval($thismonth);
287                 }
288
289                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
290                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
291
292                 if ($y < 1901) {
293                         $y = 1900;
294                 }
295                 if ($y > 2099) {
296                         $y = 2100;
297                 }
298
299                 $nextyear = $y;
300                 $nextmonth = $m + 1;
301                 if ($nextmonth > 12) {
302                         $nextmonth = 1;
303                         $nextyear ++;
304                 }
305
306                 $prevyear = $y;
307                 if ($m > 1) {
308                         $prevmonth = $m - 1;
309                 } else {
310                         $prevmonth = 12;
311                         $prevyear --;
312                 }
313
314                 $dim    = Temporal::getDaysInMonth($y, $m);
315                 $start  = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
316                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
317
318                 if ($a->argc > 1 && $a->argv[1] === 'json') {
319                         if (x($_GET, 'start')) {
320                                 $start  = $_GET['start'];
321                         }
322                         if (x($_GET, 'end'))   {
323                                 $finish = $_GET['end'];
324                         }
325                 }
326
327                 $start  = DateTimeFormat::utc($start);
328                 $finish = DateTimeFormat::utc($finish);
329
330                 $adjust_start  = DateTimeFormat::local($start);
331                 $adjust_finish = DateTimeFormat::local($finish);
332
333                 // put the event parametes in an array so we can better transmit them
334                 $event_params = [
335                         'event_id'      => (x($_GET, 'id') ? $_GET['id'] : 0),
336                         'start'         => $start,
337                         'finish'        => $finish,
338                         'adjust_start'  => $adjust_start,
339                         'adjust_finish' => $adjust_finish,
340                         'ignored'       => $ignored,
341                 ];
342
343                 // get events by id or by date
344                 if (x($_GET, 'id')) {
345                         $r = event_by_id(local_user(), $event_params);
346                 } else {
347                         $r = events_by_date(local_user(), $event_params);
348                 }
349
350                 $links = [];
351
352                 if (DBM::is_result($r)) {
353                         $r = sort_by_date($r);
354                         foreach ($r as $rr) {
355                                 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
356                                 if (! x($links,$j)) {
357                                         $links[$j] = System::baseUrl() . '/' . $a->cmd . '#link-' . $j;
358                                 }
359                         }
360                 }
361
362                 $events = [];
363
364                 // transform the event in a usable array
365                 if (DBM::is_result($r)) {
366                         $r = sort_by_date($r);
367                         $events = process_events($r);
368                 }
369
370                 if ($a->argc > 1 && $a->argv[1] === 'json'){
371                         echo json_encode($events);
372                         killme();
373                 }
374
375                 if (x($_GET, 'id')) {
376                         $tpl =  get_markup_template("event.tpl");
377                 } else {
378                         $tpl = get_markup_template("events_js.tpl");
379                 }
380
381                 // Get rid of dashes in key names, Smarty3 can't handle them
382                 foreach ($events as $key => $event) {
383                         $event_item = [];
384                         foreach ($event['item'] as $k => $v) {
385                                 $k = str_replace('-' ,'_', $k);
386                                 $event_item[$k] = $v;
387                         }
388                         $events[$key]['item'] = $event_item;
389                 }
390
391                 $o = replace_macros($tpl, [
392                         '$baseurl'   => System::baseUrl(),
393                         '$tabs'      => $tabs,
394                         '$title'     => L10n::t('Events'),
395                         '$view'      => L10n::t('View'),
396                         '$new_event' => [System::baseUrl() . '/events/new', L10n::t('Create New Event'), '', ''],
397                         '$previous'  => [System::baseUrl() . '/events/$prevyear/$prevmonth', L10n::t('Previous'), '', ''],
398                         '$next'      => [System::baseUrl() . '/events/$nextyear/$nextmonth', L10n::t('Next'), '', ''],
399                         '$calendar'  => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
400
401                         '$events'    => $events,
402
403                         '$today' => L10n::t('today'),
404                         '$month' => L10n::t('month'),
405                         '$week'  => L10n::t('week'),
406                         '$day'   => L10n::t('day'),
407                         '$list'  => L10n::t('list'),
408                 ]);
409
410                 if (x($_GET, 'id')) {
411                         echo $o;
412                         killme();
413                 }
414
415                 return $o;
416         }
417
418         if (($mode === 'edit' || $mode === 'copy') && $event_id) {
419                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
420                         intval($event_id),
421                         intval(local_user())
422                 );
423                 if (DBM::is_result($r)) {
424                         $orig_event = $r[0];
425                 }
426         }
427
428         // Passed parameters overrides anything found in the DB
429         if (in_array($mode, ['edit', 'new', 'copy'])) {
430                 if (!x($orig_event)) {$orig_event = [];}
431                 // In case of an error the browser is redirected back here, with these parameters filled in with the previous values
432                 if (x($_REQUEST, 'nofinish'))    {$orig_event['nofinish']    = $_REQUEST['nofinish'];}
433                 if (x($_REQUEST, 'adjust'))      {$orig_event['adjust']      = $_REQUEST['adjust'];}
434                 if (x($_REQUEST, 'summary'))     {$orig_event['summary']     = $_REQUEST['summary'];}
435                 if (x($_REQUEST, 'description')) {$orig_event['description'] = $_REQUEST['description'];}
436                 if (x($_REQUEST, 'location'))    {$orig_event['location']    = $_REQUEST['location'];}
437                 if (x($_REQUEST, 'start'))       {$orig_event['start']       = $_REQUEST['start'];}
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                 require_once 'include/acl_selectors.php' ;
484
485                 $perms = get_acl_permissions($orig_event);
486
487                 if ($mode === 'new' || $mode === 'copy') {
488                         $acl = (($cid) ? '' : populate_acl(((x($orig_event)) ? $orig_event : $a->user)));
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(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),
515                         '$n_text' => L10n::t('Finish date/time is not known or not relevant'),
516                         '$n_checked' => $n_checked,
517                         '$f_text' => L10n::t('Event Finishes:'),
518                         '$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'),
519                         '$a_text' => L10n::t('Adjust for viewer timezone'),
520                         '$a_checked' => $a_checked,
521                         '$d_text' => L10n::t('Description:'),
522                         '$d_orig' => $d_orig,
523                         '$l_text' => L10n::t('Location:'),
524                         '$l_orig' => $l_orig,
525                         '$t_text' => L10n::t('Title:') . ' <span class="required" title="' . L10n::t('Required') . '">*</span>',
526                         '$t_orig' => $t_orig,
527                         '$summary' => ['summary', L10n::t('Title:'), $t_orig, '', '*'],
528                         '$sh_text' => L10n::t('Share this event'),
529                         '$share' => ['share', L10n::t('Share this event'), $sh_checked, '', $sh_disabled],
530                         '$sh_checked' => $sh_checked,
531                         '$nofinish' => ['nofinish', L10n::t('Finish date/time is not known or not relevant'), $n_checked],
532                         '$adjust' => ['adjust', L10n::t('Adjust for viewer timezone'), $a_checked],
533                         '$preview' => L10n::t('Preview'),
534                         '$acl' => $acl,
535                         '$submit' => L10n::t('Submit'),
536                         '$basic' => L10n::t('Basic'),
537                         '$advanced' => L10n::t('Advanced'),
538                         '$permissions' => L10n::t('Permissions'),
539
540                 ]);
541
542                 return $o;
543         }
544
545         // Remove an event from the calendar and its related items
546         if ($mode === 'drop' && $event_id) {
547                 $del = 0;
548
549                 $params = ['event_id' => ($event_id)];
550                 $ev = event_by_id(local_user(), $params);
551
552                 // Delete only real events (no birthdays)
553                 if (DBM::is_result($ev) && $ev[0]['type'] == 'event') {
554                         $del = Item::delete($ev[0]['itemid']);
555                 }
556
557                 if ($del == 0) {
558                         notice(L10n::t('Failed to remove event') . EOL);
559                 } else {
560                         info(L10n::t('Event removed') . EOL);
561                 }
562
563                 goaway(System::baseUrl() . '/events');
564         }
565 }