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