Don't display additional content when the output mode is "raw"
[friendica.git/.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\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\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         /** @var bool */
72         protected $raw;
73
74         /** @var App\Mode $mode */
75         protected $mode;
76         /** @var IHandleUserSessions */
77         protected $session;
78         /** @var Database */
79         protected $database;
80         /** @var IManagePersonalConfigValues */
81         protected $pConfig;
82         /** @var IManageConfigValues The config */
83         protected $config;
84         /** @var ICanCache */
85         protected $cache;
86         /** @var UserDefinedChannel */
87         protected $channelRepository;
88
89         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 = [])
90         {
91                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
92
93                 $this->channelRepository = $channel;
94                 $this->mode              = $mode;
95                 $this->session           = $session;
96                 $this->database          = $database;
97                 $this->pConfig           = $pConfig;
98                 $this->config            = $config;
99                 $this->cache             = $cache;
100         }
101
102         /**
103          * Computes module parameters from the request and local configuration
104          *
105          * @throws HTTPException\BadRequestException
106          * @throws HTTPException\ForbiddenException
107          */
108         protected function parseRequest(array $request)
109         {
110                 $this->logger->debug('Got request', $request);
111                 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
112
113                 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
114                 $this->accountType       = User::getAccountTypeByString($this->accountTypeString);
115
116                 if ($this->mode->isMobile()) {
117                         $this->itemsPerPage = $this->pConfig->get(
118                                 $this->session->getLocalUserId(),
119                                 'system',
120                                 'itemspage_mobile_network',
121                                 $this->config->get('system', 'itemspage_network_mobile')
122                         );
123                 } else {
124                         $this->itemsPerPage = $this->pConfig->get(
125                                 $this->session->getLocalUserId(),
126                                 'system',
127                                 'itemspage_network',
128                                 $this->config->get('system', 'itemspage_network')
129                         );
130                 }
131
132                 if (!empty($request['item'])) {
133                         $item            = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
134                         $this->itemUriId = $item['parent-uri-id'] ?? 0;
135                 } else {
136                         $this->itemUriId = 0;
137                 }
138
139                 $this->minId = $request['min_id'] ?? null;
140                 $this->maxId = $request['max_id'] ?? null;
141
142                 $this->noSharer = !empty($request['no_sharer']);
143                 $this->force    = !empty($request['force']) && !empty($request['item']);
144                 $this->update   = !empty($request['force']) && !empty($request['first_received']) && !empty($request['first_created']) && !empty($request['first_uriid']) && !empty($request['first_commented']);
145                 $this->raw      = !empty($request['mode']) && ($request['mode'] == 'raw');
146         }
147
148         protected function getNoSharerWidget(string $base): string
149         {
150                 $path = $this->selectedTab;
151                 if (!empty($this->accountTypeString)) {
152                         $path .= '/' . $this->accountTypeString;
153                 }
154                 $query_parameters = [];
155
156                 if (!empty($this->minId)) {
157                         $query_parameters['min_id'] = $this->minId;
158                 }
159                 if (!empty($this->maxId)) {
160                         $query_parameters['max_id'] = $this->maxId;
161                 }
162
163                 $path_all       = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
164                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
165                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
166                         '$title'           => $this->l10n->t('Own Contacts'),
167                         '$path_all'        => $path_all,
168                         '$path_no_sharer'  => $path_no_sharer,
169                         '$no_sharer'       => $this->noSharer,
170                         '$all'             => $this->l10n->t('Include'),
171                         '$no_sharer_label' => $this->l10n->t('Hide'),
172                         '$base'            => $base,
173                 ]);
174         }
175
176         protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
177         {
178                 $tabs = [];
179
180                 foreach ($timelines as $tab) {
181                         if (is_null($tab->path) && !empty($parameter)) {
182                                 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
183                         } else {
184                                 $path = $tab->path ?? $prefix . '/' . $tab->code;
185                         }
186                         $tabs[$tab->code] = [
187                                 'code'      => $tab->code,
188                                 'label'     => $tab->label,
189                                 'url'       => $path,
190                                 'sel'       => $this->selectedTab == $tab->code ? 'active' : '',
191                                 'title'     => $tab->description,
192                                 'id'        => $prefix . '-' . $tab->code . '-tab',
193                                 'accesskey' => $tab->accessKey,
194                         ];
195                 }
196                 return $tabs;
197         }
198
199         /**
200          * Database query for the channel page
201          *
202          * @return array
203          * @throws \Exception
204          */
205         protected function getChannelItems()
206         {
207                 $items = $this->getRawChannelItems();
208
209                 $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
210                 $reduced  = array_column($contacts, 'cid');
211
212                 $maxpostperauthor = $this->config->get('channel', 'max_posts_per_author');
213
214                 if ($maxpostperauthor != 0) {
215                         $count          = 1;
216                         $owner_posts    = [];
217                         $selected_items = [];
218
219                         while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
220                                 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
221                                 $minId = $items[array_key_first($items)]['created'];
222                                 $maxId = $items[array_key_last($items)]['created'];
223
224                                 foreach ($items as $item) {
225                                         if (!in_array($item['owner-id'], $reduced)) {
226                                                 continue;
227                                         }
228                                         $owner_posts[$item['owner-id']][$item['uri-id']] = (($item['comments'] * 100) + $item['activities']);
229                                 }
230                                 foreach ($owner_posts as $posts) {
231                                         if (count($posts) <= $maxposts) {
232                                                 continue;
233                                         }
234                                         asort($posts);
235                                         while (count($posts) > $maxposts) {
236                                                 $uri_id = array_key_first($posts);
237                                                 unset($posts[$uri_id]);
238                                                 unset($items[$uri_id]);
239                                         }
240                                 }
241                                 $selected_items = array_merge($selected_items, $items);
242
243                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
244                                 // sorted in chronologically decreasing order
245                                 if (!empty($this->minId)) {
246                                         $this->minId = $minId;
247                                 } else {
248                                         // In any other case, the lookup continues backwards in time
249                                         $this->maxId = $maxId;
250                                 }
251
252                                 if (count($selected_items) < $this->itemsPerPage) {
253                                         $items = $this->getRawChannelItems();
254                                 }
255                         }
256                 } else {
257                         $selected_items = $items;
258                 }
259
260                 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
261                 $this->setItemsSeenByCondition($condition);
262
263                 return $selected_items;
264         }
265
266         /**
267          * Database query for the channel page
268          *
269          * @return array
270          * @throws \Exception
271          */
272         private function getRawChannelItems()
273         {
274                 $uid = $this->session->getLocalUserId();
275
276                 if ($this->selectedTab == ChannelEntity::WHATSHOT) {
277                         if (!is_null($this->accountType)) {
278                                 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
279                         } else {
280                                 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
281                         }
282                 } elseif ($this->selectedTab == ChannelEntity::FORYOU) {
283                         $cid = Contact::getPublicIdByUserId($uid);
284
285                         $condition = [
286                                 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
287                                 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
288                                 (`owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND (`notify_new_posts` OR `channel-frequency` = ?))))",
289                                 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
290                                 $uid, Contact\User::FREQUENCY_ALWAYS
291                         ];
292                 } elseif ($this->selectedTab == ChannelEntity::FOLLOWERS) {
293                         $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
294                 } elseif ($this->selectedTab == ChannelEntity::SHARERSOFSHARERS) {
295                         $cid = Contact::getPublicIdByUserId($uid);
296
297                         // @todo Suggest posts from contacts that are followed most by our followers
298                         $condition = [
299                                 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
300                                 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
301                                 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
302                                 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
303                         ];
304                 } elseif ($this->selectedTab == ChannelEntity::IMAGE) {
305                         $condition = ["`media-type` & ?", 1];
306                 } elseif ($this->selectedTab == ChannelEntity::VIDEO) {
307                         $condition = ["`media-type` & ?", 2];
308                 } elseif ($this->selectedTab == ChannelEntity::AUDIO) {
309                         $condition = ["`media-type` & ?", 4];
310                 } elseif ($this->selectedTab == ChannelEntity::LANGUAGE) {
311                         $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", User::getLanguageCode($uid)];
312                 } elseif (is_numeric($this->selectedTab)) {
313                         $condition = $this->getUserChannelConditions($this->selectedTab, $this->session->getLocalUserId());
314                 }
315
316                 if ($this->selectedTab != ChannelEntity::LANGUAGE) {
317                         $condition = $this->addLanguageCondition($uid, $condition);
318                 }
319
320                 $condition = DBA::mergeConditions($condition, ["(NOT `restricted` OR EXISTS(SELECT `id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = `post-engagement`.`uri-id`))", $uid]);
321
322                 $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]);
323
324                 if (($this->selectedTab != ChannelEntity::WHATSHOT) && !is_null($this->accountType)) {
325                         $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
326                 }
327
328                 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
329
330                 if (!empty($this->itemUriId)) {
331                         $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
332                 } else {
333                         if ($this->noSharer) {
334                                 $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()]);
335                         }
336
337                         if (isset($this->maxId)) {
338                                 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
339                         }
340
341                         if (isset($this->minId)) {
342                                 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
343
344                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
345                                 if (!isset($this->maxId)) {
346                                         $params['order']['created'] = false;
347                                 }
348                         }
349                 }
350
351                 $items = [];
352                 $result = $this->database->select('post-engagement', ['uri-id', 'created', 'owner-id', 'comments', 'activities'], $condition, $params);
353                 if ($this->database->errorNo()) {
354                         throw new \Exception($this->database->errorMessage(), $this->database->errorNo());
355                 }
356
357                 while ($item = $this->database->fetch($result)) {
358                         $items[$item['uri-id']] = $item;
359                 }
360                 $this->database->close($result);
361
362                 if (empty($items)) {
363                         return [];
364                 }
365
366                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
367                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
368                         $items = array_reverse($items, true);
369                 }
370
371                 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
372                 $this->setItemsSeenByCondition($condition);
373
374                 return $items;
375         }
376
377         private function getUserChannelConditions(int $id, int $uid): array
378         {
379                 $channel = $this->channelRepository->selectById($id, $uid);
380                 if (empty($channel)) {
381                         return [];
382                 }
383
384                 $condition = [];
385
386                 if (!empty($channel->circle)) {
387                         if ($channel->circle == -1) {
388                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))", $uid, Contact::SHARING, Contact::FRIEND];
389                         } elseif ($channel->circle == -2) {
390                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
391                         } elseif ($channel->circle == -3) {
392                                 $condition = ["EXISTS(SELECT `uri-id` FROM `post-thread-user` WHERE `uid` = ? AND `post-thread-user`.`uri-id` = `post-engagement`.`uri-id`)", $uid];
393                         } elseif ($channel->circle > 0) {
394                                 $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]);
395                         }
396                 }
397
398                 if (!empty($channel->fullTextSearch)) {
399                         $search = $channel->fullTextSearch;
400                         foreach (Engagement::KEYWORDS as $keyword) {
401                                 $search = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $search);
402                         }
403                         $condition = DBA::mergeConditions($condition, ["MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", $search]);
404                 }
405
406                 if (!empty($channel->includeTags)) {
407                         $search       = explode(',', mb_strtolower($channel->includeTags));
408                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
409                         $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));
410                 }
411
412                 if (!empty($channel->excludeTags)) {
413                         $search       = explode(',', mb_strtolower($channel->excludeTags));
414                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
415                         $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));
416                 }
417
418                 if (!empty($channel->mediaType)) {
419                         $condition = DBA::mergeConditions($condition, ["`media-type` & ?", $channel->mediaType]);
420                 }
421
422                 // For "addLanguageCondition" to work, the condition must not be empty
423                 return $condition ?: ["true"];
424         }
425
426         private function addLanguageCondition(int $uid, array $condition): array
427         {
428                 $conditions = [];
429                 $languages  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($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 (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
436                 }
437                 return $condition;
438         }
439
440         private function getMedianComments(int $uid, int $divider): int
441         {
442                 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($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  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($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                 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
524                 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
525                         $count          = 1;
526                         $previousauthor = '';
527                         $numposts       = 0;
528                         $selected_items = [];
529
530                         while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
531                                 foreach ($items as $item) {
532                                         if ($previousauthor == $item["author-link"]) {
533                                                 ++$numposts;
534                                         } else {
535                                                 $numposts = 0;
536                                         }
537                                         $previousauthor = $item["author-link"];
538
539                                         if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
540                                                 $selected_items[] = $item;
541                                         }
542                                 }
543
544                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
545                                 // sorted in chronologically decreasing order
546                                 if (isset($this->minId)) {
547                                         $this->minId = $items[0]['received'];
548                                 } else {
549                                         // In any other case, the lookup continues backwards in time
550                                         $this->maxId = $items[count($items) - 1]['received'];
551                                 }
552
553                                 $items = $this->selectItems();
554                         }
555                 } else {
556                         $selected_items = $items;
557                 }
558
559                 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
560                 $this->setItemsSeenByCondition($condition);
561
562                 return $selected_items;
563         }
564
565         /**
566          * Database query for the community page
567          *
568          * @return array
569          * @throws \Exception
570          * @TODO Move to repository/factory
571          */
572         private function selectItems()
573         {
574                 if ($this->selectedTab == 'local') {
575                         $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
576                 } elseif ($this->selectedTab == 'global') {
577                         $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
578                 } else {
579                         return [];
580                 }
581
582                 if (!is_null($this->accountType)) {
583                         $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
584                 }
585
586                 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
587
588                 if (!empty($this->itemUriId)) {
589                         $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
590                 } else {
591                         if ($this->session->getLocalUserId() && $this->noSharer) {
592                                 $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()]);
593                         }
594
595                         if (isset($this->maxId)) {
596                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
597                         }
598
599                         if (isset($this->minId)) {
600                                 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
601
602                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
603                                 if (!isset($this->maxId)) {
604                                         $params['order']['received'] = false;
605                                 }
606                         }
607                 }
608
609                 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-link'], $condition, $params);
610
611                 $items = Post::toArray($r);
612                 if (empty($items)) {
613                         return [];
614                 }
615
616                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
617                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
618                         $items = array_reverse($items);
619                 }
620
621                 return $items;
622         }
623
624         /**
625          * Sets items as seen
626          *
627          * @param array $condition The array with the SQL condition
628          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
629          */
630         protected function setItemsSeenByCondition(array $condition)
631         {
632                 if (empty($condition)) {
633                         return;
634                 }
635
636                 $unseen = Post::exists($condition);
637
638                 if ($unseen) {
639                         /// @todo handle huge "unseen" updates in the background to avoid timeout errors
640                         Item::update(['unseen' => false], $condition);
641                 }
642         }
643 }