]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Add cache for PHP 7.3 test
[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\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 {
893         $sub_link = '';
894         $poke_link = '';
895         $contact_url = '';
896         $pm_url = '';
897         $status_link = '';
898         $photos_link = '';
899         $posts_link = '';
900         $block_link = '';
901         $ignore_link = '';
902
903         if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
904                 $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
905         }
906
907         $author = ['uid' => 0, 'id' => $item['author-id'],
908                 'network' => $item['author-network'], 'url' => $item['author-link']];
909         $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
910         $sparkle = (strpos($profile_link, 'redir/') === 0);
911
912         $cid = 0;
913         $pcid = $item['author-id'];
914         $network = '';
915         $rel = 0;
916         $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
917         $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
918         if (DBA::isResult($contact)) {
919                 $cid = $contact['id'];
920                 $network = $contact['network'];
921                 $rel = $contact['rel'];
922         }
923
924         if ($sparkle) {
925                 $status_link = $profile_link . '/status';
926                 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
927                 $profile_link = $profile_link . '/profile';
928         }
929
930         if (!empty($pcid)) {
931                 $contact_url = 'contact/' . $pcid;
932                 $posts_link  = $contact_url . '/posts';
933                 $block_link  = $item['self'] ? '' : $contact_url . '/block';
934                 $ignore_link = $item['self'] ? '' : $contact_url . '/ignore';
935         }
936
937         if ($cid && !$item['self']) {
938                 $contact_url = 'contact/' . $cid;
939                 $poke_link   = $contact_url . '/poke';
940                 $posts_link  = $contact_url . '/posts';
941
942                 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
943                         $pm_url = 'message/new/' . $cid;
944                 }
945         }
946
947         if (local_user()) {
948                 $menu = [
949                         DI::l10n()->t('Follow Thread') => $sub_link,
950                         DI::l10n()->t('View Status') => $status_link,
951                         DI::l10n()->t('View Profile') => $profile_link,
952                         DI::l10n()->t('View Photos') => $photos_link,
953                         DI::l10n()->t('Network Posts') => $posts_link,
954                         DI::l10n()->t('View Contact') => $contact_url,
955                         DI::l10n()->t('Send PM') => $pm_url,
956                         DI::l10n()->t('Block') => $block_link,
957                         DI::l10n()->t('Ignore') => $ignore_link
958                 ];
959
960                 if (!empty($item['language'])) {
961                         $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
962                 }
963
964                 if ($network == Protocol::DFRN) {
965                         $menu[DI::l10n()->t("Poke")] = $poke_link;
966                 }
967
968                 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
969                         in_array($item['network'], Protocol::FEDERATED)) {
970                         $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
971                 }
972         } else {
973                 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
974         }
975
976         $args = ['item' => $item, 'menu' => $menu];
977
978         Hook::callAll('item_photo_menu', $args);
979
980         $menu = $args['menu'];
981
982         $o = '';
983         foreach ($menu as $k => $v) {
984                 if (strpos($v, 'javascript:') === 0) {
985                         $v = substr($v, 11);
986                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
987                 } elseif ($v) {
988                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
989                 }
990         }
991         return $o;
992 }
993
994 /**
995  * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
996  *
997  * Increments the count of each matching activity and adds a link to the author as needed.
998  *
999  * @param array  $activity
1000  * @param array &$conv_responses (already created with builtin activity structure)
1001  * @return void
1002  * @throws ImagickException
1003  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1004  */
1005 function builtin_activity_puller(array $activity, array &$conv_responses)
1006 {
1007         foreach ($conv_responses as $mode => $v) {
1008                 $sparkle = '';
1009
1010                 switch ($mode) {
1011                         case 'like':
1012                                 $verb = Activity::LIKE;
1013                                 break;
1014                         case 'dislike':
1015                                 $verb = Activity::DISLIKE;
1016                                 break;
1017                         case 'attendyes':
1018                                 $verb = Activity::ATTEND;
1019                                 break;
1020                         case 'attendno':
1021                                 $verb = Activity::ATTENDNO;
1022                                 break;
1023                         case 'attendmaybe':
1024                                 $verb = Activity::ATTENDMAYBE;
1025                                 break;
1026                         case 'announce':
1027                                 $verb = Activity::ANNOUNCE;
1028                                 break;
1029                         default:
1030                                 return;
1031                 }
1032
1033                 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
1034                         $author = [
1035                                 'uid' => 0,
1036                                 'id' => $activity['author-id'],
1037                                 'network' => $activity['author-network'],
1038                                 'url' => $activity['author-link']
1039                         ];
1040                         $url = Contact::magicLinkByContact($author);
1041                         if (strpos($url, 'redir/') === 0) {
1042                                 $sparkle = ' class="sparkle" ';
1043                         }
1044
1045                         $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
1046
1047                         if (empty($activity['thr-parent-id'])) {
1048                                 $activity['thr-parent-id'] = $activity['parent-uri-id'];
1049                         }
1050
1051                         // Skip when the causer of the parent is the same than the author of the announce
1052                         if (($verb == Activity::ANNOUNCE) && Post::exists(['uri-id' => $activity['thr-parent-id'],
1053                                 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
1054                                 continue;
1055                         }
1056
1057                         if (!isset($conv_responses[$mode][$activity['thr-parent-id']])) {
1058                                 $conv_responses[$mode][$activity['thr-parent-id']] = [
1059                                         'links' => [],
1060                                         'self' => 0,
1061                                 ];
1062                         } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent-id']]['links'])) {
1063                                 // only list each unique author once
1064                                 continue;
1065                         }
1066
1067                         if (public_contact() == $activity['author-id']) {
1068                                 $conv_responses[$mode][$activity['thr-parent-id']]['self'] = 1;
1069                         }
1070
1071                         $conv_responses[$mode][$activity['thr-parent-id']]['links'][] = $link;
1072
1073                         // there can only be one activity verb per item so if we found anything, we can stop looking
1074                         return;
1075                 }
1076         }
1077 }
1078
1079 /**
1080  * Format the activity text for an item/photo/video
1081  *
1082  * @param array  $links = array of pre-linked names of actors
1083  * @param string $verb  = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1084  * @param int    $id    = item id
1085  * @return string formatted text
1086  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087  */
1088 function format_activity(array $links, $verb, $id) {
1089         $o = '';
1090         $expanded = '';
1091         $phrase = '';
1092
1093         $total = count($links);
1094         if ($total == 1) {
1095                 $likers = $links[0];
1096
1097                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1098                 // list which show all likers
1099                 switch ($verb) {
1100                         case 'like' :
1101                                 $phrase = DI::l10n()->t('%s likes this.', $likers);
1102                                 break;
1103                         case 'dislike' :
1104                                 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1105                                 break;
1106                         case 'attendyes' :
1107                                 $phrase = DI::l10n()->t('%s attends.', $likers);
1108                                 break;
1109                         case 'attendno' :
1110                                 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1111                                 break;
1112                         case 'attendmaybe' :
1113                                 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1114                                 break;
1115                         case 'announce' :
1116                                 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1117                                 break;
1118                 }
1119         } elseif ($total > 1) {
1120                 if ($total < MAX_LIKERS) {
1121                         $likers = implode(', ', array_slice($links, 0, -1));
1122                         $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1123                 } else  {
1124                         $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1125                         $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1126                 }
1127
1128                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1129
1130                 $explikers = '';
1131                 switch ($verb) {
1132                         case 'like':
1133                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> like this', $spanatts, $total);
1134                                 $explikers = DI::l10n()->t('%s like this.', $likers);
1135                                 break;
1136                         case 'dislike':
1137                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1138                                 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1139                                 break;
1140                         case 'attendyes':
1141                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend', $spanatts, $total);
1142                                 $explikers = DI::l10n()->t('%s attend.', $likers);
1143                                 break;
1144                         case 'attendno':
1145                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1146                                 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1147                                 break;
1148                         case 'attendmaybe':
1149                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1150                                 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1151                                 break;
1152                         case 'announce':
1153                                 $phrase = DI::l10n()->t('<span  %1$s>%2$d people</span> reshared this', $spanatts, $total);
1154                                 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1155                                 break;
1156                 }
1157
1158                 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1159         }
1160
1161         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1162                 '$phrase' => $phrase,
1163                 '$type' => $verb,
1164                 '$id' => $id
1165         ]);
1166         $o .= $expanded;
1167
1168         return $o;
1169 }
1170
1171 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1172 {
1173         $o = '';
1174
1175         $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1176
1177         $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1178         DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1179                 '$newpost'   => 'true',
1180                 '$baseurl'   => DI::baseUrl()->get(true),
1181                 '$geotag'    => $geotag,
1182                 '$nickname'  => $x['nickname'],
1183                 '$ispublic'  => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1184                 '$linkurl'   => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1185                 '$term'      => DI::l10n()->t('Tag term:'),
1186                 '$fileas'    => DI::l10n()->t('Save to Folder:'),
1187                 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1188                 '$delitems'  => DI::l10n()->t("Delete item\x28s\x29?"),
1189                 '$is_mobile' => DI::mode()->isMobile(),
1190         ]);
1191
1192         $jotplugins = '';
1193         Hook::callAll('jot_tool', $jotplugins);
1194
1195         $tpl = Renderer::getMarkupTemplate("jot.tpl");
1196
1197         $o .= Renderer::replaceMacros($tpl, [
1198                 '$new_post' => DI::l10n()->t('New Post'),
1199                 '$return_path'  => DI::args()->getQueryString(),
1200                 '$action'       => 'item',
1201                 '$share'        => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1202                 '$loading'      => DI::l10n()->t('Loading...'),
1203                 '$upload'       => DI::l10n()->t('Upload photo'),
1204                 '$shortupload'  => DI::l10n()->t('upload photo'),
1205                 '$attach'       => DI::l10n()->t('Attach file'),
1206                 '$shortattach'  => DI::l10n()->t('attach file'),
1207                 '$edbold'       => DI::l10n()->t('Bold'),
1208                 '$editalic'     => DI::l10n()->t('Italic'),
1209                 '$eduline'      => DI::l10n()->t('Underline'),
1210                 '$edquote'      => DI::l10n()->t('Quote'),
1211                 '$edcode'       => DI::l10n()->t('Code'),
1212                 '$edimg'        => DI::l10n()->t('Image'),
1213                 '$edurl'        => DI::l10n()->t('Link'),
1214                 '$edattach'     => DI::l10n()->t('Link or Media'),
1215                 '$edvideo'      => DI::l10n()->t('Video'),
1216                 '$setloc'       => DI::l10n()->t('Set your location'),
1217                 '$shortsetloc'  => DI::l10n()->t('set location'),
1218                 '$noloc'        => DI::l10n()->t('Clear browser location'),
1219                 '$shortnoloc'   => DI::l10n()->t('clear location'),
1220                 '$title'        => $x['title'] ?? '',
1221                 '$placeholdertitle' => DI::l10n()->t('Set title'),
1222                 '$category'     => $x['category'] ?? '',
1223                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1224                 '$wait'         => DI::l10n()->t('Please wait'),
1225                 '$permset'      => DI::l10n()->t('Permission settings'),
1226                 '$shortpermset' => DI::l10n()->t('Permissions'),
1227                 '$wall'         => $notes_cid ? 0 : 1,
1228                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1229                 '$content'      => $x['content'] ?? '',
1230                 '$post_id'      => $x['post_id'] ?? '',
1231                 '$baseurl'      => DI::baseUrl()->get(true),
1232                 '$defloc'       => $x['default_location'],
1233                 '$visitor'      => $x['visitor'],
1234                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1235                 '$public'       => DI::l10n()->t('Public post'),
1236                 '$lockstate'    => $x['lockstate'],
1237                 '$bang'         => $x['bang'],
1238                 '$profile_uid'  => $x['profile_uid'],
1239                 '$preview'      => DI::l10n()->t('Preview'),
1240                 '$jotplugins'   => $jotplugins,
1241                 '$notes_cid'    => $notes_cid,
1242                 '$sourceapp'    => DI::l10n()->t($a->sourcename),
1243                 '$cancel'       => DI::l10n()->t('Cancel'),
1244                 '$rand_num'     => Crypto::randomDigits(12),
1245
1246                 // ACL permissions box
1247                 '$acl'           => $x['acl'],
1248
1249                 //jot nav tab (used in some themes)
1250                 '$message' => DI::l10n()->t('Message'),
1251                 '$browser' => DI::l10n()->t('Browser'),
1252
1253                 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1254         ]);
1255
1256
1257         if ($popup == true) {
1258                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1259         }
1260
1261         return $o;
1262 }
1263
1264 /**
1265  * Plucks the children of the given parent from a given item list.
1266  *
1267  * @param array $item_list
1268  * @param array $parent
1269  * @param bool  $recursive
1270  * @return array
1271  */
1272 function get_item_children(array &$item_list, array $parent, $recursive = true)
1273 {
1274         $children = [];
1275         foreach ($item_list as $i => $item) {
1276                 if ($item['gravity'] != GRAVITY_PARENT) {
1277                         if ($recursive) {
1278                                 // Fallback to parent-uri if thr-parent is not set
1279                                 $thr_parent = $item['thr-parent-id'];
1280                                 if ($thr_parent == '') {
1281                                         $thr_parent = $item['parent-uri-id'];
1282                                 }
1283
1284                                 if ($thr_parent == $parent['uri-id']) {
1285                                         $item['children'] = get_item_children($item_list, $item);
1286                                         $children[] = $item;
1287                                         unset($item_list[$i]);
1288                                 }
1289                         } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1290                                 $children[] = $item;
1291                                 unset($item_list[$i]);
1292                         }
1293                 }
1294         }
1295         return $children;
1296 }
1297
1298 /**
1299  * Recursively sorts a tree-like item array
1300  *
1301  * @param array $items
1302  * @return array
1303  */
1304 function sort_item_children(array $items)
1305 {
1306         $result = $items;
1307         usort($result, 'sort_thr_received_rev');
1308         foreach ($result as $k => $i) {
1309                 if (isset($result[$k]['children'])) {
1310                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1311                 }
1312         }
1313         return $result;
1314 }
1315
1316 /**
1317  * Recursively add all children items at the top level of a list
1318  *
1319  * @param array $children List of items to append
1320  * @param array $item_list
1321  */
1322 function add_children_to_list(array $children, array &$item_list)
1323 {
1324         foreach ($children as $child) {
1325                 $item_list[] = $child;
1326                 if (isset($child['children'])) {
1327                         add_children_to_list($child['children'], $item_list);
1328                 }
1329         }
1330 }
1331
1332 /**
1333  * Selectively flattens a tree-like item structure to prevent threading stairs
1334  *
1335  * This recursive function takes the item tree structure created by conv_sort() and
1336  * flatten the extraneous depth levels when people reply sequentially, removing the
1337  * stairs effect in threaded conversations limiting the available content width.
1338  *
1339  * The basic principle is the following: if a post item has only one reply and is
1340  * the last reply of its parent, then the reply is moved to the parent.
1341  *
1342  * This process is rendered somewhat more complicated because items can be either
1343  * replies or likes, and these don't factor at all in the reply count/last reply.
1344  *
1345  * @param array $parent A tree-like array of items
1346  * @return array
1347  */
1348 function smart_flatten_conversation(array $parent)
1349 {
1350         if (!isset($parent['children']) || count($parent['children']) == 0) {
1351                 return $parent;
1352         }
1353
1354         // We use a for loop to ensure we process the newly-moved items
1355         for ($i = 0; $i < count($parent['children']); $i++) {
1356                 $child = $parent['children'][$i];
1357
1358                 if (isset($child['children']) && count($child['children'])) {
1359                         // This helps counting only the regular posts
1360                         $count_post_closure = function($var) {
1361                                 return $var['verb'] === Activity::POST;
1362                         };
1363
1364                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1365
1366                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1367
1368                         // If there's only one child's children post and this is the last child post
1369                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1370
1371                                 // Searches the post item in the children
1372                                 $j = 0;
1373                                 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1374                                         $j ++;
1375                                 }
1376
1377                                 $moved_item = $child['children'][$j];
1378                                 unset($parent['children'][$i]['children'][$j]);
1379                                 $parent['children'][] = $moved_item;
1380                         } else {
1381                                 $parent['children'][$i] = smart_flatten_conversation($child);
1382                         }
1383                 }
1384         }
1385
1386         return $parent;
1387 }
1388
1389
1390 /**
1391  * Expands a flat list of items into corresponding tree-like conversation structures.
1392  *
1393  * sort the top-level posts either on "received" or "commented", and finally
1394  * append all the items at the top level (???)
1395  *
1396  * @param array  $item_list A list of items belonging to one or more conversations
1397  * @param string $order     Either on "received" or "commented"
1398  * @return array
1399  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1400  */
1401 function conv_sort(array $item_list, $order)
1402 {
1403         $parents = [];
1404
1405         if (!(is_array($item_list) && count($item_list))) {
1406                 return $parents;
1407         }
1408
1409         $blocklist = conv_get_blocklist();
1410
1411         $item_array = [];
1412
1413         // Dedupes the item list on the uri to prevent infinite loops
1414         foreach ($item_list as $item) {
1415                 if (in_array($item['author-id'], $blocklist)) {
1416                         continue;
1417                 }
1418
1419                 $item_array[$item['uri-id']] = $item;
1420         }
1421
1422         // Extract the top level items
1423         foreach ($item_array as $item) {
1424                 if ($item['gravity'] == GRAVITY_PARENT) {
1425                         $parents[] = $item;
1426                 }
1427         }
1428
1429         if (stristr($order, 'pinned_received')) {
1430                 usort($parents, 'sort_thr_pinned_received');
1431         } elseif (stristr($order, 'received')) {
1432                 usort($parents, 'sort_thr_received');
1433         } elseif (stristr($order, 'commented')) {
1434                 usort($parents, 'sort_thr_commented');
1435         }
1436
1437         /*
1438          * Plucks children from the item_array, second pass collects eventual orphan
1439          * items and add them as children of their top-level post.
1440          */
1441         foreach ($parents as $i => $parent) {
1442                 $parents[$i]['children'] =
1443                         array_merge(get_item_children($item_array, $parent, true),
1444                                 get_item_children($item_array, $parent, false));
1445         }
1446
1447         foreach ($parents as $i => $parent) {
1448                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1449         }
1450
1451         if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1452                 foreach ($parents as $i => $parent) {
1453                         $parents[$i] = smart_flatten_conversation($parent);
1454                 }
1455         }
1456
1457         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1458         /// However, this apparently ensures responses (likes, attendance) display (?!)
1459         foreach ($parents as $parent) {
1460                 if (count($parent['children'])) {
1461                         add_children_to_list($parent['children'], $parents);
1462                 }
1463         }
1464
1465         return $parents;
1466 }
1467
1468 /**
1469  * usort() callback to sort item arrays by pinned and the received key
1470  *
1471  * @param array $a
1472  * @param array $b
1473  * @return int
1474  */
1475 function sort_thr_pinned_received(array $a, array $b)
1476 {
1477         if ($b['pinned'] && !$a['pinned']) {
1478                 return 1;
1479         } elseif (!$b['pinned'] && $a['pinned']) {
1480                 return -1;
1481         }
1482
1483         return strcmp($b['received'], $a['received']);
1484 }
1485
1486 /**
1487  * usort() callback to sort item arrays by the received key
1488  *
1489  * @param array $a
1490  * @param array $b
1491  * @return int
1492  */
1493 function sort_thr_received(array $a, array $b)
1494 {
1495         return strcmp($b['received'], $a['received']);
1496 }
1497
1498 /**
1499  * usort() callback to reverse sort item arrays by the received key
1500  *
1501  * @param array $a
1502  * @param array $b
1503  * @return int
1504  */
1505 function sort_thr_received_rev(array $a, array $b)
1506 {
1507         return strcmp($a['received'], $b['received']);
1508 }
1509
1510 /**
1511  * usort() callback to sort item arrays by the commented key
1512  *
1513  * @param array $a
1514  * @param array $b
1515  * @return int
1516  */
1517 function sort_thr_commented(array $a, array $b)
1518 {
1519         return strcmp($b['commented'], $a['commented']);
1520 }