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