Improve handling of the visibility parameter of the new ACL
[friendica.git/.git] / mod / cal.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * The calendar module
21  *
22  * This calendar is for profile visitors and contains only the events
23  * of the profile owner
24  */
25
26 use Friendica\App;
27 use Friendica\Content\Feature;
28 use Friendica\Content\Nav;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Content\Widget;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Session;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Event;
37 use Friendica\Model\Item;
38 use Friendica\Model\Profile;
39 use Friendica\Module\BaseProfile;
40 use Friendica\Network\HTTPException;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Temporal;
43
44 function cal_init(App $a)
45 {
46         if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
47                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
48         }
49
50         if ($a->argc < 2) {
51                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
52         }
53
54         Nav::setSelected('events');
55
56         $nick = $a->argv[1];
57         $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
58         if (!DBA::isResult($user)) {
59                 throw new HTTPException\NotFoundException();
60         }
61
62         $a->data['user'] = $user;
63         $a->profile_uid = $user['uid'];
64
65         // if it's a json request abort here becaus we don't
66         // need the widget data
67         if (!empty($a->argv[2]) && ($a->argv[2] === 'json')) {
68                 return;
69         }
70
71         $a->profile = Profile::getByNickname($nick, $a->profile_uid);
72
73         if (empty($a->profile)) {
74                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
75         }
76
77         $account_type = Contact::getAccountType($a->profile);
78
79         $tpl = Renderer::getMarkupTemplate('widget/vcard.tpl');
80
81         $vcard_widget = Renderer::replaceMacros($tpl, [
82                 '$name' => $a->profile['name'],
83                 '$photo' => $a->profile['photo'],
84                 '$addr' => $a->profile['addr'] ?: '',
85                 '$account_type' => $account_type,
86                 '$about' => BBCode::convert($a->profile['about']),
87         ]);
88
89         $cal_widget = Widget\CalendarExport::getHTML();
90
91         if (empty(DI::page()['aside'])) {
92                 DI::page()['aside'] = '';
93         }
94
95         DI::page()['aside'] .= $vcard_widget;
96         DI::page()['aside'] .= $cal_widget;
97
98         return;
99 }
100
101 function cal_content(App $a)
102 {
103         Nav::setSelected('events');
104
105         // get the translation strings for the callendar
106         $i18n = Event::getStrings();
107
108         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.min.css');
109         DI::page()->registerStylesheet('view/asset/fullcalendar/dist/fullcalendar.print.min.css', 'print');
110         DI::page()->registerFooterScript('view/asset/moment/min/moment-with-locales.min.js');
111         DI::page()->registerFooterScript('view/asset/fullcalendar/dist/fullcalendar.min.js');
112
113         $htpl = Renderer::getMarkupTemplate('event_head.tpl');
114         DI::page()['htmlhead'] .= Renderer::replaceMacros($htpl, [
115                 '$module_url' => '/cal/' . $a->data['user']['nickname'],
116                 '$modparams' => 2,
117                 '$i18n' => $i18n,
118         ]);
119
120         $mode = 'view';
121         $y = 0;
122         $m = 0;
123         $ignored = (!empty($_REQUEST['ignored']) ? intval($_REQUEST['ignored']) : 0);
124
125         $format = 'ical';
126         if ($a->argc == 4 && $a->argv[2] == 'export') {
127                 $mode = 'export';
128                 $format = $a->argv[3];
129         }
130
131         // Setup permissions structures
132         $owner_uid = intval($a->data['user']['uid']);
133         $nick = $a->data['user']['nickname'];
134
135         $contact_id = Session::getRemoteContactID($a->profile['uid']);
136
137         $remote_contact = $contact_id && DBA::exists('contact', ['id' => $contact_id, 'uid' => $a->profile['uid']]);
138
139         $is_owner = local_user() == $a->profile['uid'];
140
141         if ($a->profile['hidewall'] && !$is_owner && !$remote_contact) {
142                 notice(DI::l10n()->t('Access to this profile has been restricted.'));
143                 return;
144         }
145
146         // get the permissions
147         $sql_perms = Item::getPermissionsSQLByUserId($owner_uid);
148         // we only want to have the events of the profile owner
149         $sql_extra = " AND `event`.`cid` = 0 " . $sql_perms;
150
151         // get the tab navigation bar
152         $tabs = BaseProfile::getTabsHTML($a, 'cal', false, $a->data['user']['nickname']);
153
154         // The view mode part is similiar to /mod/events.php
155         if ($mode == 'view') {
156                 $thisyear = DateTimeFormat::localNow('Y');
157                 $thismonth = DateTimeFormat::localNow('m');
158                 if (!$y) {
159                         $y = intval($thisyear);
160                 }
161
162                 if (!$m) {
163                         $m = intval($thismonth);
164                 }
165
166                 // Put some limits on dates. The PHP date functions don't seem to do so well before 1900.
167                 // An upper limit was chosen to keep search engines from exploring links millions of years in the future.
168
169                 if ($y < 1901) {
170                         $y = 1900;
171                 }
172
173                 if ($y > 2099) {
174                         $y = 2100;
175                 }
176
177                 $nextyear = $y;
178                 $nextmonth = $m + 1;
179                 if ($nextmonth > 12) {
180                         $nextmonth = 1;
181                         $nextyear ++;
182                 }
183
184                 $prevyear = $y;
185                 if ($m > 1) {
186                         $prevmonth = $m - 1;
187                 } else {
188                         $prevmonth = 12;
189                         $prevyear --;
190                 }
191
192                 $dim = Temporal::getDaysInMonth($y, $m);
193                 $start = sprintf('%d-%d-%d %d:%d:%d', $y, $m, 1, 0, 0, 0);
194                 $finish = sprintf('%d-%d-%d %d:%d:%d', $y, $m, $dim, 23, 59, 59);
195
196
197                 if (!empty($a->argv[2]) && ($a->argv[2] === 'json')) {
198                         if (!empty($_GET['start'])) {
199                                 $start = $_GET['start'];
200                         }
201
202                         if (!empty($_GET['end'])) {
203                                 $finish = $_GET['end'];
204                         }
205                 }
206
207                 $start = DateTimeFormat::utc($start);
208                 $finish = DateTimeFormat::utc($finish);
209
210                 $adjust_start = DateTimeFormat::local($start);
211                 $adjust_finish = DateTimeFormat::local($finish);
212
213                 // put the event parametes in an array so we can better transmit them
214                 $event_params = [
215                         'event_id'      => intval($_GET['id'] ?? 0),
216                         'start'         => $start,
217                         'finish'        => $finish,
218                         'adjust_start'  => $adjust_start,
219                         'adjust_finish' => $adjust_finish,
220                         'ignore'        => $ignored,
221                 ];
222
223                 // get events by id or by date
224                 if ($event_params['event_id']) {
225                         $r = Event::getListById($owner_uid, $event_params['event_id'], $sql_extra);
226                 } else {
227                         $r = Event::getListByDate($owner_uid, $event_params, $sql_extra);
228                 }
229
230                 $links = [];
231
232                 if (DBA::isResult($r)) {
233                         $r = Event::sortByDate($r);
234                         foreach ($r as $rr) {
235                                 $j = $rr['adjust'] ? DateTimeFormat::local($rr['start'], 'j') : DateTimeFormat::utc($rr['start'], 'j');
236                                 if (empty($links[$j])) {
237                                         $links[$j] = DI::baseUrl() . '/' . DI::args()->getCommand() . '#link-' . $j;
238                                 }
239                         }
240                 }
241
242                 // transform the event in a usable array
243                 $events = Event::prepareListForTemplate($r);
244
245                 if (!empty($a->argv[2]) && ($a->argv[2] === 'json')) {
246                         echo json_encode($events);
247                         exit();
248                 }
249
250                 // links: array('href', 'text', 'extra css classes', 'title')
251                 if (!empty($_GET['id'])) {
252                         $tpl = Renderer::getMarkupTemplate("event.tpl");
253                 } else {
254 //                      if (DI::config()->get('experimentals','new_calendar')==1){
255                         $tpl = Renderer::getMarkupTemplate("events_js.tpl");
256 //                      } else {
257 //                              $tpl = Renderer::getMarkupTemplate("events.tpl");
258 //                      }
259                 }
260
261                 // Get rid of dashes in key names, Smarty3 can't handle them
262                 foreach ($events as $key => $event) {
263                         $event_item = [];
264                         foreach ($event['item'] as $k => $v) {
265                                 $k = str_replace('-', '_', $k);
266                                 $event_item[$k] = $v;
267                         }
268                         $events[$key]['item'] = $event_item;
269                 }
270
271                 $o = Renderer::replaceMacros($tpl, [
272                         '$tabs' => $tabs,
273                         '$title' => DI::l10n()->t('Events'),
274                         '$view' => DI::l10n()->t('View'),
275                         '$previous' => [DI::baseUrl() . "/events/$prevyear/$prevmonth", DI::l10n()->t('Previous'), '', ''],
276                         '$next' => [DI::baseUrl() . "/events/$nextyear/$nextmonth", DI::l10n()->t('Next'), '', ''],
277                         '$calendar' => Temporal::getCalendarTable($y, $m, $links, ' eventcal'),
278                         '$events' => $events,
279                         "today" => DI::l10n()->t("today"),
280                         "month" => DI::l10n()->t("month"),
281                         "week" => DI::l10n()->t("week"),
282                         "day" => DI::l10n()->t("day"),
283                         "list" => DI::l10n()->t("list"),
284                 ]);
285
286                 if (!empty($_GET['id'])) {
287                         echo $o;
288                         exit();
289                 }
290
291                 return $o;
292         }
293
294         if ($mode == 'export') {
295                 if (!$owner_uid) {
296                         notice(DI::l10n()->t('User not found'));
297                         return;
298                 }
299
300                 // Get the export data by uid
301                 $evexport = Event::exportListByUserId($owner_uid, $format);
302
303                 if (!$evexport["success"]) {
304                         if ($evexport["content"]) {
305                                 notice(DI::l10n()->t('This calendar format is not supported'));
306                         } else {
307                                 notice(DI::l10n()->t('No exportable data found'));
308                         }
309
310                         // If it the own calendar return to the events page
311                         // otherwise to the profile calendar page
312                         if (local_user() === $owner_uid) {
313                                 $return_path = "events";
314                         } else {
315                                 $return_path = "cal/" . $nick;
316                         }
317
318                         DI::baseUrl()->redirect($return_path);
319                 }
320
321                 // If nothing went wrong we can echo the export content
322                 if ($evexport["success"]) {
323                         header('Content-type: text/calendar');
324                         header('content-disposition: attachment; filename="' . DI::l10n()->t('calendar') . '-' . $nick . '.' . $evexport["extension"] . '"');
325                         echo $evexport["content"];
326                         exit();
327                 }
328
329                 return;
330         }
331 }