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