]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Timeline.php
Network, Channels and Community are children of timeline
[friendica.git] / src / Module / Conversation / Timeline.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\Conversation\Collection\Timelines;
28 use Friendica\Content\Conversation\Entity\Timeline as TimelineEntity;
29 use Friendica\Core\Cache\Capability\ICanCache;
30 use Friendica\Core\Cache\Enum\Duration;
31 use Friendica\Core\Config\Capability\IManageConfigValues;
32 use Friendica\Core\L10n;
33 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session\Capability\IHandleUserSessions;
36 use Friendica\Model\Contact;
37 use Friendica\Model\User;
38 use Friendica\Database\Database;
39 use Friendica\Model\Item;
40 use Friendica\Model\Post;
41 use Friendica\Module\Response;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Profiler;
44 use Psr\Log\LoggerInterface;
45
46 class Timeline extends BaseModule
47 {
48         /** @var string */
49         protected static $selectedTab;
50         /** @var mixed */
51         protected static $min_id;
52         /** @var mixed */
53         protected static $max_id;
54         /** @var string */
55         protected static $accountTypeString;
56         /** @var int */
57         protected static $accountType;
58         /** @var int */
59         protected static $item_id;
60         /** @var int */
61         protected static $itemsPerPage;
62         /** @var bool */
63         protected static $no_sharer;
64
65         /** @var App\Mode $mode */
66         protected $mode;
67         /** @var UserSession */
68         protected $session;
69         /** @var Database */
70         protected $database;
71         /** @var IManagePersonalConfigValues */
72         protected $pConfig;
73         /** @var IManageConfigValues The config */
74         protected $config;
75         /** @var ICanCache */
76         protected $cache;
77
78         public function __construct(Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
79         {
80                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
81
82                 $this->mode     = $mode;
83                 $this->session  = $session;
84                 $this->database = $database;
85                 $this->pConfig  = $pConfig;
86                 $this->config   = $config;
87                 $this->cache    = $cache;
88         }
89
90         /**
91          * Computes module parameters from the request and local configuration
92          *
93          * @throws HTTPException\BadRequestException
94          * @throws HTTPException\ForbiddenException
95          */
96         protected function parseRequest(array $request)
97         {
98                 self::$selectedTab = $this->parameters['content'] ?? '';
99
100                 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
101                 self::$accountType       = User::getAccountTypeByString(self::$accountTypeString);
102
103                 if ($this->mode->isMobile()) {
104                         self::$itemsPerPage = $this->pConfig->get(
105                                 $this->session->getLocalUserId(),
106                                 'system',
107                                 'itemspage_mobile_network',
108                                 $this->config->get('system', 'itemspage_network_mobile')
109                         );
110                 } else {
111                         self::$itemsPerPage = $this->pConfig->get(
112                                 $this->session->getLocalUserId(),
113                                 'system',
114                                 'itemspage_network',
115                                 $this->config->get('system', 'itemspage_network')
116                         );
117                 }
118
119                 self::$min_id = $request['min_id'] ?? null;
120                 self::$max_id = $request['max_id'] ?? null;
121
122                 self::$no_sharer = !empty($request['no_sharer']);
123         }
124
125         protected function getNoSharerWidget(string $base): string
126         {
127                 $path = self::$selectedTab;
128                 if (!empty(self::$accountTypeString)) {
129                         $path .= '/' . self::$accountTypeString;
130                 }
131                 $query_parameters = [];
132
133                 if (!empty(self::$min_id)) {
134                         $query_parameters['min_id'] = self::$min_id;
135                 }
136                 if (!empty(self::$max_id)) {
137                         $query_parameters['max_id'] = self::$max_id;
138                 }
139
140                 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
141                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
142                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
143                         '$title'           => $this->l10n->t('Own Contacts'),
144                         '$path_all'        => $path_all,
145                         '$path_no_sharer'  => $path_no_sharer,
146                         '$no_sharer'       => self::$no_sharer,
147                         '$all'             => $this->l10n->t('Include'),
148                         '$no_sharer_label' => $this->l10n->t('Hide'),
149                         '$base'            => $base,
150                 ]);
151         }
152
153         protected function getTabArray(Timelines $timelines, string $prefix): array
154         {
155                 $tabs = [];
156
157                 foreach ($timelines as $tab) {
158                         $tabs[] = [
159                                 'label'     => $tab->label,
160                                 'url'       => $tab->path ?? $prefix . '/' . $tab->code,
161                                 'sel'       => self::$selectedTab == $tab->code ? 'active' : '',
162                                 'title'     => $tab->description,
163                                 'id'        => $prefix . '-' . $tab->code . '-tab',
164                                 'accesskey' => $tab->accessKey,
165                         ];
166                 }
167                 return $tabs;
168         }
169
170         /**
171          * Database query for the channel page
172          *
173          * @return array
174          * @throws \Exception
175          */
176         protected function getChannelItems()
177         {
178                 $uid = $this->session->getLocalUserId();
179
180                 if (self::$selectedTab == TimelineEntity::WHATSHOT) {
181                         if (!is_null(self::$accountType)) {
182                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), self::$accountType];
183                         } else {
184                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
185                         }
186                 } elseif (self::$selectedTab == TimelineEntity::FORYOU) {
187                         $cid = Contact::getPublicIdByUserId($uid);
188                         $condition = [
189                                 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
190                                 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
191                                 (`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
192                                 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
193                                 $uid, Contact::FRIEND, Contact::SHARING
194                         ];
195                 } elseif (self::$selectedTab == TimelineEntity::FOLLOWERS) {
196                         $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
197                 } elseif (self::$selectedTab == TimelineEntity::SHARERSOFSHARERS) {
198                         $cid = Contact::getPublicIdByUserId($uid);
199
200                         // @todo Suggest posts from contacts that are followed most by our followers
201                         $condition = [
202                                 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
203                                 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
204                                 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
205                                 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
206                         ];
207                 } elseif (self::$selectedTab == TimelineEntity::IMAGE) {
208                         $condition = ["`media-type` & ?", 1];
209                 } elseif (self::$selectedTab == TimelineEntity::VIDEO) {
210                         $condition = ["`media-type` & ?", 2];
211                 } elseif (self::$selectedTab == TimelineEntity::AUDIO) {
212                         $condition = ["`media-type` & ?", 4];
213                 } elseif (self::$selectedTab == TimelineEntity::LANGUAGE) {
214                         $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($uid))];
215                 }
216
217                 if (self::$selectedTab != TimelineEntity::LANGUAGE) {
218                         $condition = $this->addLanguageCondition($uid, $condition);
219                 }
220
221                 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
222                 $condition[] = $uid;
223
224                 if ((self::$selectedTab != TimelineEntity::WHATSHOT) && !is_null(self::$accountType)) {
225                         $condition[0] .= " AND `contact-type` = ?";
226                         $condition[] = self::$accountType;
227                 }
228
229                 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
230
231                 if (!empty(self::$item_id)) {
232                         $condition[0] .= " AND `uri-id` = ?";
233                         $condition[] = self::$item_id;
234                 } else {
235                         if (self::$no_sharer) {
236                                 $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`)";
237                                 $condition[] = $uid;
238                         }
239
240                         if (isset(self::$max_id)) {
241                                 $condition[0] .= " AND `created` < ?";
242                                 $condition[] = self::$max_id;
243                         }
244
245                         if (isset(self::$min_id)) {
246                                 $condition[0] .= " AND `created` > ?";
247                                 $condition[] = self::$min_id;
248
249                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
250                                 if (!isset(self::$max_id)) {
251                                         $params['order']['created'] = false;
252                                 }
253                         }
254                 }
255
256                 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
257                 if (empty($items)) {
258                         return [];
259                 }
260
261                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
262                 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
263                         $items = array_reverse($items);
264                 }
265
266                 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $uid, 'uri-id' => array_column($items, 'uri-id')]);
267
268                 return $items;
269         }
270
271         private function addLanguageCondition(int $uid, array $condition): array
272         {
273                 $conditions = [];
274                 $languages  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
275                 $languages  = $this->l10n->convertForLanguageDetection($languages);
276                 foreach ($languages as $language) {
277                         $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
278                         $condition[]  = $language;
279                 }
280                 if (!empty($conditions)) {
281                         $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
282                 }
283                 return $condition;
284         }
285
286         private function getMedianComments(int $uid, int $divider): int
287         {
288                 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
289                 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
290                 $comments  = $this->cache->get($cache_key);
291                 if (!empty($comments)) {
292                         return $comments;
293                 }
294
295                 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
296                 $condition = $this->addLanguageCondition($uid, $condition);
297
298                 $limit    = $this->database->count('post-engagement', $condition) / $divider;
299                 $post     = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
300                 $comments = $post[0]['comments'] ?? 0;
301                 if (empty($comments)) {
302                         return 0;
303                 }
304
305                 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
306                 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
307                 return $comments;
308         }
309
310         private function getMedianActivities(int $uid, int $divider): int
311         {
312                 $languages  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
313                 $cache_key  = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
314                 $activities = $this->cache->get($cache_key);
315                 if (!empty($activities)) {
316                         return $activities;
317                 }
318
319                 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
320                 $condition = $this->addLanguageCondition($uid, $condition);
321
322                 $limit      = $this->database->count('post-engagement', $condition) / $divider;
323                 $post       = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
324                 $activities = $post[0]['activities'] ?? 0;
325                 if (empty($activities)) {
326                         return 0;
327                 }
328
329                 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
330                 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
331                 return $activities;
332         }
333
334         private function getMedianRelationThreadScore(int $cid, int $divider): int
335         {
336                 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
337                 $score     = $this->cache->get($cache_key);
338                 if (!empty($score)) {
339                         return $score;
340                 }
341
342                 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
343
344                 $limit    = $this->database->count('contact-relation', $condition) / $divider;
345                 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
346                 $score    = $relation[0]['relation-thread-score'] ?? 0;
347                 if (empty($score)) {
348                         return 0;
349                 }
350
351                 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
352                 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
353                 return $score;
354         }
355
356         /**
357          * Computes the displayed items.
358          *
359          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
360          * so we may have to retrieve more content beyond the first query
361          *
362          * @return array
363          * @throws \Exception
364          */
365         protected function getCommunityItems()
366         {
367                 $items = $this->selectItems();
368
369                 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
370                 if ($maxpostperauthor != 0 && self::$selectedTab == 'local') {
371                         $count = 1;
372                         $previousauthor = '';
373                         $numposts = 0;
374                         $selected_items = [];
375
376                         while (count($selected_items) < self::$itemsPerPage && ++$count < 50 && count($items) > 0) {
377                                 foreach ($items as $item) {
378                                         if ($previousauthor == $item["author-link"]) {
379                                                 ++$numposts;
380                                         } else {
381                                                 $numposts = 0;
382                                         }
383                                         $previousauthor = $item["author-link"];
384
385                                         if (($numposts < $maxpostperauthor) && (count($selected_items) < self::$itemsPerPage)) {
386                                                 $selected_items[] = $item;
387                                         }
388                                 }
389
390                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
391                                 // sorted in chronologically decreasing order
392                                 if (isset(self::$min_id)) {
393                                         self::$min_id = $items[0]['commented'];
394                                 } else {
395                                         // In any other case, the lookup continues backwards in time
396                                         self::$max_id = $items[count($items) - 1]['commented'];
397                                 }
398
399                                 $items = $this->selectItems();
400                         }
401                 } else {
402                         $selected_items = $items;
403                 }
404
405                 return $selected_items;
406         }
407
408         /**
409          * Database query for the community page
410          *
411          * @return array
412          * @throws \Exception
413          * @TODO Move to repository/factory
414          */
415         private function selectItems()
416         {
417                 if (self::$selectedTab == 'local') {
418                         if (!is_null(self::$accountType)) {
419                                 $condition = ["`wall` AND `origin` AND `private` = ? AND `owner-contact-type` = ?", Item::PUBLIC, self::$accountType];
420                         } else {
421                                 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
422                         }
423                 } elseif (self::$selectedTab == 'global') {
424                         if (!is_null(self::$accountType)) {
425                                 $condition = ["`uid` = ? AND `private` = ? AND `owner-contact-type` = ?", 0, Item::PUBLIC, self::$accountType];
426                         } else {
427                                 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
428                         }
429                 } else {
430                         return [];
431                 }
432
433                 $params = ['order' => ['commented' => true], 'limit' => self::$itemsPerPage];
434
435                 if (!empty(self::$item_id)) {
436                         $condition[0] .= " AND `id` = ?";
437                         $condition[] = self::$item_id;
438                 } else {
439                         if ($this->session->getLocalUserId() && self::$no_sharer) {
440                                 $condition[0] .= " AND NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-thread-user-view`.`uri-id`)";
441                                 $condition[] = $this->session->getLocalUserId();
442                         }
443
444                         if (isset(self::$max_id)) {
445                                 $condition[0] .= " AND `commented` < ?";
446                                 $condition[] = self::$max_id;
447                         }
448
449                         if (isset(self::$min_id)) {
450                                 $condition[0] .= " AND `commented` > ?";
451                                 $condition[] = self::$min_id;
452
453                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
454                                 if (!isset(self::$max_id)) {
455                                         $params['order']['commented'] = false;
456                                 }
457                         }
458                 }
459
460                 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'commented', 'author-link'], $condition, $params);
461
462                 $items = Post::toArray($r);
463                 if (empty($items)) {
464                         return [];
465                 }
466
467                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
468                 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
469                         $items = array_reverse($items);
470                 }
471
472                 return $items;
473         }
474 }