]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation.php
1d7430e1933a0b97dd0225296b20bfeb5a5ff219
[friendica.git] / src / Content / Conversation.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\Content;
23
24 use Friendica\App;
25 use Friendica\App\Arguments;
26 use Friendica\App\BaseURL;
27 use Friendica\BaseModule;
28 use Friendica\Core\ACL;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session\Capability\IHandleUserSessions;
36 use Friendica\Core\Theme;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Item as ItemModel;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Model\Verb;
44 use Friendica\Object\Post as PostObject;
45 use Friendica\Object\Thread;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Profiler;
50 use Friendica\Util\Strings;
51 use Friendica\Util\Temporal;
52 use Psr\Log\LoggerInterface;
53
54 class Conversation
55 {
56         const MODE_COMMUNITY     = 'community';
57         const MODE_CONTACTS      = 'contacts';
58         const MODE_CONTACT_POSTS = 'contact-posts';
59         const MODE_DISPLAY       = 'display';
60         const MODE_FILED         = 'filed';
61         const MODE_NETWORK       = 'network';
62         const MODE_NOTES         = 'notes';
63         const MODE_SEARCH        = 'search';
64         const MODE_PROFILE       = 'profile';
65
66         /** @var Activity */
67         private $activity;
68         /** @var L10n */
69         private $l10n;
70         /** @var Profiler */
71         private $profiler;
72         /** @var LoggerInterface */
73         private $logger;
74         /** @var Item */
75         private $item;
76         /** @var App\Arguments */
77         private $args;
78         /** @var IManagePersonalConfigValues */
79         private $pConfig;
80         /** @var BaseURL */
81         private $baseURL;
82         /** @var IManageConfigValues */
83         private $config;
84         /** @var App */
85         private $app;
86         /** @var App\Page */
87         private $page;
88         /** @var App\Mode */
89         private $mode;
90         /** @var IHandleUserSessions */
91         private $session;
92
93         public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app, IHandleUserSessions $session)
94         {
95                 $this->activity = $activity;
96                 $this->item     = $item;
97                 $this->config   = $config;
98                 $this->mode     = $mode;
99                 $this->baseURL  = $baseURL;
100                 $this->profiler = $profiler;
101                 $this->logger   = $logger;
102                 $this->l10n     = $l10n;
103                 $this->args     = $args;
104                 $this->pConfig  = $pConfig;
105                 $this->page     = $page;
106                 $this->app      = $app;
107                 $this->session  = $session;
108         }
109
110         /**
111          * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
112          *
113          * Increments the count of each matching activity and adds a link to the author as needed.
114          *
115          * @param array  $activity
116          * @param array &$conv_responses (already created with builtin activity structure)
117          * @return void
118          * @throws ImagickException
119          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120          */
121         public function builtinActivityPuller(array $activity, array &$conv_responses)
122         {
123                 $thread_parent = $activity['thr-parent-row'] ?? [];
124
125                 foreach ($conv_responses as $mode => $v) {
126                         $sparkle = '';
127
128                         switch ($mode) {
129                                 case 'like':
130                                         $verb = Activity::LIKE;
131                                         break;
132                                 case 'dislike':
133                                         $verb = Activity::DISLIKE;
134                                         break;
135                                 case 'attendyes':
136                                         $verb = Activity::ATTEND;
137                                         break;
138                                 case 'attendno':
139                                         $verb = Activity::ATTENDNO;
140                                         break;
141                                 case 'attendmaybe':
142                                         $verb = Activity::ATTENDMAYBE;
143                                         break;
144                                 case 'announce':
145                                         $verb = Activity::ANNOUNCE;
146                                         break;
147                                 default:
148                                         return;
149                         }
150
151                         if (!empty($activity['verb']) && $this->activity->match($activity['verb'], $verb) && ($activity['gravity'] != ItemModel::GRAVITY_PARENT)) {
152                                 $author = [
153                                         'uid'     => 0,
154                                         'id'      => $activity['author-id'],
155                                         'network' => $activity['author-network'],
156                                         'url'     => $activity['author-link']
157                                 ];
158                                 $url = Contact::magicLinkByContact($author);
159                                 if (strpos($url, 'contact/redir/') === 0) {
160                                         $sparkle = ' class="sparkle" ';
161                                 }
162
163                                 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
164
165                                 if (empty($activity['thr-parent-id'])) {
166                                         $activity['thr-parent-id'] = $activity['parent-uri-id'];
167                                 }
168
169                                 // Skip when the causer of the parent is the same as the author of the announce
170                                 if (($verb == Activity::ANNOUNCE) && !empty($thread_parent['causer-id']) && ($thread_parent['causer-id'] == $activity['author-id'])) {
171                                         continue;
172                                 }
173
174                                 if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
175                                         $conv_responses[$mode][$activity['thr-parent-id']] = [
176                                                 'links' => [],
177                                                 'self'  => 0,
178                                         ];
179                                 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
180                                         // only list each unique author once
181                                         continue;
182                                 }
183
184                                 if ($this->session->getPublicContactId() == $activity['author-id']) {
185                                         $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
186                                 }
187
188                                 $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
189
190                                 // there can only be one activity verb per item so if we found anything, we can stop looking
191                                 return;
192                         }
193                 }
194         }
195
196         /**
197          * Format the activity text for an item/photo/video
198          *
199          * @param array  $links = array of pre-linked names of actors
200          * @param string $verb  = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
201          * @param int    $id    = item id
202          * @return string formatted text
203          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
204          */
205         public function formatActivity(array $links, string $verb, int $id): string
206         {
207                 $this->profiler->startRecording('rendering');
208                 $o        = '';
209                 $expanded = '';
210                 $phrase   = '';
211
212                 $total = count($links);
213                 if ($total == 1) {
214                         $likers = $links[0];
215
216                         // Phrase if there is only one liker. In other cases it will be uses for the expanded
217                         // list which show all likers
218                         switch ($verb) {
219                                 case 'like':
220                                         $phrase = $this->l10n->t('%s likes this.', $likers);
221                                         break;
222                                 case 'dislike':
223                                         $phrase = $this->l10n->t('%s doesn\'t like this.', $likers);
224                                         break;
225                                 case 'attendyes':
226                                         $phrase = $this->l10n->t('%s attends.', $likers);
227                                         break;
228                                 case 'attendno':
229                                         $phrase = $this->l10n->t('%s doesn\'t attend.', $likers);
230                                         break;
231                                 case 'attendmaybe':
232                                         $phrase = $this->l10n->t('%s attends maybe.', $likers);
233                                         break;
234                                 case 'announce':
235                                         $phrase = $this->l10n->t('%s reshared this.', $likers);
236                                         break;
237                         }
238                 } elseif ($total > 1) {
239                         if ($total < $this->config->get('system', 'max_likers')) {
240                                 $likers = implode(', ', array_slice($links, 0, -1));
241                                 $likers .= ' ' . $this->l10n->t('and') . ' ' . $links[count($links) - 1];
242                         } else {
243                                 $likers = implode(', ', array_slice($links, 0, $this->config->get('system', 'max_likers') - 1));
244                                 $likers .= ' ' . $this->l10n->t('and %d other people', $total - $this->config->get('system', 'max_likers'));
245                         }
246
247                         $spanatts = "class=\"btn btn-link fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
248
249                         $explikers = '';
250                         switch ($verb) {
251                                 case 'like':
252                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> like this', $spanatts, $total);
253                                         $explikers = $this->l10n->t('%s like this.', $likers);
254                                         break;
255                                 case 'dislike':
256                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> don\'t like this', $spanatts, $total);
257                                         $explikers = $this->l10n->t('%s don\'t like this.', $likers);
258                                         break;
259                                 case 'attendyes':
260                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> attend', $spanatts, $total);
261                                         $explikers = $this->l10n->t('%s attend.', $likers);
262                                         break;
263                                 case 'attendno':
264                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> don\'t attend', $spanatts, $total);
265                                         $explikers = $this->l10n->t('%s don\'t attend.', $likers);
266                                         break;
267                                 case 'attendmaybe':
268                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> attend maybe', $spanatts, $total);
269                                         $explikers = $this->l10n->t('%s attend maybe.', $likers);
270                                         break;
271                                 case 'announce':
272                                         $phrase    = $this->l10n->t('<button type="button" %1$s>%2$d people</button> reshared this', $spanatts, $total);
273                                         $explikers = $this->l10n->t('%s reshared this.', $likers);
274                                         break;
275                         }
276
277                         $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . '</p>';
278                 }
279
280                 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
281                         '$phrase' => $phrase,
282                         '$type'   => $verb,
283                         '$id'     => $id
284                 ]);
285                 $o .= $expanded;
286
287                 $this->profiler->stopRecording();
288                 return $o;
289         }
290
291         public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
292         {
293                 $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
294                 if (empty($user['uid'])) {
295                         return '';
296                 }
297
298                 $this->profiler->startRecording('rendering');
299                 $o = '';
300
301                 $x['allow_location']   = $x['allow_location']   ?? $user['allow_location'];
302                 $x['default_location'] = $x['default_location'] ?? $user['default-location'];
303                 $x['nickname']         = $x['nickname']         ?? $user['nickname'];
304                 $x['lockstate']        = $x['lockstate']        ?? ACL::getLockstateForUserId($user['uid']) ? 'lock' : 'unlock';
305                 $x['acl']              = $x['acl']              ?? ACL::getFullSelectorHTML($this->page, $user['uid'], true);
306                 $x['bang']             = $x['bang']             ?? '';
307                 $x['visitor']          = $x['visitor']          ?? 'block';
308                 $x['is_owner']         = $x['is_owner']         ?? true;
309                 $x['profile_uid']      = $x['profile_uid']      ?? $this->session->getLocalUserId();
310
311
312                 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
313
314                 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
315                 $this->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
316                         '$newpost'   => 'true',
317                         '$baseurl'   => $this->baseURL,
318                         '$geotag'    => $geotag,
319                         '$nickname'  => $x['nickname'],
320                         '$ispublic'  => $this->l10n->t('Visible to <strong>everybody</strong>'),
321                         '$linkurl'   => $this->l10n->t('Please enter a image/video/audio/webpage URL:'),
322                         '$term'      => $this->l10n->t('Tag term:'),
323                         '$fileas'    => $this->l10n->t('Save to Folder:'),
324                         '$whereareu' => $this->l10n->t('Where are you right now?'),
325                         '$delitems'  => $this->l10n->t("Delete item\x28s\x29?"),
326                         '$is_mobile' => $this->mode->isMobile(),
327                 ]);
328
329                 $jotplugins = '';
330                 Hook::callAll('jot_tool', $jotplugins);
331
332                 if ($this->config->get('system', 'set_creation_date')) {
333                         $created_at = Temporal::getDateTimeField(
334                                 new \DateTime(DBA::NULL_DATETIME),
335                                 new \DateTime('now'),
336                                 null,
337                                 $this->l10n->t('Created at'),
338                                 'created_at'
339                         );
340                 } else {
341                         $created_at = '';
342                 }
343
344                 $tpl = Renderer::getMarkupTemplate('jot.tpl');
345
346                 $o .= Renderer::replaceMacros($tpl, [
347                         '$new_post'            => $this->l10n->t('New Post'),
348                         '$return_path'         => $this->args->getQueryString(),
349                         '$action'              => 'item',
350                         '$share'               => ($x['button'] ?? '') ?: $this->l10n->t('Share'),
351                         '$loading'             => $this->l10n->t('Loading...'),
352                         '$upload'              => $this->l10n->t('Upload photo'),
353                         '$shortupload'         => $this->l10n->t('upload photo'),
354                         '$attach'              => $this->l10n->t('Attach file'),
355                         '$shortattach'         => $this->l10n->t('attach file'),
356                         '$edbold'              => $this->l10n->t('Bold'),
357                         '$editalic'            => $this->l10n->t('Italic'),
358                         '$eduline'             => $this->l10n->t('Underline'),
359                         '$edquote'             => $this->l10n->t('Quote'),
360                         '$edcode'              => $this->l10n->t('Code'),
361                         '$edimg'               => $this->l10n->t('Image'),
362                         '$edurl'               => $this->l10n->t('Link'),
363                         '$edattach'            => $this->l10n->t('Link or Media'),
364                         '$edvideo'             => $this->l10n->t('Video'),
365                         '$setloc'              => $this->l10n->t('Set your location'),
366                         '$shortsetloc'         => $this->l10n->t('set location'),
367                         '$noloc'               => $this->l10n->t('Clear browser location'),
368                         '$shortnoloc'          => $this->l10n->t('clear location'),
369                         '$title'               => $x['title'] ?? '',
370                         '$placeholdertitle'    => $this->l10n->t('Set title'),
371                         '$category'            => $x['category'] ?? '',
372                         '$placeholdercategory' => Feature::isEnabled($this->session->getLocalUserId(), 'categories') ? $this->l10n->t("Categories \x28comma-separated list\x29") : '',
373                         '$scheduled_at'        => Temporal::getDateTimeField(
374                                 new \DateTime(),
375                                 new \DateTime('now + 6 months'),
376                                 null,
377                                 $this->l10n->t('Scheduled at'),
378                                 'scheduled_at'
379                         ),
380                         '$created_at'   => $created_at,
381                         '$wait'         => $this->l10n->t('Please wait'),
382                         '$permset'      => $this->l10n->t('Permission settings'),
383                         '$shortpermset' => $this->l10n->t('Permissions'),
384                         '$wall'         => $notes_cid ? 0 : 1,
385                         '$posttype'     => $notes_cid ? ItemModel::PT_PERSONAL_NOTE : ItemModel::PT_ARTICLE,
386                         '$content'      => $x['content'] ?? '',
387                         '$post_id'      => $x['post_id'] ?? '',
388                         '$baseurl'      => $this->baseURL,
389                         '$defloc'       => $x['default_location'],
390                         '$visitor'      => $x['visitor'],
391                         '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
392                         '$public'       => $this->l10n->t('Public post'),
393                         '$lockstate'    => $x['lockstate'],
394                         '$bang'         => $x['bang'],
395                         '$profile_uid'  => $x['profile_uid'],
396                         '$preview'      => $this->l10n->t('Preview'),
397                         '$jotplugins'   => $jotplugins,
398                         '$notes_cid'    => $notes_cid,
399                         '$cancel'       => $this->l10n->t('Cancel'),
400                         '$rand_num'     => Crypto::randomDigits(12),
401
402                         // ACL permissions box
403                         '$acl' => $x['acl'],
404
405                         //jot nav tab (used in some themes)
406                         '$message' => $this->l10n->t('Message'),
407                         '$browser' => $this->l10n->t('Browser'),
408
409                         '$compose_link_title'  => $this->l10n->t('Open Compose page'),
410                         '$always_open_compose' => $this->pConfig->get($this->session->getLocalUserId(), 'frio', 'always_open_compose', false),
411
412                         // Dropzone
413                         '$max_imagesize' => round(\Friendica\Util\Strings::getBytesFromShorthand($this->config->get('system', 'maximagesize')) / 1000000, 1),
414
415                 ]);
416
417
418                 if ($popup == true) {
419                         $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
420                 }
421
422                 $this->profiler->stopRecording();
423                 return $o;
424         }
425
426         /**
427          * "Render" a conversation or list of items for HTML display.
428          * There are two major forms of display:
429          *      - Sequential or unthreaded ("New Item View" or search results)
430          *      - conversation view
431          * The $mode parameter decides between the various renderings and also
432          * figures out how to determine page owner and other contextual items
433          * that are based on unique features of the calling module.
434          * @param array  $items
435          * @param string $mode
436          * @param        $update @TODO Which type?
437          * @param bool   $preview
438          * @param string $order
439          * @param int    $uid
440          * @return string
441          * @throws ImagickException
442          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
443          */
444         public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
445         {
446                 $this->profiler->startRecording('rendering');
447
448                 $this->page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
449                 $this->page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
450                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
451                 $this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
452
453                 $live_update_div = '';
454
455                 $blocklist = $this->getBlocklist();
456
457                 $previewing = (($preview) ? ' preview ' : '');
458
459                 if ($mode === self::MODE_NETWORK) {
460                         $items = $this->addChildren($items, false, $order, $uid, $mode);
461                         if (!$update) {
462                                 /*
463                                 * The special div is needed for liveUpdate to kick in for this page.
464                                 * We only launch liveUpdate if you aren't filtering in some incompatible
465                                 * way and also you aren't writing a comment (discovered in javascript).
466                                 */
467                                 $live_update_div = '<div id="live-network"></div>' . "\r\n"
468                                         . "<script> var profile_uid = " . $_SESSION['uid']
469                                         . "; var netargs = '" . substr($this->args->getCommand(), 8)
470                                         . '?f='
471                                         . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
472                                         . (!empty($_GET['search'])    ? '&search='    . rawurlencode($_GET['search'])    : '')
473                                         . (!empty($_GET['star'])      ? '&star='      . rawurlencode($_GET['star'])      : '')
474                                         . (!empty($_GET['order'])     ? '&order='     . rawurlencode($_GET['order'])     : '')
475                                         . (!empty($_GET['bmark'])     ? '&bmark='     . rawurlencode($_GET['bmark'])     : '')
476                                         . (!empty($_GET['liked'])     ? '&liked='     . rawurlencode($_GET['liked'])     : '')
477                                         . (!empty($_GET['conv'])      ? '&conv='      . rawurlencode($_GET['conv'])      : '')
478                                         . (!empty($_GET['nets'])      ? '&nets='      . rawurlencode($_GET['nets'])      : '')
479                                         . (!empty($_GET['cmin'])      ? '&cmin='      . rawurlencode($_GET['cmin'])      : '')
480                                         . (!empty($_GET['cmax'])      ? '&cmax='      . rawurlencode($_GET['cmax'])      : '')
481                                         . (!empty($_GET['file'])      ? '&file='      . rawurlencode($_GET['file'])      : '')
482
483                                         . "'; </script>\r\n";
484                         }
485                 } elseif ($mode === self::MODE_PROFILE) {
486                         $items = $this->addChildren($items, false, $order, $uid, $mode);
487
488                         if (!$update) {
489                                 $tab = !empty($_GET['tab']) ? trim($_GET['tab']) : 'posts';
490
491                                 if ($tab === 'posts') {
492                                         /*
493                                         * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
494                                         * because browser prefetching might change it on us. We have to deliver it with the page.
495                                         */
496
497                                         $live_update_div = '<div id="live-profile"></div>' . "\r\n"
498                                                 . "<script> var profile_uid = " . $uid
499                                                 . "; var netargs = '?f='; </script>\r\n";
500                                 }
501                         }
502                 } elseif ($mode === self::MODE_NOTES) {
503                         $items = $this->addChildren($items, false, $order, $this->session->getLocalUserId(), $mode);
504
505                         if (!$update) {
506                                 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
507                                         . "<script> var profile_uid = " . $this->session->getLocalUserId()
508                                         . "; var netargs = '?f='; </script>\r\n";
509                         }
510                 } elseif ($mode === self::MODE_DISPLAY) {
511                         $items = $this->addChildren($items, false, $order, $uid, $mode);
512
513                         if (!$update) {
514                                 $live_update_div = '<div id="live-display"></div>' . "\r\n"
515                                         . "<script> var profile_uid = " . ($this->session->getLocalUserId() ?: 0) . ";"
516                                         . "</script>";
517                         }
518                 } elseif ($mode === self::MODE_COMMUNITY) {
519                         $items = $this->addChildren($items, true, $order, $uid, $mode);
520
521                         if (!$update) {
522                                 $live_update_div = '<div id="live-community"></div>' . "\r\n"
523                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 10)
524                                         . '?f='
525                                         . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
526                                         . (!empty($_GET['accounttype']) ? '&accounttype=' . rawurlencode($_GET['accounttype']) : '')
527                                         . "'; </script>\r\n";
528                         }
529                 } elseif ($mode === self::MODE_CONTACTS) {
530                         $items = $this->addChildren($items, false, $order, $uid, $mode);
531
532                         if (!$update) {
533                                 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
534                                         . "<script> var profile_uid = -1; var netargs = '" . substr($this->args->getCommand(), 8)
535                                         ."?f='; </script>\r\n";
536                         }
537                 } elseif ($mode === self::MODE_SEARCH) {
538                         $live_update_div = '<div id="live-search"></div>' . "\r\n";
539                 }
540
541                 $page_dropping = $this->session->getLocalUserId() && $this->session->getLocalUserId() == $uid && $mode != self::MODE_SEARCH;
542
543                 if (!$update) {
544                         $_SESSION['return_path'] = $this->args->getQueryString();
545                 }
546
547                 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
548                 Hook::callAll('conversation_start', $cb);
549
550                 $items = $cb['items'];
551
552                 $conv_responses = [
553                         'like'        => [],
554                         'dislike'     => [],
555                         'attendyes'   => [],
556                         'attendno'    => [],
557                         'attendmaybe' => [],
558                         'announce'    => [],
559                 ];
560
561                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
562                         unset($conv_responses['dislike']);
563                 }
564
565                 // array with html for each thread (parent+comments)
566                 $threads   = [];
567                 $threadsid = -1;
568
569                 $page_template     = Renderer::getMarkupTemplate("conversation.tpl");
570                 $formSecurityToken = BaseModule::getFormSecurityToken('contact_action');
571
572                 if (!empty($items)) {
573                         if (in_array($mode, [self::MODE_COMMUNITY, self::MODE_CONTACTS, self::MODE_PROFILE])) {
574                                 $writable = true;
575                         } else {
576                                 $writable = $items[0]['writable'] || ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
577                         }
578
579                         if (!$this->session->getLocalUserId()) {
580                                 $writable = false;
581                         }
582
583                         if (in_array($mode, [self::MODE_FILED, self::MODE_SEARCH, self::MODE_CONTACT_POSTS])) {
584
585                                 /*
586                                 * "New Item View" on network page or search page results
587                                 * - just loop through the items and format them minimally for display
588                                 */
589
590                                 $tpl = 'search_item.tpl';
591
592                                 $uriids = [];
593
594                                 foreach ($items as $item) {
595                                         if (in_array($item['uri-id'], $uriids)) {
596                                                 continue;
597                                         }
598
599                                         $uriids[] = $item['uri-id'];
600
601                                         if (!$this->item->isVisibleActivity($item)) {
602                                                 continue;
603                                         }
604
605                                         if (in_array($item['author-id'], $blocklist)) {
606                                                 continue;
607                                         }
608
609                                         $threadsid++;
610
611                                         // prevent private email from leaking.
612                                         if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
613                                                 continue;
614                                         }
615
616                                         $profile_name = $item['author-name'];
617                                         if (!empty($item['author-link']) && empty($item['author-name'])) {
618                                                 $profile_name = $item['author-link'];
619                                         }
620
621                                         $tags = Tag::populateFromItem($item);
622
623                                         $author       = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']];
624                                         $profile_link = Contact::magicLinkByContact($author);
625
626                                         $sparkle = '';
627                                         if (strpos($profile_link, 'contact/redir/') === 0) {
628                                                 $sparkle = ' sparkle';
629                                         }
630
631                                         $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
632                                         Hook::callAll('render_location', $locate);
633                                         $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
634
635                                         $this->item->localize($item);
636                                         if ($mode === self::MODE_FILED) {
637                                                 $dropping = true;
638                                         } else {
639                                                 $dropping = false;
640                                         }
641
642                                         $drop = [
643                                                 'dropping' => $dropping,
644                                                 'pagedrop' => $page_dropping,
645                                                 'select'   => $this->l10n->t('Select'),
646                                                 'delete'   => $this->l10n->t('Delete'),
647                                         ];
648
649                                         $likebuttons = [
650                                                 'like'     => null,
651                                                 'dislike'  => null,
652                                                 'share'    => null,
653                                                 'announce' => null,
654                                         ];
655
656                                         if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'hide_dislike')) {
657                                                 unset($likebuttons['dislike']);
658                                         }
659
660                                         $body_html = ItemModel::prepareBody($item, true, $preview);
661
662                                         [$categories, $folders] = $this->item->determineCategoriesTerms($item, $this->session->getLocalUserId());
663
664                                         if (!empty($item['title'])) {
665                                                 $title = $item['title'];
666                                         } elseif (!empty($item['content-warning']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'disable_cw', false)) {
667                                                 $title = ucfirst($item['content-warning']);
668                                         } else {
669                                                 $title = '';
670                                         }
671
672                                         if (!empty($item['featured'])) {
673                                                 $pinned = $this->l10n->t('Pinned item');
674                                         } else {
675                                                 $pinned = '';
676                                         }
677
678                                         $tmp_item = [
679                                                 'template'             => $tpl,
680                                                 'id'                   => ($preview ? 'P0' : $item['id']),
681                                                 'guid'                 => ($preview ? 'Q0' : $item['guid']),
682                                                 'commented'            => $item['commented'],
683                                                 'received'             => $item['received'],
684                                                 'created_date'         => $item['created'],
685                                                 'uriid'                => $item['uri-id'],
686                                                 'network'              => $item['network'],
687                                                 'network_name'         => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
688                                                 'network_icon'         => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
689                                                 'linktitle'            => $this->l10n->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
690                                                 'profile_url'          => $profile_link,
691                                                 'item_photo_menu_html' => $this->item->photoMenu($item, $formSecurityToken),
692                                                 'name'                 => $profile_name,
693                                                 'sparkle'              => $sparkle,
694                                                 'lock'                 => false,
695                                                 'thumb'                => $this->baseURL->remove($this->item->getAuthorAvatar($item)),
696                                                 'title'                => $title,
697                                                 'body_html'            => $body_html,
698                                                 'tags'                 => $tags['tags'],
699                                                 'hashtags'             => $tags['hashtags'],
700                                                 'mentions'             => $tags['mentions'],
701                                                 'implicit_mentions'    => $tags['implicit_mentions'],
702                                                 'txt_cats'             => $this->l10n->t('Categories:'),
703                                                 'txt_folders'          => $this->l10n->t('Filed under:'),
704                                                 'has_cats'             => ((count($categories)) ? 'true' : ''),
705                                                 'has_folders'          => ((count($folders)) ? 'true' : ''),
706                                                 'categories'           => $categories,
707                                                 'folders'              => $folders,
708                                                 'text'                 => strip_tags($body_html),
709                                                 'localtime'            => DateTimeFormat::local($item['created'], 'r'),
710                                                 'utc'                  => DateTimeFormat::utc($item['created'], 'c'),
711                                                 'ago'                  => (($item['app']) ? $this->l10n->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
712                                                 'location_html'        => $location_html,
713                                                 'indent'               => '',
714                                                 'owner_name'           => '',
715                                                 'owner_url'            => '',
716                                                 'owner_photo'          => $this->baseURL->remove($this->item->getOwnerAvatar($item)),
717                                                 'plink'                => ItemModel::getPlink($item),
718                                                 'edpost'               => false,
719                                                 'pinned'               => $pinned,
720                                                 'isstarred'            => 'unstarred',
721                                                 'star'                 => false,
722                                                 'drop'                 => $drop,
723                                                 'vote'                 => $likebuttons,
724                                                 'like_html'            => '',
725                                                 'dislike_html '        => '',
726                                                 'comment_html'         => '',
727                                                 'conv'                 => ($preview ? '' : ['href' => 'display/' . $item['guid'], 'title' => $this->l10n->t('View in context')]),
728                                                 'previewing'           => $previewing,
729                                                 'wait'                 => $this->l10n->t('Please wait'),
730                                                 'thread_level'         => 1,
731                                         ];
732
733                                         $arr = ['item' => $item, 'output' => $tmp_item];
734                                         Hook::callAll('display_item', $arr);
735
736                                         $threads[$threadsid]['id']      = $item['id'];
737                                         $threads[$threadsid]['network'] = $item['network'];
738                                         $threads[$threadsid]['items']   = [$arr['output']];
739                                 }
740                         } else {
741                                 // Normal View
742                                 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
743
744                                 $conv = new Thread($mode, $preview, $writable);
745
746                                 /*
747                                 * get all the topmost parents
748                                 * this shouldn't be needed, as we should have only them in our array
749                                 * But for now, this array respects the old style, just in case
750                                 */
751                                 foreach ($items as $item) {
752                                         if (in_array($item['author-id'], $blocklist)) {
753                                                 continue;
754                                         }
755
756                                         // Can we put this after the visibility check?
757                                         $this->builtinActivityPuller($item, $conv_responses);
758
759                                         // Only add what is visible
760                                         if ($item['network'] === Protocol::MAIL && $this->session->getLocalUserId() != $item['uid']) {
761                                                 continue;
762                                         }
763
764                                         if (!$this->item->isVisibleActivity($item)) {
765                                                 continue;
766                                         }
767
768                                         /// @todo Check if this call is needed or not
769                                         $arr = ['item' => $item];
770                                         Hook::callAll('display_item', $arr);
771
772                                         $item['pagedrop'] = $page_dropping;
773
774                                         if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
775                                                 $item_object = new PostObject($item);
776                                                 $conv->addParent($item_object);
777                                         }
778                                 }
779
780                                 $threads = $conv->getTemplateData($conv_responses, $formSecurityToken);
781                                 if (!$threads) {
782                                         $this->logger->info('[ERROR] conversation : Failed to get template data.');
783                                         $threads = [];
784                                 }
785                         }
786                 }
787
788                 $o = Renderer::replaceMacros($page_template, [
789                         '$baseurl'     => $this->baseURL,
790                         '$return_path' => $this->args->getQueryString(),
791                         '$live_update' => $live_update_div,
792                         '$remove'      => $this->l10n->t('remove'),
793                         '$mode'        => $mode,
794                         '$update'      => $update,
795                         '$threads'     => $threads,
796                         '$dropping'    => ($page_dropping ? $this->l10n->t('Delete Selected Items') : false),
797                 ]);
798
799                 $this->profiler->stopRecording();
800                 return $o;
801         }
802
803         private function getBlocklist(): array
804         {
805                 if (!$this->session->getLocalUserId()) {
806                         return [];
807                 }
808
809                 $str_blocked = str_replace(["\n", "\r"], ",", $this->pConfig->get($this->session->getLocalUserId(), 'system', 'blocked') ?? '');
810                 if (empty($str_blocked)) {
811                         return [];
812                 }
813
814                 $blocklist = [];
815
816                 foreach (explode(',', $str_blocked) as $entry) {
817                         $cid = Contact::getIdForURL(trim($entry), 0, false);
818                         if (!empty($cid)) {
819                                 $blocklist[] = $cid;
820                         }
821                 }
822
823                 return $blocklist;
824         }
825
826         /**
827          * Adds some information (Causer, post reason, direction) to the fetched post row.
828          *
829          * @param array   $row        Post row
830          * @param array   $activity   Contact data of the resharer
831          * @param array   $thr_parent Thread parent row
832          *
833          * @return array items with parents and comments
834          */
835         private function addRowInformation(array $row, array $activity, array $thr_parent): array
836         {
837                 $this->profiler->startRecording('rendering');
838
839                 if (!$row['writable']) {
840                         $row['writable'] = in_array($row['network'], Protocol::FEDERATED);
841                 }
842
843                 if (!empty($activity)) {
844                         if (($row['gravity'] == ItemModel::GRAVITY_PARENT)) {
845                                 $row['post-reason'] = ItemModel::PR_ANNOUNCEMENT;
846
847                                 $row     = array_merge($row, $activity);
848                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
849
850                                 $row['causer-link']   = $contact['url'];
851                                 $row['causer-avatar'] = $contact['thumb'];
852                                 $row['causer-name']   = $contact['name'];
853                         } elseif (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
854                                 ($row['author-id'] == $activity['causer-id'])) {
855                                 return $row;
856                         }
857                 }
858
859                 switch ($row['post-reason']) {
860                         case ItemModel::PR_TO:
861                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'to')];
862                                 break;
863                         case ItemModel::PR_CC:
864                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'cc')];
865                                 break;
866                         case ItemModel::PR_BTO:
867                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bto')];
868                                 break;
869                         case ItemModel::PR_BCC:
870                                 $row['direction'] = ['direction' => 7, 'title' => $this->l10n->t('You had been addressed (%s).', 'bcc')];
871                                 break;
872                         case ItemModel::PR_FOLLOWER:
873                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('You are following %s.', $row['causer-name'] ?: $row['author-name'])];
874                                 break;
875                         case ItemModel::PR_TAG:
876                                 $row['direction'] = ['direction' => 4, 'title' => $this->l10n->t('You subscribed to one or more tags in this post.')];
877                                 break;
878                         case ItemModel::PR_ANNOUNCEMENT:
879                                 if (!empty($row['causer-id']) && $this->pConfig->get($this->session->getLocalUserId(), 'system', 'display_resharer')) {
880                                         $row['owner-id']     = $row['causer-id'];
881                                         $row['owner-link']   = $row['causer-link'];
882                                         $row['owner-avatar'] = $row['causer-avatar'];
883                                         $row['owner-name']   = $row['causer-name'];
884                                 }
885
886                                 if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT]) && !empty($row['causer-id'])) {
887                                         $causer = ['uid' => 0, 'id' => $row['causer-id'], 'network' => $row['causer-network'], 'url' => $row['causer-link']];
888
889                                         $row['reshared'] = $this->l10n->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
890                                 }
891                                 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Reshared') : $this->l10n->t('Reshared by %s <%s>', $row['causer-name'], $row['causer-link']))];
892                                 break;
893                         case ItemModel::PR_COMMENT:
894                                 $row['direction'] = ['direction' => 5, 'title' => $this->l10n->t('%s is participating in this thread.', $row['author-name'])];
895                                 break;
896                         case ItemModel::PR_STORED:
897                                 $row['direction'] = ['direction' => 8, 'title' => $this->l10n->t('Stored for general reasons')];
898                                 break;
899                         case ItemModel::PR_GLOBAL:
900                                 $row['direction'] = ['direction' => 9, 'title' => $this->l10n->t('Global post')];
901                                 break;
902                         case ItemModel::PR_RELAY:
903                                 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Sent via an relay server') : $this->l10n->t('Sent via the relay server %s <%s>', $row['causer-name'], $row['causer-link']))];
904                                 break;
905                         case ItemModel::PR_FETCHED:
906                                 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? $this->l10n->t('Fetched') : $this->l10n->t('Fetched because of %s <%s>', $row['causer-name'], $row['causer-link']))];
907                                 break;
908                         case ItemModel::PR_COMPLETION:
909                                 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of a child post to complete this thread.')];
910                                 break;
911                         case ItemModel::PR_DIRECT:
912                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Local delivery')];
913                                 break;
914                         case ItemModel::PR_ACTIVITY:
915                                 $row['direction'] = ['direction' => 2, 'title' => $this->l10n->t('Stored because of your activity (like, comment, star, ...)')];
916                                 break;
917                         case ItemModel::PR_DISTRIBUTE:
918                                 $row['direction'] = ['direction' => 6, 'title' => $this->l10n->t('Distributed')];
919                                 break;
920                         case ItemModel::PR_PUSHED:
921                                 $row['direction'] = ['direction' => 1, 'title' => $this->l10n->t('Pushed to us')];
922                                 break;
923                 }
924
925                 $row['thr-parent-row'] = $thr_parent;
926
927                 $this->profiler->stopRecording();
928                 return $row;
929         }
930
931         /**
932          * Add comments to top level entries that had been fetched before
933          *
934          * The system will fetch the comments for the local user whenever possible.
935          * This behaviour is currently needed to allow commenting on Friendica posts.
936          *
937          * @param array  $parents       Parent items
938          * @param bool   $block_authors
939          * @param bool   $order
940          * @param int    $uid
941          * @param string $mode
942          * @return array items with parents and comments
943          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
944          */
945         private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
946         {
947                 $this->profiler->startRecording('rendering');
948                 if (count($parents) > 1) {
949                         $max_comments = $this->config->get('system', 'max_comments', 100);
950                 } else {
951                         $max_comments = $this->config->get('system', 'max_display_comments', 1000);
952                 }
953
954                 $activities      = [];
955                 $uriids          = [];
956                 $commentcounter  = [];
957                 $activitycounter = [];
958
959                 foreach ($parents as $parent) {
960                         if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == ItemModel::GRAVITY_ACTIVITY)) {
961                                 $uriid = $parent['thr-parent-id'];
962                                 if (!empty($parent['author-id'])) {
963                                         $activities[$uriid] = ['causer-id' => $parent['author-id']];
964                                         foreach (['commented', 'received', 'created'] as $orderfields) {
965                                                 if (!empty($parent[$orderfields])) {
966                                                         $activities[$uriid][$orderfields] = $parent[$orderfields];
967                                                 }
968                                         }
969                                 }
970                         } else {
971                                 $uriid = $parent['uri-id'];
972                         }
973                         $uriids[] = $uriid;
974
975                         $commentcounter[$uriid]  = 0;
976                         $activitycounter[$uriid] = 0;
977                 }
978
979                 $condition = ['parent-uri-id' => $uriids];
980                 if ($block_authors) {
981                         $condition['author-hidden'] = false;
982                 }
983
984                 if ($this->config->get('system', 'emoji_activities')) {
985                         $emojis = $this->getEmojis($uriids);
986                         $condition = DBA::mergeConditions($condition, ["(`gravity` != ? OR `origin`)", ItemModel::GRAVITY_ACTIVITY]);
987                 }
988
989                 $condition = DBA::mergeConditions($condition,
990                         ["`uid` IN (0, ?) AND (NOT `vid` IN (?, ?, ?) OR `vid` IS NULL)", $uid, Verb::getID(Activity::FOLLOW), Verb::getID(Activity::VIEW), Verb::getID(Activity::READ)]);
991
992                 $condition = DBA::mergeConditions($condition,
993                         ["`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked`
994                         AND ((NOT `contact-pending` AND (`contact-rel` IN (?, ?))) OR `self` OR `contact-uid` = ?)",
995                         Contact::SHARING, Contact::FRIEND, 0]);
996
997                 $thread_parents = Post::select(['uri-id', 'causer-id'], $condition, ['order' => ['uri-id' => false, 'uid']]);
998
999                 $thr_parent = [];
1000
1001                 while ($row = Post::fetch($thread_parents)) {
1002                         $thr_parent[$row['uri-id']] = $row;
1003                 }
1004                 DBA::close($thread_parents);
1005
1006                 $params = ['order' => ['uri-id' => true, 'uid' => true]];
1007
1008                 $thread_items = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
1009
1010                 $items         = [];
1011                 $quote_uri_ids = [];
1012                 $authors       = [];
1013
1014                 while ($row = Post::fetch($thread_items)) {
1015                         if (!empty($items[$row['uri-id']]) && ($row['uid'] == 0)) {
1016                                 continue;
1017                         }
1018
1019                         if (($mode != self::MODE_CONTACTS) && !$row['origin']) {
1020                                 $row['featured'] = false;
1021                         }
1022
1023                         if ($max_comments > 0) {
1024                                 if (($row['gravity'] == ItemModel::GRAVITY_COMMENT) && (++$commentcounter[$row['parent-uri-id']] > $max_comments)) {
1025                                         continue;
1026                                 }
1027                                 if (($row['gravity'] == ItemModel::GRAVITY_ACTIVITY) && (++$activitycounter[$row['parent-uri-id']] > $max_comments)) {
1028                                         continue;
1029                                 }
1030                         }
1031
1032                         $authors[] = $row['author-id'];
1033                         $authors[] = $row['owner-id'];
1034
1035                         if (in_array($row['gravity'], [ItemModel::GRAVITY_PARENT, ItemModel::GRAVITY_COMMENT])) {
1036                                 $quote_uri_ids[$row['uri-id']] = [
1037                                         'uri-id'        => $row['uri-id'],
1038                                         'uri'           => $row['uri'],
1039                                         'parent-uri-id' => $row['parent-uri-id'],
1040                                         'parent-uri'    => $row['parent-uri'],
1041                                 ];
1042                         }
1043
1044                         $items[$row['uri-id']] = $this->addRowInformation($row, $activities[$row['uri-id']] ?? [], $thr_parent[$row['thr-parent-id']] ?? []);
1045                 }
1046
1047                 DBA::close($thread_items);
1048
1049                 $quotes = Post::select(array_merge(ItemModel::DISPLAY_FIELDLIST, ['featured', 'contact-uid', 'gravity', 'post-type', 'post-reason']), ['quote-uri-id' => array_column($quote_uri_ids, 'uri-id'), 'body' => '', 'uid' => 0]);
1050                 while ($quote = Post::fetch($quotes)) {
1051                         $row = $quote;
1052
1053                         $row['uid']           = $uid;
1054                         $row['verb']          = $row['body'] = $row['raw-body'] = Activity::ANNOUNCE;
1055                         $row['gravity']       = ItemModel::GRAVITY_ACTIVITY;
1056                         $row['object-type']   = Activity\ObjectType::NOTE;
1057                         $row['parent-uri']    = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri'];
1058                         $row['parent-uri-id'] = $quote_uri_ids[$quote['quote-uri-id']]['parent-uri-id'];
1059                         $row['thr-parent']    = $quote_uri_ids[$quote['quote-uri-id']]['uri'];
1060                         $row['thr-parent-id'] = $quote_uri_ids[$quote['quote-uri-id']]['uri-id'];
1061
1062                         $authors[] = $row['author-id'];
1063                         $authors[] = $row['owner-id'];
1064
1065                         $items[$row['uri-id']] = $this->addRowInformation($row, [], []);
1066                 }
1067                 DBA::close($quotes);
1068
1069                 $authors = array_unique($authors);
1070
1071                 $blocks    = [];
1072                 $ignores   = [];
1073                 $collapses = [];
1074                 if (!empty($authors)) {
1075                         $usercontacts = DBA::select('user-contact', ['cid', 'blocked', 'ignored', 'collapsed'], ['uid' => $uid, 'cid' => $authors]);
1076                         while ($usercontact = DBA::fetch($usercontacts)) {
1077                                 if ($usercontact['blocked']) {
1078                                         $blocks[] = $usercontact['cid'];
1079                                 }
1080                                 if ($usercontact['ignored']) {
1081                                         $ignores[] = $usercontact['cid'];
1082                                 }
1083                                 if ($usercontact['collapsed']) {
1084                                         $collapses[] = $usercontact['cid'];
1085                                 }
1086                         }
1087                         DBA::close($usercontacts);
1088                 }
1089
1090                 foreach ($items as $key => $row) {
1091                         $items[$key]['emojis'] = $emojis[$key] ?? [];
1092
1093                         $always_display = in_array($mode, [self::MODE_CONTACTS, self::MODE_CONTACT_POSTS]);
1094
1095                         $items[$key]['user-blocked-author']   = !$always_display && in_array($row['author-id'], $blocks);
1096                         $items[$key]['user-ignored-author']   = !$always_display && in_array($row['author-id'], $ignores);
1097                         $items[$key]['user-blocked-owner']    = !$always_display && in_array($row['owner-id'], $blocks);
1098                         $items[$key]['user-ignored-owner']    = !$always_display && in_array($row['owner-id'], $ignores);
1099                         $items[$key]['user-collapsed-author'] = !$always_display && in_array($row['author-id'], $collapses);
1100                         $items[$key]['user-collapsed-owner']  = !$always_display && in_array($row['owner-id'], $collapses);
1101
1102                         if (in_array($mode, [self::MODE_COMMUNITY, self::MODE_NETWORK]) &&
1103                                 (in_array($row['author-id'], $blocks) || in_array($row['owner-id'], $blocks) || in_array($row['author-id'], $ignores) || in_array($row['owner-id'], $ignores))) {
1104                                 unset($items[$key]);
1105                         }
1106                 }
1107
1108                 $items = $this->convSort($items, $order);
1109
1110                 $this->profiler->stopRecording();
1111                 return $items;
1112         }
1113
1114         /**
1115          * Fetch emoji reaction from the conversation
1116          *
1117          * @param array $uriids
1118          * @return array
1119          */
1120         private function getEmojis(array $uriids): array
1121         {
1122                 $activity_emoji = [
1123                         Activity::LIKE        => '👍',
1124                         Activity::DISLIKE     => '👎',
1125                         Activity::ATTEND      => '✔️',
1126                         Activity::ATTENDMAYBE => '❓',
1127                         Activity::ATTENDNO    => '❌',
1128                         Activity::ANNOUNCE    => '♻',
1129                         Activity::VIEW        => '📺',
1130                 ];
1131
1132                 $index_list = array_values($activity_emoji);
1133                 $verbs      = array_merge(array_keys($activity_emoji), [Activity::EMOJIREACT]);
1134
1135                 $condition = DBA::mergeConditions(['parent-uri-id' => $uriids, 'gravity' => ItemModel::GRAVITY_ACTIVITY, 'verb' => $verbs], ["NOT `deleted`"]);
1136                 $separator = chr(255) . chr(255) . chr(255);
1137
1138                 $sql = "SELECT `thr-parent-id`, `body`, `verb`, COUNT(*) AS `total`, GROUP_CONCAT(REPLACE(`author-name`, '" . $separator . "', ' ') SEPARATOR '". $separator ."' LIMIT 50) AS `title` FROM `post-view` WHERE " . array_shift($condition) . " GROUP BY `thr-parent-id`, `verb`, `body`";
1139
1140                 $emojis = [];
1141
1142                 $rows = DBA::p($sql, $condition);
1143                 while ($row = DBA::fetch($rows)) {
1144                         $row['verb'] = $row['body'] ? Activity::EMOJIREACT : $row['verb'];
1145                         $emoji       = $row['body'] ?: $activity_emoji[$row['verb']];
1146                         if (!isset($index_list[$emoji])) {
1147                                 $index_list[] = $emoji;
1148                         }
1149                         $index = array_search($emoji, $index_list);
1150
1151                         $emojis[$row['thr-parent-id']][$index]['emoji'] = $emoji;
1152                         $emojis[$row['thr-parent-id']][$index]['verb']  = $row['verb'];
1153                         $emojis[$row['thr-parent-id']][$index]['total'] = ($emojis[$row['thr-parent-id']][$index]['total'] ?? 0) + $row['total'];
1154                         $emojis[$row['thr-parent-id']][$index]['title'] = array_unique(array_merge($emojis[$row['thr-parent-id']][$index]['title'] ?? [], explode($separator, $row['title'])));
1155                 }
1156                 DBA::close($rows);
1157
1158                 return $emojis;
1159         }
1160
1161         /**
1162          * Plucks the children of the given parent from a given item list.
1163          *
1164          * @param array $item_list
1165          * @param array $parent
1166          * @param bool  $recursive
1167          * @return array
1168          */
1169         private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
1170         {
1171                 $this->profiler->startRecording('rendering');
1172                 $children = [];
1173                 foreach ($item_list as $i => $item) {
1174                         if ($item['gravity'] != ItemModel::GRAVITY_PARENT) {
1175                                 if ($recursive) {
1176                                         // Fallback to parent-uri if thr-parent is not set
1177                                         $thr_parent = $item['thr-parent-id'];
1178                                         if ($thr_parent == '') {
1179                                                 $thr_parent = $item['parent-uri-id'];
1180                                         }
1181
1182                                         if ($thr_parent == $parent['uri-id']) {
1183                                                 $item['children'] = $this->getItemChildren($item_list, $item);
1184
1185                                                 $children[] = $item;
1186                                                 unset($item_list[$i]);
1187                                         }
1188                                 } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1189                                         $children[] = $item;
1190                                         unset($item_list[$i]);
1191                                 }
1192                         }
1193                 }
1194                 $this->profiler->stopRecording();
1195                 return $children;
1196         }
1197
1198         /**
1199          * Recursively sorts a tree-like item array
1200          *
1201          * @param array $items
1202          * @return array
1203          */
1204         private function sortItemChildren(array $items): array
1205         {
1206                 $this->profiler->startRecording('rendering');
1207                 $result = $items;
1208                 usort($result, [$this, 'sortThrReceivedRev']);
1209                 foreach ($result as $k => $i) {
1210                         if (isset($result[$k]['children'])) {
1211                                 $result[$k]['children'] = $this->sortItemChildren($result[$k]['children']);
1212                         }
1213                 }
1214                 $this->profiler->stopRecording();
1215                 return $result;
1216         }
1217
1218         /**
1219          * Recursively add all children items at the top level of a list
1220          *
1221          * @param array $children List of items to append
1222          * @param array $item_list
1223          */
1224         private function addChildrenToList(array $children, array &$item_list)
1225         {
1226                 foreach ($children as $child) {
1227                         $item_list[] = $child;
1228                         if (isset($child['children'])) {
1229                                 $this->addChildrenToList($child['children'], $item_list);
1230                         }
1231                 }
1232         }
1233
1234         /**
1235          * Selectively flattens a tree-like item structure to prevent threading stairs
1236          *
1237          * This recursive function takes the item tree structure created by conv_sort() and
1238          * flatten the extraneous depth levels when people reply sequentially, removing the
1239          * stairs effect in threaded conversations limiting the available content width.
1240          *
1241          * The basic principle is the following: if a post item has only one reply and is
1242          * the last reply of its parent, then the reply is moved to the parent.
1243          *
1244          * This process is rendered somewhat more complicated because items can be either
1245          * replies or likes, and these don't factor at all in the reply count/last reply.
1246          *
1247          * @param array $parent A tree-like array of items
1248          * @return array
1249          */
1250         private function smartFlattenConversation(array $parent): array
1251         {
1252                 $this->profiler->startRecording('rendering');
1253                 if (!isset($parent['children']) || count($parent['children']) == 0) {
1254                         $this->profiler->stopRecording();
1255                         return $parent;
1256                 }
1257
1258                 // We use a for loop to ensure we process the newly-moved items
1259                 for ($i = 0; $i < count($parent['children']); $i++) {
1260                         $child = $parent['children'][$i];
1261
1262                         if (isset($child['children']) && count($child['children'])) {
1263                                 // This helps counting only the regular posts
1264                                 $count_post_closure = function ($var) {
1265                                         $this->profiler->stopRecording();
1266                                         return $var['verb'] === Activity::POST;
1267                                 };
1268
1269                                 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1270
1271                                 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1272
1273                                 // If there's only one child's children post and this is the last child post
1274                                 if ($child_post_count == 1 && $remaining_post_count == 1) {
1275
1276                                         // Searches the post item in the children
1277                                         $j = 0;
1278                                         while ($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1279                                                 $j ++;
1280                                         }
1281
1282                                         $moved_item = $child['children'][$j];
1283                                         unset($parent['children'][$i]['children'][$j]);
1284                                         $parent['children'][] = $moved_item;
1285                                 } else {
1286                                         $parent['children'][$i] = $this->smartFlattenConversation($child);
1287                                 }
1288                         }
1289                 }
1290
1291                 $this->profiler->stopRecording();
1292                 return $parent;
1293         }
1294
1295         /**
1296          * Expands a flat list of items into corresponding tree-like conversation structures.
1297          *
1298          * sort the top-level posts either on "received" or "commented", and finally
1299          * append all the items at the top level (???)
1300          *
1301          * @param array  $item_list A list of items belonging to one or more conversations
1302          * @param string $order     Either on "received" or "commented"
1303          * @return array
1304          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1305          */
1306         private function convSort(array $item_list, string $order): array
1307         {
1308                 $this->profiler->startRecording('rendering');
1309                 $parents = [];
1310
1311                 if (!(is_array($item_list) && count($item_list))) {
1312                         $this->profiler->stopRecording();
1313                         return $parents;
1314                 }
1315
1316                 $blocklist = $this->getBlocklist();
1317
1318                 $item_array = [];
1319
1320                 // Dedupes the item list on the uri to prevent infinite loops
1321                 foreach ($item_list as $item) {
1322                         if (in_array($item['author-id'], $blocklist)) {
1323                                 continue;
1324                         }
1325
1326                         $item_array[$item['uri-id']] = $item;
1327                 }
1328
1329                 // Extract the top level items
1330                 foreach ($item_array as $item) {
1331                         if ($item['gravity'] == ItemModel::GRAVITY_PARENT) {
1332                                 $parents[] = $item;
1333                         }
1334                 }
1335
1336                 if (stristr($order, 'pinned_received')) {
1337                         usort($parents, [$this, 'sortThrFeaturedReceived']);
1338                 } elseif (stristr($order, 'pinned_commented')) {
1339                         usort($parents, [$this, 'sortThrFeaturedCommented']);
1340                 } elseif (stristr($order, 'received')) {
1341                         usort($parents, [$this, 'sortThrReceived']);
1342                 } elseif (stristr($order, 'commented')) {
1343                         usort($parents, [$this, 'sortThrCommented']);
1344                 } elseif (stristr($order, 'created')) {
1345                         usort($parents, [$this, 'sortThrCreated']);
1346                 }
1347
1348                 /*
1349                 * Plucks children from the item_array, second pass collects eventual orphan
1350                 * items and add them as children of their top-level post.
1351                 */
1352                 foreach ($parents as $i => $parent) {
1353                         $parents[$i]['children'] = array_merge($this->getItemChildren($item_array, $parent, true),
1354                                 $this->getItemChildren($item_array, $parent, false));
1355                 }
1356
1357                 foreach ($parents as $i => $parent) {
1358                         $parents[$i]['children'] = $this->sortItemChildren($parents[$i]['children']);
1359                 }
1360
1361                 if (!$this->pConfig->get($this->session->getLocalUserId(), 'system', 'no_smart_threading', 0)) {
1362                         foreach ($parents as $i => $parent) {
1363                                 $parents[$i] = $this->smartFlattenConversation($parent);
1364                         }
1365                 }
1366
1367                 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1368                 /// However, this apparently ensures responses (likes, attendance) display (?!)
1369                 foreach ($parents as $parent) {
1370                         if (count($parent['children'])) {
1371                                 $this->addChildrenToList($parent['children'], $parents);
1372                         }
1373                 }
1374
1375                 $this->profiler->stopRecording();
1376                 return $parents;
1377         }
1378
1379         /**
1380          * usort() callback to sort item arrays by featured and the received key
1381          *
1382          * @param array $a
1383          * @param array $b
1384          * @return int
1385          */
1386         private function sortThrFeaturedReceived(array $a, array $b): int
1387         {
1388                 if ($b['featured'] && !$a['featured']) {
1389                         return 1;
1390                 } elseif (!$b['featured'] && $a['featured']) {
1391                         return -1;
1392                 }
1393
1394                 return strcmp($b['received'], $a['received']);
1395         }
1396
1397         /**
1398          * usort() callback to sort item arrays by featured and the received key
1399          *
1400          * @param array $a
1401          * @param array $b
1402          * @return int
1403          */
1404         private function sortThrFeaturedCommented(array $a, array $b): int
1405         {
1406                 if ($b['featured'] && !$a['featured']) {
1407                         return 1;
1408                 } elseif (!$b['featured'] && $a['featured']) {
1409                         return -1;
1410                 }
1411
1412                 return strcmp($b['commented'], $a['commented']);
1413         }
1414
1415         /**
1416          * usort() callback to sort item arrays by the received key
1417          *
1418          * @param array $a
1419          * @param array $b
1420          * @return int
1421          */
1422         private function sortThrReceived(array $a, array $b): int
1423         {
1424                 return strcmp($b['received'], $a['received']);
1425         }
1426
1427         /**
1428          * usort() callback to reverse sort item arrays by the received key
1429          *
1430          * @param array $a
1431          * @param array $b
1432          * @return int
1433          */
1434         private function sortThrReceivedRev(array $a, array $b): int
1435         {
1436                 return strcmp($a['received'], $b['received']);
1437         }
1438
1439         /**
1440          * usort() callback to sort item arrays by the commented key
1441          *
1442          * @param array $a
1443          * @param array $b
1444          * @return int
1445          */
1446         private function sortThrCommented(array $a, array $b): int
1447         {
1448                 return strcmp($b['commented'], $a['commented']);
1449         }
1450
1451         /**
1452          * usort() callback to sort item arrays by the created key
1453          *
1454          * @param array $a
1455          * @param array $b
1456          * @return int
1457          */
1458         private function sortThrCreated(array $a, array $b): int
1459         {
1460                 return strcmp($b['created'], $a['created']);
1461         }
1462 }