]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Timeline.php
Merge pull request #13676 from MrPetovan/bug/13673-markers-json-output
[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\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
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 UserDefinedChannel */
85         protected $channelRepository;
86
87         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 = [])
88         {
89                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
90
91                 $this->channelRepository = $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]') = ?", 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                 if ($this->database->errorNo()) {
351                         throw new \Exception($this->database->errorMessage(), $this->database->errorNo());
352                 }
353
354                 while ($item = $this->database->fetch($result)) {
355                         $items[$item['uri-id']] = $item;
356                 }
357                 $this->database->close($result);
358
359                 if (empty($items)) {
360                         return [];
361                 }
362
363                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
364                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
365                         $items = array_reverse($items, true);
366                 }
367
368                 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
369                 $this->setItemsSeenByCondition($condition);
370
371                 return $items;
372         }
373
374         private function getUserChannelConditions(int $id, int $uid): array
375         {
376                 $channel = $this->channelRepository->selectById($id, $uid);
377                 if (empty($channel)) {
378                         return [];
379                 }
380
381                 $condition = [];
382
383                 if (!empty($channel->circle)) {
384                         if ($channel->circle == -1) {
385                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))", $uid, Contact::SHARING, Contact::FRIEND];
386                         } elseif ($channel->circle == -2) {
387                                 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
388                         } elseif ($channel->circle == -3) {
389                                 $condition = ["EXISTS(SELECT `uri-id` FROM `post-thread-user` WHERE `uid` = ? AND `post-thread-user`.`uri-id` = `post-engagement`.`uri-id`)", $uid];
390                         } elseif ($channel->circle > 0) {
391                                 $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]);
392                         }
393                 }
394
395                 if (!empty($channel->fullTextSearch)) {
396                         $search = $channel->fullTextSearch;
397                         foreach (Engagement::KEYWORDS as $keyword) {
398                                 $search = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $search);
399                         }
400                         $condition = DBA::mergeConditions($condition, ["MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", $search]);
401                 }
402
403                 if (!empty($channel->includeTags)) {
404                         $search       = explode(',', mb_strtolower($channel->includeTags));
405                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
406                         $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));
407                 }
408
409                 if (!empty($channel->excludeTags)) {
410                         $search       = explode(',', mb_strtolower($channel->excludeTags));
411                         $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
412                         $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));
413                 }
414
415                 if (!empty($channel->mediaType)) {
416                         $condition = DBA::mergeConditions($condition, ["`media-type` & ?", $channel->mediaType]);
417                 }
418
419                 // For "addLanguageCondition" to work, the condition must not be empty
420                 return $condition ?: ["true"];
421         }
422
423         private function addLanguageCondition(int $uid, array $condition): array
424         {
425                 $conditions = [];
426                 $languages  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
427                 foreach ($languages as $language) {
428                         $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
429                         $condition[]  = $language;
430                 }
431                 if (!empty($conditions)) {
432                         $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
433                 }
434                 return $condition;
435         }
436
437         private function getMedianComments(int $uid, int $divider): int
438         {
439                 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
440                 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
441                 $comments  = $this->cache->get($cache_key);
442                 if (!empty($comments)) {
443                         return $comments;
444                 }
445
446                 $condition = ["`contact-type` != ? AND `comments` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
447                 $condition = $this->addLanguageCondition($uid, $condition);
448
449                 $limit    = $this->database->count('post-engagement', $condition) / $divider;
450                 $post     = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
451                 $comments = $post[0]['comments'] ?? 0;
452                 if (empty($comments)) {
453                         return 0;
454                 }
455
456                 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
457                 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
458                 return $comments;
459         }
460
461         private function getMedianActivities(int $uid, int $divider): int
462         {
463                 $languages  = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
464                 $cache_key  = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
465                 $activities = $this->cache->get($cache_key);
466                 if (!empty($activities)) {
467                         return $activities;
468                 }
469
470                 $condition = ["`contact-type` != ? AND `activities` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
471                 $condition = $this->addLanguageCondition($uid, $condition);
472
473                 $limit      = $this->database->count('post-engagement', $condition) / $divider;
474                 $post       = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
475                 $activities = $post[0]['activities'] ?? 0;
476                 if (empty($activities)) {
477                         return 0;
478                 }
479
480                 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
481                 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
482                 return $activities;
483         }
484
485         private function getMedianRelationThreadScore(int $cid, int $divider): int
486         {
487                 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
488                 $score     = $this->cache->get($cache_key);
489                 if (!empty($score)) {
490                         return $score;
491                 }
492
493                 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
494
495                 $limit    = $this->database->count('contact-relation', $condition) / $divider;
496                 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
497                 $score    = $relation[0]['relation-thread-score'] ?? 0;
498                 if (empty($score)) {
499                         return 0;
500                 }
501
502                 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
503                 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
504                 return $score;
505         }
506
507         /**
508          * Computes the displayed items.
509          *
510          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
511          * so we may have to retrieve more content beyond the first query
512          *
513          * @return array
514          * @throws \Exception
515          */
516         protected function getCommunityItems()
517         {
518                 $items = $this->selectItems();
519
520                 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
521                 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
522                         $count          = 1;
523                         $previousauthor = '';
524                         $numposts       = 0;
525                         $selected_items = [];
526
527                         while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
528                                 foreach ($items as $item) {
529                                         if ($previousauthor == $item["author-link"]) {
530                                                 ++$numposts;
531                                         } else {
532                                                 $numposts = 0;
533                                         }
534                                         $previousauthor = $item["author-link"];
535
536                                         if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
537                                                 $selected_items[] = $item;
538                                         }
539                                 }
540
541                                 // If we're looking at a "previous page", the lookup continues forward in time because the list is
542                                 // sorted in chronologically decreasing order
543                                 if (isset($this->minId)) {
544                                         $this->minId = $items[0]['received'];
545                                 } else {
546                                         // In any other case, the lookup continues backwards in time
547                                         $this->maxId = $items[count($items) - 1]['received'];
548                                 }
549
550                                 $items = $this->selectItems();
551                         }
552                 } else {
553                         $selected_items = $items;
554                 }
555
556                 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
557                 $this->setItemsSeenByCondition($condition);
558
559                 return $selected_items;
560         }
561
562         /**
563          * Database query for the community page
564          *
565          * @return array
566          * @throws \Exception
567          * @TODO Move to repository/factory
568          */
569         private function selectItems()
570         {
571                 if ($this->selectedTab == 'local') {
572                         $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
573                 } elseif ($this->selectedTab == 'global') {
574                         $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
575                 } else {
576                         return [];
577                 }
578
579                 if (!is_null($this->accountType)) {
580                         $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
581                 }
582
583                 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
584
585                 if (!empty($this->itemUriId)) {
586                         $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
587                 } else {
588                         if ($this->session->getLocalUserId() && $this->noSharer) {
589                                 $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()]);
590                         }
591
592                         if (isset($this->maxId)) {
593                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
594                         }
595
596                         if (isset($this->minId)) {
597                                 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
598
599                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
600                                 if (!isset($this->maxId)) {
601                                         $params['order']['received'] = false;
602                                 }
603                         }
604                 }
605
606                 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-link'], $condition, $params);
607
608                 $items = Post::toArray($r);
609                 if (empty($items)) {
610                         return [];
611                 }
612
613                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
614                 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
615                         $items = array_reverse($items);
616                 }
617
618                 return $items;
619         }
620
621         /**
622          * Sets items as seen
623          *
624          * @param array $condition The array with the SQL condition
625          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
626          */
627         protected function setItemsSeenByCondition(array $condition)
628         {
629                 if (empty($condition)) {
630                         return;
631                 }
632
633                 $unseen = Post::exists($condition);
634
635                 if ($unseen) {
636                         /// @todo handle huge "unseen" updates in the background to avoid timeout errors
637                         Item::update(['unseen' => false], $condition);
638                 }
639         }
640 }