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