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