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