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