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