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