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