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