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