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