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