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