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