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