]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Channel.php
Use $request / changed icon
[friendica.git] / src / Module / Conversation / Channel.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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
21 namespace Friendica\Module\Conversation;
22
23 use Friendica\BaseModule;
24 use Friendica\Content\BoundariesPager;
25 use Friendica\Content\Conversation;
26 use Friendica\Content\Feature;
27 use Friendica\Content\Nav;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Content\Widget;
30 use Friendica\Content\Widget\TrendingTags;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Renderer;
34 use Friendica\Database\DBA;
35 use Friendica\DI;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Post;
38 use Friendica\Model\User;
39 use Friendica\Module\Security\Login;
40 use Friendica\Network\HTTPException;
41
42 class Channel extends BaseModule
43 {
44         const WHATSHOT  = 'whatshot';
45         const FORYOU    = 'foryou';
46         const FOLLOWERS = 'followers';
47         const IMAGE     = 'image';
48         const VIDEO     = 'video';
49         const AUDIO     = 'audio';
50
51         protected static $content;
52         protected static $accountTypeString;
53         protected static $accountType;
54         protected static $itemsPerPage;
55         protected static $min_id;
56         protected static $max_id;
57         protected static $item_id;
58
59         protected function content(array $request = []): string
60         {
61                 if (!DI::userSession()->getLocalUserId()) {
62                         return Login::form();
63                 }
64
65                 $this->parseRequest($request);
66
67                 $t = Renderer::getMarkupTemplate("community.tpl");
68                 $o = Renderer::replaceMacros($t, [
69                         '$content' => '',
70                         '$header'  => '',
71                 ]);
72
73                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
74                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
75                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
76                 }
77
78                 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
79                         $tabs = [];
80
81                         $tabs[] = [
82                                 'label'     => DI::l10n()->t('For you'),
83                                 'url'       => 'channel/' . self::FORYOU,
84                                 'sel'       => self::$content == self::FORYOU ? 'active' : '',
85                                 'title'     => DI::l10n()->t('Posts from contacts you interact with and who interact with you'),
86                                 'id'        => 'channel-foryou-tab',
87                                 'accesskey' => 'y'
88                         ];
89
90                         $tabs[] = [
91                                 'label'     => DI::l10n()->t('Followers'),
92                                 'url'       => 'channel/' . self::FOLLOWERS,
93                                 'sel'       => self::$content == self::FOLLOWERS ? 'active' : '',
94                                 'title'     => DI::l10n()->t('Posts from your followers that you don\'t follow'),
95                                 'id'        => 'channel-followers-tab',
96                                 'accesskey' => 'f'
97                         ];
98
99                         $tabs[] = [
100                                 'label'     => DI::l10n()->t('Whats Hot'),
101                                 'url'       => 'channel/' . self::WHATSHOT,
102                                 'sel'       => self::$content == self::WHATSHOT ? 'active' : '',
103                                 'title'     => DI::l10n()->t('Posts with a lot of interactions'),
104                                 'id'        => 'channel-whatshot-tab',
105                                 'accesskey' => 'h'
106                         ];
107
108                         $tabs[] = [
109                                 'label'     => DI::l10n()->t('Images'),
110                                 'url'       => 'channel/' . self::IMAGE,
111                                 'sel'       => self::$content == self::IMAGE ? 'active' : '',
112                                 'title'     => DI::l10n()->t('Posts with images'),
113                                 'id'        => 'channel-image-tab',
114                                 'accesskey' => 'i'
115                         ];
116
117                         $tabs[] = [
118                                 'label'     => DI::l10n()->t('Videos'),
119                                 'url'       => 'channel/' . self::VIDEO,
120                                 'sel'       => self::$content == self::VIDEO ? 'active' : '',
121                                 'title'     => DI::l10n()->t('Posts with videos'),
122                                 'id'        => 'channel-video-tab',
123                                 'accesskey' => 'v'
124                         ];
125
126                         $tabs[] = [
127                                 'label'     => DI::l10n()->t('Audio'),
128                                 'url'       => 'channel/' . self::AUDIO,
129                                 'sel'       => self::$content == self::AUDIO ? 'active' : '',
130                                 'title'     => DI::l10n()->t('Posts with audio'),
131                                 'id'        => 'channel-audio-tab',
132                                 'accesskey' => 'a'
133                         ];
134
135                         $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
136                         $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
137
138                         Nav::setSelected('channel');
139
140                         DI::page()['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
141
142                         if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && DI::config()->get('system', 'community_no_sharer')) {
143                                 $path = self::$content;
144                                 if (!empty($this->parameters['accounttype'])) {
145                                         $path .= '/' . $this->parameters['accounttype'];
146                                 }
147                                 $query_parameters = [];
148
149                                 if (!empty($request['min_id'])) {
150                                         $query_parameters['min_id'] = $request['min_id'];
151                                 }
152                                 if (!empty($request['max_id'])) {
153                                         $query_parameters['max_id'] = $request['max_id'];
154                                 }
155                                 if (!empty($request['last_created'])) {
156                                         $query_parameters['max_id'] = $request['last_created'];
157                                 }
158
159                                 $path_all       = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
160                                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
161                                 DI::page()['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
162                                         '$title'           => DI::l10n()->t('Own Contacts'),
163                                         '$path_all'        => $path_all,
164                                         '$path_no_sharer'  => $path_no_sharer,
165                                         '$no_sharer'       => !empty($request['no_sharer']),
166                                         '$all'             => DI::l10n()->t('Include'),
167                                         '$no_sharer_label' => DI::l10n()->t('Hide'),
168                                         '$base'            => 'channel',
169                                 ]);
170                         }
171
172                         if (Feature::isEnabled(DI::userSession()->getLocalUserId(), 'trending_tags')) {
173                                 DI::page()['aside'] .= TrendingTags::getHTML(self::$content);
174                         }
175
176                         // We need the editor here to be able to reshare an item.
177                         $o .= DI::conversation()->statusEditor([], 0, true);
178                 }
179
180                 $items = self::getItems($request);
181
182                 if (!DBA::isResult($items)) {
183                         DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
184                         return $o;
185                 }
186
187                 $o .= DI::conversation()->render($items, Conversation::MODE_CHANNEL, false, false, 'created', DI::userSession()->getLocalUserId());
188
189                 $pager = new BoundariesPager(
190                         DI::l10n(),
191                         DI::args()->getQueryString(),
192                         $items[0]['created'],
193                         $items[count($items) - 1]['created'],
194                         self::$itemsPerPage
195                 );
196
197                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
198                         $o .= HTML::scrollLoader();
199                 } else {
200                         $o .= $pager->renderMinimal(count($items));
201                 }
202
203                 return $o;
204         }
205
206         /**
207          * Computes module parameters from the request and local configuration
208          *
209          * @throws HTTPException\BadRequestException
210          * @throws HTTPException\ForbiddenException
211          */
212         protected function parseRequest(array $request)
213         {
214                 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
215                 self::$accountType       = User::getAccountTypeByString(self::$accountTypeString);
216
217                 self::$content = $this->parameters['content'] ?? '';
218                 if (!self::$content) {
219                         self::$content = self::FORYOU;
220                 }
221
222                 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::IMAGE, self::VIDEO, self::AUDIO])) {
223                         throw new HTTPException\BadRequestException(DI::l10n()->t('Channel not available.'));
224                 }
225
226                 if (DI::mode()->isMobile()) {
227                         self::$itemsPerPage = DI::pConfig()->get(
228                                 DI::userSession()->getLocalUserId(),
229                                 'system',
230                                 'itemspage_mobile_network',
231                                 DI::config()->get('system', 'itemspage_network_mobile')
232                         );
233                 } else {
234                         self::$itemsPerPage = DI::pConfig()->get(
235                                 DI::userSession()->getLocalUserId(),
236                                 'system',
237                                 'itemspage_network',
238                                 DI::config()->get('system', 'itemspage_network')
239                         );
240                 }
241
242                 if (!empty($request['item'])) {
243                         $item          = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
244                         self::$item_id = $item['parent-uri-id'] ?? 0;
245                 } else {
246                         self::$item_id = 0;
247                 }
248
249                 Logger::debug('Blubb', ['get' => $request]);
250                 self::$min_id = $request['min_id']       ?? null;
251                 self::$max_id = $request['max_id']       ?? null;
252                 self::$max_id = $request['last_created'] ?? self::$max_id;
253         }
254
255         /**
256          * Computes the displayed items.
257          *
258          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
259          * so we may have to retrieve more content beyond the first query
260          *
261          * @return array
262          * @throws \Exception
263          */
264         protected static function getItems(array $request)
265         {
266                 if (self::$content == self::WHATSHOT) {
267                         if (!is_null(self::$accountType)) {
268                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", self::getMedianComments(4), self::getMedianActivities(4), self::$accountType];
269                         } else {
270                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", self::getMedianComments(4), self::getMedianActivities(4), Contact::TYPE_COMMUNITY];
271                         }
272                 } elseif (self::$content == self::FORYOU) {
273                         $cid = Contact::getPublicIdByUserId(DI::userSession()->getLocalUserId());
274
275                         $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
276                                 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
277                                 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
278                                 $cid, self::getMedianThreadScore($cid, 4), self::getMedianComments(4), self::getMedianActivities(4), DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
279                                 DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
280                 } elseif (self::$content == self::FOLLOWERS) {
281                         $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", DI::userSession()->getLocalUserId(), Contact::FOLLOWER];
282                 } elseif (self::$content == self::IMAGE) {
283                         $condition = ["`media-type` & ?", 1];
284                 } elseif (self::$content == self::VIDEO) {
285                         $condition = ["`media-type` & ?", 2];
286                 } elseif (self::$content == self::AUDIO) {
287                         $condition = ["`media-type` & ?", 4];
288                 }
289
290                 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
291                 $condition[] = DI::userSession()->getLocalUserId();
292
293                 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
294                         $condition[0] .= " AND `contact-type` = ?";
295                         $condition[] = self::$accountType;
296                 }
297
298                 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
299
300                 if (!empty(self::$item_id)) {
301                         $condition[0] .= " AND `uri-id` = ?";
302                         $condition[] = self::$item_id;
303                 } else {
304                         if (!empty($request['no_sharer'])) {
305                                 $condition[0] .= " AND NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-engagement`.`uri-id`)";
306                                 $condition[] = DI::userSession()->getLocalUserId();
307                         }
308
309                         if (isset(self::$max_id)) {
310                                 $condition[0] .= " AND `created` < ?";
311                                 $condition[] = self::$max_id;
312                         }
313
314                         if (isset(self::$min_id)) {
315                                 $condition[0] .= " AND `created` > ?";
316                                 $condition[] = self::$min_id;
317
318                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
319                                 if (!isset(self::$max_id)) {
320                                         $params['order']['created'] = false;
321                                 }
322                         }
323                 }
324
325                 $items = DBA::selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
326
327                 if (empty($items)) {
328                         return [];
329                 }
330
331                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
332                 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
333                         $items = array_reverse($items);
334                 }
335
336                 return $items;
337         }
338
339         private static function getMedianComments(int $divider): int
340         {
341                 $cache_key = 'Channel:getMedianComments:' . $divider;
342                 $comments  = DI::cache()->get($cache_key);
343                 if (!empty($comments)) {
344                         return $comments;
345                 }
346
347                 $limit    = DBA::count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
348                 $post     = DBA::selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
349                 $comments = $post[0]['comments'] ?? 0;
350                 if (empty($comments)) {
351                         return 0;
352                 }
353
354                 DI::cache()->set($cache_key, $comments, Duration::HOUR);
355                 return $comments;
356         }
357
358         private static function getMedianActivities(int $divider): int
359         {
360                 $cache_key  = 'Channel:getMedianActivities:' . $divider;
361                 $activities = DI::cache()->get($cache_key);
362                 if (!empty($activities)) {
363                         return $activities;
364                 }
365
366                 $limit      = DBA::count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
367                 $post       = DBA::selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
368                 $activities = $post[0]['activities'] ?? 0;
369                 if (empty($activities)) {
370                         return 0;
371                 }
372
373                 DI::cache()->set($cache_key, $activities, Duration::HOUR);
374                 return $activities;
375         }
376
377         private static function getMedianThreadScore(int $cid, int $divider): int
378         {
379                 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
380                 $score     = DI::cache()->get($cache_key);
381                 if (!empty($score)) {
382                         return $score;
383                 }
384
385                 $limit    = DBA::count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
386                 $relation = DBA::selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
387                 $score    = $relation[0]['thread-score'] ?? 0;
388                 if (empty($score)) {
389                         return 0;
390                 }
391
392                 DI::cache()->set($cache_key, $score, Duration::HOUR);
393                 return $score;
394         }
395 }