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