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