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