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