Merge remote-tracking branch 'upstream/develop' into search
[friendica.git/.git] / src / Module / Conversation / Timeline.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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\Channel as ChannelEntity;
29 use Friendica\Content\Conversation\Repository\UserDefinedChannel;
30 use Friendica\Core\Cache\Capability\ICanCache;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Config\Capability\IManageConfigValues;
33 use Friendica\Core\L10n;
34 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
35 use Friendica\Core\Renderer;
36 use Friendica\Core\Session\Capability\IHandleUserSessions;
37 use Friendica\Model\Contact;
38 use Friendica\Model\User;
39 use Friendica\Database\Database;
40 use Friendica\Database\DBA;
41 use Friendica\Model\Item;
42 use Friendica\Model\Post;
43 use Friendica\Model\Post\Engagement;
44 use Friendica\Model\Verb;
45 use Friendica\Module\Response;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Profiler;
49 use Psr\Log\LoggerInterface;
50
51 class Timeline extends BaseModule
52 {
53         /** @var string */
54         protected $selectedTab;
55         /** @var mixed */
56         protected $minId;
57         /** @var mixed */
58         protected $maxId;
59         /** @var string */
60         protected $accountTypeString;
61         /** @var int */
62         protected $accountType;
63         /** @var int */
64         protected $itemUriId;
65         /** @var int */
66         protected $itemsPerPage;
67         /** @var bool */
68         protected $noSharer;
69         /** @var bool */
70         protected $force;
71         /** @var bool */
72         protected $update;
73         /** @var bool */
74         protected $raw;
75
76         /** @var App\Mode $mode */
77         protected $mode;
78         /** @var IHandleUserSessions */
79         protected $session;
80         /** @var Database */
81         protected $database;
82         /** @var IManagePersonalConfigValues */
83         protected $pConfig;
84         /** @var IManageConfigValues The config */
85         protected $config;
86         /** @var ICanCache */
87         protected $cache;
88         /** @var UserDefinedChannel */
89         protected $channelRepository;
90
91         public function __construct(UserDefinedChannel $channel, 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 = [])
92         {
93                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
94
95                 $this->channelRepository = $channel;
96                 $this->mode              = $mode;
97                 $this->session           = $session;
98                 $this->database          = $database;
99                 $this->pConfig           = $pConfig;
100                 $this->config            = $config;
101                 $this->cache             = $cache;
102         }
103
104         /**
105          * Computes module parameters from the request and local configuration
106          *
107          * @throws HTTPException\BadRequestException
108          * @throws HTTPException\ForbiddenException
109          */
110         protected function parseRequest(array $request)
111         {
112                 $this->logger->debug('Got request', $request);
113                 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
114
115                 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
116                 $this->accountType       = User::getAccountTypeByString($this->accountTypeString);
117
118                 if ($this->mode->isMobile()) {
119                         $this->itemsPerPage = $this->pConfig->get(
120                                 $this->session->getLocalUserId(),
121                                 'system',
122                                 'itemspage_mobile_network',
123                                 $this->config->get('system', 'itemspage_network_mobile')
124                         );
125                 } else {
126                         $this->itemsPerPage = $this->pConfig->get(
127                                 $this->session->getLocalUserId(),
128                                 'system',
129                                 'itemspage_network',
130                                 $this->config->get('system', 'itemspage_network')
131                         );
132                 }
133
134                 if (!empty($request['item'])) {
135                         $item            = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
136                         $this->itemUriId = $item['parent-uri-id'] ?? 0;
137                 } else {
138                         $this->itemUriId = 0;
139                 }
140
141                 $this->minId = $request['min_id'] ?? null;
142                 $this->maxId = $request['max_id'] ?? null;
143
144                 $this->noSharer = !empty($request['no_sharer']);
145                 $this->force    = !empty($request['force']) && !empty($request['item']);
146                 $this->update   = !empty($request['force']) && !empty($request['first_received']) && !empty($request['first_created']) && !empty($request['first_uriid']) && !empty($request['first_commented']);
147                 $this->raw      = !empty($request['mode']) && ($request['mode'] == 'raw');
148         }
149
150         protected function getNoSharerWidget(string $base): string
151         {
152                 $path = $this->selectedTab;
153                 if (!empty($this->accountTypeString)) {
154                         $path .= '/' . $this->accountTypeString;
155                 }
156                 $query_parameters = [];
157
158                 if (!empty($this->minId)) {
159                         $query_parameters['min_id'] = $this->minId;
160                 }
161                 if (!empty($this->maxId)) {
162                         $query_parameters['max_id'] = $this->maxId;
163                 }
164
165                 $path_all       = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
166                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
167                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
168                         '$title'           => $this->l10n->t('Own Contacts'),
169                         '$path_all'        => $path_all,
170                         '$path_no_sharer'  => $path_no_sharer,
171                         '$no_sharer'       => $this->noSharer,
172                         '$all'             => $this->l10n->t('Include'),
173                         '$no_sharer_label' => $this->l10n->t('Hide'),
174                         '$base'            => $base,
175                 ]);
176         }
177
178         protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
179         {
180                 $tabs = [];
181
182                 foreach ($timelines as $tab) {
183                         if (is_null($tab->path) && !empty($parameter)) {
184                                 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
185                         } else {
186                                 $path = $tab->path ?? $prefix . '/' . $tab->code;
187                         }
188                         $tabs[$tab->code] = [
189                                 'code'      => $tab->code,
190                                 'label'     => $tab->label,
191                                 'url'       => $path,
192                                 'sel'       => $this->selectedTab == $tab->code ? 'active' : '',
193                                 'title'     => $tab->description,
194                                 'id'        => $prefix . '-' . $tab->code . '-tab',
195                                 'accesskey' => $tab->accessKey,
196                         ];
197                 }
198                 return $tabs;
199         }
200
201         /**
202          * Database query for the channel page
203          *
204          * @return array
205          * @throws \Exception
206          */
207         protected function getChannelItems()
208         {
209                 $items = $this->getRawChannelItems();
210
211                 $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
212                 $reduced  = array_column($contacts, 'cid');
213
214                 $maxpostperauthor = $this->config->get('channel', 'max_posts_per_author');
215
216                 if ($maxpostperauthor != 0) {
217                         $count          = 1;
218                         $owner_posts    = [];
219                         $selected_items = [];
220
221                         while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
222                                 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
223                                 $minId = $items[array_key_first($items)]['created'];
224                                 $maxId = $items[array_key_last($items)]['created'];
225
226                                 foreach ($items as $item) {
227                                         if (!in_array($item['owner-id'], $reduced)) {
228                                                 continue;
229                                         }
230                                         $owner_posts[$item['owner-id']][$item['uri-id']] = (($item['comments'] * 100) + $item['activities']);
231                                 }
232                                 foreach ($owner_posts as $posts) {
233                                         if (count($posts) <= $maxposts) {
234                                                 continue;
235                                         }
236                                         asort($posts);
237                                         while (count($posts) > $maxposts) {
238                                                 $uri_id = array_key_first($posts);
239                                                 unset($posts[$uri_id]);
240                                                 unset($items[$uri_id]);
241                                         }
242                                 }
243                                 $selected_items = array_merge($selected_items, $items);
244
245                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
246                                 // sorted in chronologically decreasing order
247                                 if (!empty($this->minId)) {
248                                         $this->minId = $minId;
249                                 } else {
250                                         // In any other case, the lookup continues backwards in time
251                                         $this->maxId = $maxId;
252                                 }
253
254                                 if (count($selected_items) < $this->itemsPerPage) {
255                                         $items = $this->getRawChannelItems();
256                                 }
257                         }
258                 } else {
259                         $selected_items = $items;
260                 }
261
262                 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
263                 $this->setItemsSeenByCondition($condition);
264
265                 return $selected_items;
266         }
267
268         /**
269          * Database query for the channel page
270          *
271          * @return array
272          * @throws \Exception
273          */
274         private function getRawChannelItems()
275         {
276                 $uid = $this->session->getLocalUserId();
277
278                 if ($this->selectedTab == ChannelEntity::WHATSHOT) {
279                         if (!is_null($this->accountType)) {
280                                 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
281                         } else {
282                                 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
283                         }
284                 } elseif ($this->selectedTab == ChannelEntity::FORYOU) {
285                         $cid = Contact::getPublicIdByUserId($uid);
286
287                         $condition = [
288                                 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
289                                 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
290                                 (`owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND (`notify_new_posts` OR `channel-frequency` = ?))))",
291                                 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
292                                 $uid, Contact\User::FREQUENCY_ALWAYS
293                         ];
294                 } elseif ($this->selectedTab == ChannelEntity::FOLLOWERS) {
295                         $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
296                 } elseif ($this->selectedTab == ChannelEntity::SHARERSOFSHARERS) {
297                         $cid = Contact::getPublicIdByUserId($uid);
298
299                         // @todo Suggest posts from contacts that are followed most by our followers
300                         $condition = [
301                                 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
302                                 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
303                                 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
304                                 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
305                         ];
306                 } elseif ($this->selectedTab == ChannelEntity::IMAGE) {
307                         $condition = ["`media-type` & ?", 1];
308                 } elseif ($this->selectedTab == ChannelEntity::VIDEO) {
309                         $condition = ["`media-type` & ?", 2];
310                 } elseif ($this->selectedTab == ChannelEntity::AUDIO) {
311                         $condition = ["`media-type` & ?", 4];
312                 } elseif ($this->selectedTab == ChannelEntity::LANGUAGE) {
313                         $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", User::getLanguageCode($uid)];
314                 } elseif (is_numeric($this->selectedTab)) {
315                         $condition = $this->getUserChannelConditions($this->selectedTab, $uid);
316                 }
317
318                 if (($this->selectedTab != ChannelEntity::LANGUAGE) && !is_numeric($this->selectedTab)) {
319                         $condition = $this->addLanguageCondition($uid, $condition);
320                 }
321
322                 $condition = DBA::mergeConditions($condition, ["(NOT `restricted` OR EXISTS(SELECT `id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = `post-engagement`.`uri-id`))", $uid]);
323
324                 $condition = DBA::mergeConditions($condition, ["NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed` OR `is-blocked` OR `channel-frequency` = ?))", $uid, Contact\User::FREQUENCY_NEVER]);
325
326                 if (($this->selectedTab != ChannelEntity::WHATSHOT) && !is_null($this->accountType)) {
327                         $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
328                 }
329
330                 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
331
332                 if (!empty($this->itemUriId)) {
333                         $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
334                 } else {
335                         if ($this->noSharer) {
336                                 $condition = DBA::mergeConditions($condition, ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-engagement`.`uri-id`)", $this->session->getLocalUserId()]);
337                         }
338
339                         if (isset($this->maxId)) {
340                                 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
341                         }
342
343                         if (isset($this->minId)) {
344                                 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
345
346                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
347                                 if (!isset($this->maxId)) {
348                                         $params['order']['created'] = false;
349                                 }
350                         }
351                 }
352
353                 $items = [];
354                 $result = $this->database->select('post-engagement', ['uri-id', 'created', 'owner-id', 'comments', 'activities'], $condition, $params);
355                 if ($this->database->errorNo()) {
356                         throw new \Exception($this->database->errorMessage(), $this->database->errorNo());
357                 }
358
359                 while ($item = $this->database->fetch($result)) {
360                         $items[$item['uri-id']] = $item;
361                 }
362                 $this->database->close($result);
363
364                 if (empty($items)) {
365                         return [];
366                 }
367
368                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
369                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
370                         $items = array_reverse($items, true);
371                 }
372
373                 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
374                 $this->setItemsSeenByCondition($condition);
375
376                 return $items;
377         }
378
379         private function getUserChannelConditions(int $id, int $uid): array
380         {
381                 $channel = $this->channelRepository->selectById($id, $uid);
382                 if (empty($channel)) {
383                         return [];
384                 }
385
386                 $condition = [];
387
388                 if (!empty($channel->circle)) {
389                         if ($channel->circle == -1) {
390                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))", $uid, Contact::SHARING, Contact::FRIEND];
391                         } elseif ($channel->circle == -2) {
392                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
393                         } elseif ($channel->circle == -3) {
394                                 $condition = ["EXISTS(SELECT `uri-id` FROM `post-thread-user` WHERE `uid` = ? AND `post-thread-user`.`uri-id` = `post-engagement`.`uri-id`)", $uid];
395                         } elseif ($channel->circle > 0) {
396                                 $condition = DBA::mergeConditions($condition, ["`owner-id` IN (SELECT `pid` FROM `group_member` INNER JOIN `account-user-view` ON `group_member`.`contact-id` = `account-user-view`.`id` WHERE `gid` = ? AND `account-user-view`.`uid` = ?)", $channel->circle, $uid]);
397                         }
398                 }
399
400                 if (!empty($channel->fullTextSearch)) {
401                         $condition = DBA::mergeConditions($condition, ["MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", Engagement::escapeKeywords($channel->fullTextSearch)]);
402                 }
403
404                 if (!empty($channel->includeTags)) {
405                         $search       = explode(',', mb_strtolower($channel->includeTags));
406                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
407                         $condition    = DBA::mergeConditions($condition, array_merge(["`uri-id` IN (SELECT `uri-id` FROM `post-tag` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` WHERE `post-tag`.`type` = 1 AND `name` IN (" . $placeholders . "))"], $search));
408                 }
409
410                 if (!empty($channel->excludeTags)) {
411                         $search       = explode(',', mb_strtolower($channel->excludeTags));
412                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
413                         $condition    = DBA::mergeConditions($condition, array_merge(["NOT `uri-id` IN (SELECT `uri-id` FROM `post-tag` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` WHERE `post-tag`.`type` = 1 AND `name` IN (" . $placeholders . "))"], $search));
414                 }
415
416                 if (!empty($channel->mediaType)) {
417                         $condition = DBA::mergeConditions($condition, ["`media-type` & ?", $channel->mediaType]);
418                 }
419
420                 // For "addLanguageCondition" to work, the condition must not be empty
421                 $condition = $this->addLanguageCondition($uid, $condition ?: ["true"], $channel->languages);
422
423                 return $condition;
424         }
425
426         private function addLanguageCondition(int $uid, array $condition, $languages = null): array
427         {
428                 $conditions = [];
429                 $languages  = $languages ?: User::getWantedLanguages($uid);
430                 foreach ($languages as $language) {
431                         $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
432                         $condition[]  = $language;
433                 }
434                 if (!empty($conditions)) {
435                         $condition[0] .= " AND (" . implode(' OR ', $conditions) . ")";
436                 }
437                 return $condition;
438         }
439
440         private function getMedianComments(int $uid, int $divider): int
441         {
442                 $languages = User::getWantedLanguages($uid);
443                 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
444                 $comments  = $this->cache->get($cache_key);
445                 if (!empty($comments)) {
446                         return $comments;
447                 }
448
449                 $condition = ["`contact-type` != ? AND `comments` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
450                 $condition = $this->addLanguageCondition($uid, $condition);
451
452                 $limit    = $this->database->count('post-engagement', $condition) / $divider;
453                 $post     = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
454                 $comments = $post[0]['comments'] ?? 0;
455                 if (empty($comments)) {
456                         return 0;
457                 }
458
459                 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
460                 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
461                 return $comments;
462         }
463
464         private function getMedianActivities(int $uid, int $divider): int
465         {
466                 $languages  = User::getWantedLanguages($uid);
467                 $cache_key  = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
468                 $activities = $this->cache->get($cache_key);
469                 if (!empty($activities)) {
470                         return $activities;
471                 }
472
473                 $condition = ["`contact-type` != ? AND `activities` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
474                 $condition = $this->addLanguageCondition($uid, $condition);
475
476                 $limit      = $this->database->count('post-engagement', $condition) / $divider;
477                 $post       = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
478                 $activities = $post[0]['activities'] ?? 0;
479                 if (empty($activities)) {
480                         return 0;
481                 }
482
483                 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
484                 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
485                 return $activities;
486         }
487
488         private function getMedianRelationThreadScore(int $cid, int $divider): int
489         {
490                 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
491                 $score     = $this->cache->get($cache_key);
492                 if (!empty($score)) {
493                         return $score;
494                 }
495
496                 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
497
498                 $limit    = $this->database->count('contact-relation', $condition) / $divider;
499                 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
500                 $score    = $relation[0]['relation-thread-score'] ?? 0;
501                 if (empty($score)) {
502                         return 0;
503                 }
504
505                 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
506                 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
507                 return $score;
508         }
509
510         /**
511          * Computes the displayed items.
512          *
513          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
514          * so we may have to retrieve more content beyond the first query
515          *
516          * @return array
517          * @throws \Exception
518          */
519         protected function getCommunityItems()
520         {
521                 $items = $this->selectItems();
522
523                 if ($this->selectedTab == 'local') {
524                         $maxpostperauthor = (int)$this->config->get('system', 'max_author_posts_community_page');
525                         $key = 'author-id';
526                 } elseif ($this->selectedTab == 'global') {
527                         $maxpostperauthor = (int)$this->config->get('system', 'max_server_posts_community_page');
528                         $key = 'author-gsid';
529                 } else {
530                         $maxpostperauthor = 0;
531                 }
532                 if ($maxpostperauthor != 0) {
533                         $count          = 1;
534                         $author_posts   = [];
535                         $selected_items = [];
536
537                         while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
538                                 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
539                                 $minId = $items[array_key_first($items)]['received'];
540                                 $maxId = $items[array_key_last($items)]['received'];
541
542                                 foreach ($items as $item) {
543                                         $author_posts[$item[$key]][$item['uri-id']] = $item['received'];
544                                 }
545                                 foreach ($author_posts as $posts) {
546                                         if (count($posts) <= $maxposts) {
547                                                 continue;
548                                         }
549                                         asort($posts);
550                                         while (count($posts) > $maxposts) {
551                                                 $uri_id = array_key_first($posts);
552                                                 unset($posts[$uri_id]);
553                                                 unset($items[$uri_id]);
554                                         }
555                                 }
556                                 $selected_items = array_merge($selected_items, $items);
557
558                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
559                                 // sorted in chronologically decreasing order
560                                 if (!empty($this->minId)) {
561                                         $this->minId = $minId;
562                                 } else {
563                                         // In any other case, the lookup continues backwards in time
564                                         $this->maxId = $maxId;
565                                 }
566
567                                 if (count($selected_items) < $this->itemsPerPage) {
568                                         $items = $this->selectItems();
569                                 }
570                         }
571                 } else {
572                         $selected_items = $items;
573                 }
574
575                 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
576                 $this->setItemsSeenByCondition($condition);
577
578                 return $selected_items;
579         }
580
581         /**
582          * Database query for the community page
583          *
584          * @return array
585          * @throws \Exception
586          * @TODO Move to repository/factory
587          */
588         private function selectItems()
589         {
590                 if ($this->selectedTab == 'local') {
591                         $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
592                 } elseif ($this->selectedTab == 'global') {
593                         $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
594                 } else {
595                         return [];
596                 }
597
598                 if (!is_null($this->accountType)) {
599                         $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
600                 }
601
602                 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
603
604                 if (!empty($this->itemUriId)) {
605                         $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
606                 } else {
607                         if ($this->session->getLocalUserId() && $this->noSharer) {
608                                 $condition = DBA::mergeConditions($condition, ["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`)", $this->session->getLocalUserId()]);
609                         }
610
611                         if (isset($this->maxId)) {
612                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
613                         }
614
615                         if (isset($this->minId)) {
616                                 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
617
618                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
619                                 if (!isset($this->maxId)) {
620                                         $params['order']['received'] = false;
621                                 }
622                         }
623                 }
624
625                 $items = [];
626                 $result = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-id', 'author-gsid'], $condition, $params);
627
628                 while ($item = $this->database->fetch($result)) {
629                         $item['comments'] = 0;
630
631                         $items[$item['uri-id']] = $item;
632                 }
633                 $this->database->close($result);
634
635                 if (empty($items)) {
636                         return [];
637                 }
638
639                 $uriids = array_keys($items);
640                 
641                 foreach (Post\Counts::get(['parent-uri-id' => $uriids, 'verb' => Activity::POST]) as $count) {
642                         $items[$count['parent-uri-id']]['comments'] += $count['count'];
643                 }
644
645                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
646                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
647                         $items = array_reverse($items);
648                 }
649
650                 return $items;
651         }
652
653         /**
654          * Sets items as seen
655          *
656          * @param array $condition The array with the SQL condition
657          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
658          */
659         protected function setItemsSeenByCondition(array $condition)
660         {
661                 if (empty($condition)) {
662                         return;
663                 }
664
665                 $unseen = Post::exists($condition);
666
667                 if ($unseen) {
668                         /// @todo handle huge "unseen" updates in the background to avoid timeout errors
669                         Item::update(['unseen' => false], $condition);
670                 }
671         }
672 }