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