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