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