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