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