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