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