]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #10362 from tobiasd/2021.06-CHANGELOG
[friendica.git] / include / conversation.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\ContactSelector;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\Theme;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Tag;
39 use Friendica\Model\Verb;
40 use Friendica\Object\Post as PostObject;
41 use Friendica\Object\Thread;
42 use Friendica\Protocol\Activity;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Proxy;
46 use Friendica\Util\Strings;
47 use Friendica\Util\Temporal;
48 use Friendica\Util\XML;
49
50 function item_extract_images($body) {
51
52         $saved_image = [];
53         $orig_body = $body;
54         $new_body = '';
55
56         $cnt = 0;
57         $img_start = strpos($orig_body, '[img');
58         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
59         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
60         while (($img_st_close !== false) && ($img_end !== false)) {
61
62                 $img_st_close++; // make it point to AFTER the closing bracket
63                 $img_end += $img_start;
64
65                 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
66                         // This is an embedded image
67
68                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
69                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
70
71                         $cnt++;
72                 } else {
73                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
74                 }
75
76                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
77
78                 if ($orig_body === false) {
79                         // in case the body ends on a closing image tag
80                         $orig_body = '';
81                 }
82
83                 $img_start = strpos($orig_body, '[img');
84                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
85                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
86         }
87
88         $new_body = $new_body . $orig_body;
89
90         return ['body' => $new_body, 'images' => $saved_image];
91 }
92
93 function item_redir_and_replace_images($body, $images, $cid) {
94
95         $origbody = $body;
96         $newbody = '';
97
98         $cnt = 1;
99         $pos = BBCode::getTagPosition($origbody, 'url', 0);
100         while ($pos !== false && $cnt < 1000) {
101
102                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
103                 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
104                                    . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
105
106                 $newbody .= substr($origbody, 0, $pos['start']['open']);
107                 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
108                 $origbody = substr($origbody, $pos['end']['close']);
109                 if ($origbody === false) {
110                         $origbody = '';
111                 }
112
113                 $subject = preg_replace($search, $replace, $subject);
114                 $newbody .= $subject;
115
116                 $cnt++;
117                 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
118                 $pos = BBCode::getTagPosition($origbody, 'url', 0);
119         }
120         $newbody .= $origbody;
121
122         $cnt = 0;
123         foreach ($images as $image) {
124                 /*
125                  * We're depending on the property of 'foreach' (specified on the PHP website) that
126                  * it loops over the array starting from the first element and going sequentially
127                  * to the last element.
128                  */
129                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
130                 $cnt++;
131         }
132         return $newbody;
133 }
134
135 /**
136  * Render actions localized
137  *
138  * @param $item
139  * @throws ImagickException
140  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141  */
142 function localize_item(&$item)
143 {
144         $extracted = item_extract_images($item['body']);
145         if ($extracted['images']) {
146                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
147         }
148
149         /// @todo The following functionality needs to be cleaned up.
150         if (!empty($item['verb'])) {
151                 $activity = DI::activity();
152
153                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
154
155                 if (stristr($item['verb'], Activity::POKE)) {
156                         $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
157                         if (!$verb) {
158                                 return;
159                         }
160                         if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
161                                 return;
162                         }
163
164                         $obj = XML::parseString($xmlhead . $item['object']);
165
166                         $Bname = $obj->title;
167                         $Blink = $obj->id;
168                         $Bphoto = "";
169
170                         foreach ($obj->link as $l) {
171                                 $atts = $l->attributes();
172                                 switch ($atts['rel']) {
173                                         case "alternate": $Blink = $atts['href'];
174                                         case "photo": $Bphoto = $atts['href'];
175                                 }
176                         }
177
178                         $author = ['uid' => 0, 'id' => $item['author-id'],
179                                 'network' => $item['author-network'], 'url' => $item['author-link']];
180                         $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
181
182                         if (!empty($Blink)) {
183                                 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
184                         } else {
185                                 $B = '';
186                         }
187
188                         if ($Bphoto != "" && !empty($Blink)) {
189                                 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
190                         }
191
192                         /*
193                          * we can't have a translation string with three positions but no distinguishable text
194                          * So here is the translate string.
195                          */
196                         $txt = DI::l10n()->t('%1$s poked %2$s');
197
198                         // now translate the verb
199                         $poked_t = trim(sprintf($txt, '', ''));
200                         $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
201
202                         // then do the sprintf on the translation string
203
204                         $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
205
206                 }
207
208                 if ($activity->match($item['verb'], Activity::TAG)) {
209                         $fields = ['author-id', 'author-link', 'author-name', 'author-network',
210                                 'verb', 'object-type', 'resource-id', 'body', 'plink'];
211                         $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
212                         if (!DBA::isResult($obj)) {
213                                 return;
214                         }
215
216                         $author_arr = ['uid' => 0, 'id' => $item['author-id'],
217                                 'network' => $item['author-network'], 'url' => $item['author-link']];
218                         $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
219
220                         $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
221                                 'network' => $obj['author-network'], 'url' => $obj['author-link']];
222                         $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
223
224                         switch ($obj['verb']) {
225                                 case Activity::POST:
226                                         switch ($obj['object-type']) {
227                                                 case Activity\ObjectType::EVENT:
228                                                         $post_type = DI::l10n()->t('event');
229                                                         break;
230                                                 default:
231                                                         $post_type = DI::l10n()->t('status');
232                                         }
233                                         break;
234                                 default:
235                                         if ($obj['resource-id']) {
236                                                 $post_type = DI::l10n()->t('photo');
237                                                 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
238                                                 $rr['plink'] = $m[1];
239                                         } else {
240                                                 $post_type = DI::l10n()->t('status');
241                                         }
242                                         // Let's break everthing ... ;-)
243                                         break;
244                         }
245                         $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
246
247                         $parsedobj = XML::parseString($xmlhead . $item['object']);
248
249                         $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
250                         $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
251                 }
252         }
253
254         $matches = null;
255         if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
256                 foreach ($matches as $mtch) {
257                         if (!strpos($mtch[1], 'zrl=')) {
258                                 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
259                         }
260                 }
261         }
262
263         // add zrl's to public images
264         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
265         if (preg_match($photo_pattern, $item['body'])) {
266                 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' , true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
267                 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
268         }
269
270         // add sparkle links to appropriate permalinks
271         // Only create a redirection to a magic link when logged in
272         if (!empty($item['plink']) && Session::isAuthenticated()) {
273                 $author = ['uid' => 0, 'id' => $item['author-id'],
274                         'network' => $item['author-network'], 'url' => $item['author-link']];
275                 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
276         }
277 }
278
279 /**
280  * Count the total of comments on this item and its desendants
281  * @TODO proper type-hint + doc-tag
282  * @param $item
283  * @return int
284  */
285 function count_descendants($item) {
286         $total = count($item['children']);
287
288         if ($total > 0) {
289                 foreach ($item['children'] as $child) {
290                         if (!visible_activity($child)) {
291                                 $total --;
292                         }
293                         $total += count_descendants($child);
294                 }
295         }
296
297         return $total;
298 }
299
300 function visible_activity($item) {
301
302         $activity = DI::activity();
303
304         if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
305                 return false;
306         }
307
308         // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
309         if ($activity->match($item['verb'], Activity::FOLLOW) &&
310             $item['object-type'] === Activity\ObjectType::NOTE &&
311             empty($item['self']) &&
312             $item['uid'] == local_user()) {
313                 return false;
314         }
315
316         return true;
317 }
318
319 function conv_get_blocklist()
320 {
321         if (!local_user()) {
322                 return [];
323         }
324
325         $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
326         if (empty($str_blocked)) {
327                 return [];
328         }
329
330         $blocklist = [];
331
332         foreach (explode(',', $str_blocked) as $entry) {
333                 $cid = Contact::getIdForURL(trim($entry), 0, false);
334                 if (!empty($cid)) {
335                         $blocklist[] = $cid;
336                 }
337         }
338
339         return $blocklist;
340 }
341
342 /**
343  * "Render" a conversation or list of items for HTML display.
344  * There are two major forms of display:
345  *      - Sequential or unthreaded ("New Item View" or search results)
346  *      - conversation view
347  * The $mode parameter decides between the various renderings and also
348  * figures out how to determine page owner and other contextual items
349  * that are based on unique features of the calling module.
350  * @param App    $a
351  * @param array  $items
352  * @param        $mode
353  * @param        $update
354  * @param bool   $preview
355  * @param string $order
356  * @param int    $uid
357  * @return string
358  * @throws ImagickException
359  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360  */
361 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
362 {
363         $page = DI::page();
364
365         $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
366         $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
367         $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
368         $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
369
370         $ssl_state = (local_user() ? true : false);
371
372         $profile_owner = 0;
373         $live_update_div = '';
374
375         $blocklist = conv_get_blocklist();
376
377         $previewing = (($preview) ? ' preview ' : '');
378
379         if ($mode === 'network') {
380                 $items = conversation_add_children($items, false, $order, $uid);
381                 $profile_owner = local_user();
382                 if (!$update) {
383                         /*
384                          * The special div is needed for liveUpdate to kick in for this page.
385                          * We only launch liveUpdate if you aren't filtering in some incompatible
386                          * way and also you aren't writing a comment (discovered in javascript).
387                          */
388                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
389                                 . "<script> var profile_uid = " . $_SESSION['uid']
390                                 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
391                                 . '?f='
392                                 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
393                                 . (!empty($_GET['search'])    ? '&search='    . rawurlencode($_GET['search'])    : '')
394                                 . (!empty($_GET['star'])      ? '&star='      . rawurlencode($_GET['star'])      : '')
395                                 . (!empty($_GET['order'])     ? '&order='     . rawurlencode($_GET['order'])     : '')
396                                 . (!empty($_GET['bmark'])     ? '&bmark='     . rawurlencode($_GET['bmark'])     : '')
397                                 . (!empty($_GET['liked'])     ? '&liked='     . rawurlencode($_GET['liked'])     : '')
398                                 . (!empty($_GET['conv'])      ? '&conv='      . rawurlencode($_GET['conv'])      : '')
399                                 . (!empty($_GET['nets'])      ? '&nets='      . rawurlencode($_GET['nets'])      : '')
400                                 . (!empty($_GET['cmin'])      ? '&cmin='      . rawurlencode($_GET['cmin'])      : '')
401                                 . (!empty($_GET['cmax'])      ? '&cmax='      . rawurlencode($_GET['cmax'])      : '')
402                                 . (!empty($_GET['file'])      ? '&file='      . rawurlencode($_GET['file'])      : '')
403
404                                 . "'; </script>\r\n";
405                 }
406         } elseif ($mode === 'profile') {
407                 $items = conversation_add_children($items, false, $order, $uid);
408                 $profile_owner = $a->profile['uid'];
409
410                 if (!$update) {
411                         $tab = 'posts';
412                         if (!empty($_GET['tab'])) {
413                                 $tab = Strings::escapeTags(trim($_GET['tab']));
414                         }
415                         if ($tab === 'posts') {
416                                 /*
417                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
418                                  * because browser prefetching might change it on us. We have to deliver it with the page.
419                                  */
420
421                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
422                                         . "<script> var profile_uid = " . $a->profile['uid']
423                                         . "; var netargs = '?f='; </script>\r\n";
424                         }
425                 }
426         } elseif ($mode === 'notes') {
427                 $items = conversation_add_children($items, false, $order, local_user());
428                 $profile_owner = local_user();
429
430                 if (!$update) {
431                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
432                                 . "<script> var profile_uid = " . local_user()
433                                 . "; var netargs = '/?f='; </script>\r\n";
434                 }
435         } elseif ($mode === 'display') {
436                 $items = conversation_add_children($items, false, $order, $uid);
437                 $profile_owner = $a->profile['uid'];
438
439                 if (!$update) {
440                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
441                                 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
442                                 . "</script>";
443                 }
444         } elseif ($mode === 'community') {
445                 $items = conversation_add_children($items, true, $order, $uid);
446                 $profile_owner = 0;
447
448                 if (!$update) {
449                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
450                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
451                                 . '?f='
452                                 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
453                                 . "'; </script>\r\n";
454                 }
455         } elseif ($mode === 'contacts') {
456                 $items = conversation_add_children($items, false, $order, $uid);
457                 $profile_owner = 0;
458
459                 if (!$update) {
460                         $live_update_div = '<div id="live-contact"></div>' . "\r\n"
461                                 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
462                                 ."/?f='; </script>\r\n";
463                 }
464         } elseif ($mode === 'search') {
465                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
466         }
467
468         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
469
470         if (!$update) {
471                 $_SESSION['return_path'] = DI::args()->getQueryString();
472         }
473
474         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
475         Hook::callAll('conversation_start', $cb);
476
477         $items = $cb['items'];
478
479         $conv_responses = [
480                 'like'        => [],
481                 'dislike'     => [],
482                 'attendyes'   => [],
483                 'attendno'    => [],
484                 'attendmaybe' => [],
485                 'announce'    => [],
486         ];
487
488         if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
489                 unset($conv_responses['dislike']);
490         }
491
492         // array with html for each thread (parent+comments)
493         $threads = [];
494         $threadsid = -1;
495
496         $page_template = Renderer::getMarkupTemplate("conversation.tpl");
497
498         if (!empty($items)) {
499                 if (in_array($mode, ['community', 'contacts'])) {
500                         $writable = true;
501                 } else {
502                         $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
503                 }
504
505                 if (!local_user()) {
506                         $writable = false;
507                 }
508
509                 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
510
511                         /*
512                          * "New Item View" on network page or search page results
513                          * - just loop through the items and format them minimally for display
514                          */
515
516                         $tpl = 'search_item.tpl';
517
518                         foreach ($items as $item) {
519
520                                 if (!visible_activity($item)) {
521                                         continue;
522                                 }
523
524                                 if (in_array($item['author-id'], $blocklist)) {
525                                         continue;
526                                 }
527
528                                 $threadsid++;
529
530                                 // prevent private email from leaking.
531                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
532                                         continue;
533                                 }
534
535                                 $profile_name = $item['author-name'];
536                                 if (!empty($item['author-link']) && empty($item['author-name'])) {
537                                         $profile_name = $item['author-link'];
538                                 }
539
540                                 $tags = Tag::populateFromItem($item);
541
542                                 $author = ['uid' => 0, 'id' => $item['author-id'],
543                                         'network' => $item['author-network'], 'url' => $item['author-link']];
544                                 $profile_link = Contact::magicLinkByContact($author);
545
546                                 $sparkle = '';
547                                 if (strpos($profile_link, 'redir/') === 0) {
548                                         $sparkle = ' sparkle';
549                                 }
550
551                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
552                                 Hook::callAll('render_location', $locate);
553                                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
554
555                                 localize_item($item);
556                                 if ($mode === 'filed') {
557                                         $dropping = true;
558                                 } else {
559                                         $dropping = false;
560                                 }
561
562                                 $drop = [
563                                         'dropping' => $dropping,
564                                         'pagedrop' => $page_dropping,
565                                         'select' => DI::l10n()->t('Select'),
566                                         'delete' => DI::l10n()->t('Delete'),
567                                 ];
568
569                                 $likebuttons = [
570                                         'like'     => null,
571                                         'dislike'  => null,
572                                         'share'    => null,
573                                         'announce' => null,
574                                 ];
575
576                                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
577                                         unset($likebuttons['dislike']);
578                                 }
579
580                                 $body_html = Item::prepareBody($item, true, $preview);
581
582                                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
583
584                                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
585                                         $title = ucfirst($item['content-warning']);
586                                 } else {
587                                         $title = $item['title'];
588                                 }
589
590                                 $tmp_item = [
591                                         'template' => $tpl,
592                                         'id' => ($preview ? 'P0' : $item['id']),
593                                         'guid' => ($preview ? 'Q0' : $item['guid']),
594                                         'commented' => $item['commented'],
595                                         'received' => $item['received'],
596                                         'created_date' => $item['created'],
597                                         'uriid' => $item['uri-id'],
598                                         'network' => $item['network'],
599                                         'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
600                                         'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
601                                         'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
602                                         'profile_url' => $profile_link,
603                                         'item_photo_menu_html' => item_photo_menu($item),
604                                         'name' => $profile_name,
605                                         'sparkle' => $sparkle,
606                                         'lock' => false,
607                                         'thumb' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
608                                         'title' => $title,
609                                         'body_html' => $body_html,
610                                         'tags' => $tags['tags'],
611                                         'hashtags' => $tags['hashtags'],
612                                         'mentions' => $tags['mentions'],
613                                         'implicit_mentions' => $tags['implicit_mentions'],
614                                         'txt_cats' => DI::l10n()->t('Categories:'),
615                                         'txt_folders' => DI::l10n()->t('Filed under:'),
616                                         'has_cats' => ((count($categories)) ? 'true' : ''),
617                                         'has_folders' => ((count($folders)) ? 'true' : ''),
618                                         'categories' => $categories,
619                                         'folders' => $folders,
620                                         'text' => strip_tags($body_html),
621                                         'localtime' => DateTimeFormat::local($item['created'], 'r'),
622                                         'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
623                                         'location_html' => $location_html,
624                                         'indent' => '',
625                                         'owner_name' => '',
626                                         'owner_url' => '',
627                                         'owner_photo' => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
628                                         'plink' => Item::getPlink($item),
629                                         'edpost' => false,
630                                         'isstarred' => 'unstarred',
631                                         'star' => false,
632                                         'drop' => $drop,
633                                         'vote' => $likebuttons,
634                                         'like_html' => '',
635                                         'dislike_html' => '',
636                                         'comment_html' => '',
637                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
638                                         'previewing' => $previewing,
639                                         'wait' => DI::l10n()->t('Please wait'),
640                                         'thread_level' => 1,
641                                 ];
642
643                                 $arr = ['item' => $item, 'output' => $tmp_item];
644                                 Hook::callAll('display_item', $arr);
645
646                                 $threads[$threadsid]['id'] = $item['id'];
647                                 $threads[$threadsid]['network'] = $item['network'];
648                                 $threads[$threadsid]['items'] = [$arr['output']];
649
650                         }
651                 } else {
652                         // Normal View
653                         $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
654
655                         $conv = new Thread($mode, $preview, $writable);
656
657                         /*
658                          * get all the topmost parents
659                          * this shouldn't be needed, as we should have only them in our array
660                          * But for now, this array respects the old style, just in case
661                          */
662                         foreach ($items as $item) {
663                                 if (in_array($item['author-id'], $blocklist)) {
664                                         continue;
665                                 }
666
667                                 // Can we put this after the visibility check?
668                                 builtin_activity_puller($item, $conv_responses);
669
670                                 // Only add what is visible
671                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
672                                         continue;
673                                 }
674
675                                 if (!visible_activity($item)) {
676                                         continue;
677                                 }
678
679                                 /// @todo Check if this call is needed or not
680                                 $arr = ['item' => $item];
681                                 Hook::callAll('display_item', $arr);
682
683                                 $item['pagedrop'] = $page_dropping;
684
685                                 if ($item['gravity'] == GRAVITY_PARENT) {
686                                         $item_object = new PostObject($item);
687                                         $conv->addParent($item_object);
688                                 }
689                         }
690
691                         $threads = $conv->getTemplateData($conv_responses);
692                         if (!$threads) {
693                                 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
694                                 $threads = [];
695                         }
696                 }
697         }
698
699         $o = Renderer::replaceMacros($page_template, [
700                 '$baseurl' => DI::baseUrl()->get($ssl_state),
701                 '$return_path' => DI::args()->getQueryString(),
702                 '$live_update' => $live_update_div,
703                 '$remove' => DI::l10n()->t('remove'),
704                 '$mode' => $mode,
705                 '$update' => $update,
706                 '$user' => $a->user,
707                 '$threads' => $threads,
708                 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
709         ]);
710
711         return $o;
712 }
713
714 /**
715  * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
716  *
717  * @param mixed   $thread_items Database statement with thread posts
718  * @param boolean $pinned       Is the item pinned?
719  * @param array   $activity     Contact data of the resharer
720  *
721  * @return array items with parents and comments
722  */
723 function conversation_fetch_comments($thread_items, bool $pinned, array $activity) {
724         $comments = [];
725
726         while ($row = Post::fetch($thread_items)) {
727                 if (!empty($activity)) {
728                         if (($row['gravity'] == GRAVITY_PARENT)) {
729                                 $row['post-reason'] = Item::PR_ANNOUNCEMENT;
730                                 $row = array_merge($row, $activity);
731                                 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
732                                 $row['causer-link'] = $contact['url'];
733                                 $row['causer-avatar'] = $contact['thumb'];
734                                 $row['causer-name'] = $contact['name'];
735                         } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
736                                 ($row['author-id'] == $activity['causer-id'])) {
737                                 continue;
738                         }
739                 }
740
741                 switch ($row['post-reason']) {
742                         case Item::PR_TO:
743                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
744                                 break;
745                         case Item::PR_CC:
746                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
747                                 break;
748                         case Item::PR_BTO:
749                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
750                                 break;
751                         case Item::PR_BCC:
752                                 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
753                                 break;
754                         case Item::PR_FOLLOWER:
755                                 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
756                                 break;
757                         case Item::PR_TAG:
758                                 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
759                                 break;
760                         case Item::PR_ANNOUNCEMENT:
761                                 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
762                                         $row['owner-id'] = $row['causer-id'];
763                                         $row['owner-link'] = $row['causer-link'];
764                                         $row['owner-avatar'] = $row['causer-avatar'];
765                                         $row['owner-name'] = $row['causer-name'];
766                                 }
767
768                                 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
769                                         $causer = ['uid' => 0, 'id' => $row['causer-id'],
770                                                 'network' => $row['causer-network'], 'url' => $row['causer-link']];
771                                         $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkByContact($causer)) .'">' . htmlentities($row['causer-name']) . '</a>');
772                                 }
773                                 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s <%s>', $row['causer-name'], $row['causer-link']))];
774                                 break;
775                         case Item::PR_COMMENT:
776                                 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
777                                 break;
778                         case Item::PR_STORED:
779                                 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
780                                 break;
781                         case Item::PR_GLOBAL:
782                                 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
783                                 break;
784                         case Item::PR_RELAY:
785                                 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s <%s>', $row['causer-name'], $row['causer-link']))];
786                                 break;
787                         case Item::PR_FETCHED:
788                                 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s <%s>', $row['causer-name'], $row['causer-link']))];
789                                 break;
790                         }
791
792                 if ($row['gravity'] == GRAVITY_PARENT) {
793                         $row['pinned'] = $pinned;
794                 }
795
796                 $comments[] = $row;
797         }
798
799         DBA::close($thread_items);
800
801         return $comments;
802 }
803
804 /**
805  * Add comments to top level entries that had been fetched before
806  *
807  * The system will fetch the comments for the local user whenever possible.
808  * This behaviour is currently needed to allow commenting on Friendica posts.
809  *
810  * @param array $parents Parent items
811  *
812  * @param       $block_authors
813  * @param       $order
814  * @param       $uid
815  * @return array items with parents and comments
816  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817  */
818 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
819         if (count($parents) > 1) {
820                 $max_comments = DI::config()->get('system', 'max_comments', 100);
821         } else {
822                 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
823         }
824
825         $params = ['order' => ['gravity', 'uid', 'commented' => true]];
826
827         if ($max_comments > 0) {
828                 $params['limit'] = $max_comments;
829         }
830
831         $items = [];
832
833         foreach ($parents AS $parent) {
834                 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
835                         $condition = ["`parent-uri-id` = ? AND `uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
836                                 $parent['thr-parent-id'], $uid, Verb::getID(Activity::FOLLOW)];
837                         if (!empty($parent['author-id'])) {
838                                 $activity = ['causer-id' => $parent['author-id']];
839                                 foreach (['commented', 'received', 'created'] as $orderfields) {
840                                         if (!empty($parent[$orderfields])) {
841                                                 $activity[$orderfields] = $parent[$orderfields];
842                                         }
843                                 }
844                         }
845                 } else {
846                         $condition = ["`parent-uri-id` = ? AND `uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
847                                 $parent['uri-id'], $uid, Verb::getID(Activity::FOLLOW)];
848                         $activity = [];
849                 }
850                 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params, $activity);
851         }
852
853         foreach ($items as $index => $item) {
854                 if ($item['uid'] == 0) {
855                         $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
856                 }
857         }
858
859         $items = conv_sort($items, $order);
860
861         return $items;
862 }
863
864 /**
865  * Fetch conversation items
866  *
867  * @param array   $parent        Parent Item array
868  * @param array   $items         Item array
869  * @param array   $condition     SQL condition
870  * @param boolean $block_authors Don't show posts from contacts that are hidden (used on the community page)
871  * @param array   $params        SQL parameters
872  * @param array   $activity      Contact data of the resharer
873  * @return array
874  */
875 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params, array $activity) {
876         if ($block_authors) {
877                 $condition[0] .= " AND NOT `author-hidden`";
878         }
879
880         $thread_items = Post::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type', 'post-reason']), $condition, $params);
881
882         $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false, $activity);
883
884         if (count($comments) != 0) {
885                 $items = array_merge($items, $comments);
886         }
887         return $items;
888 }
889
890 function item_photo_menu($item)
891 {
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  = $item['self'] ? '' : $contact_url . '/block';
933                 $ignore_link = $item['self'] ? '' : $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                 '$edvideo'      => DI::l10n()->t('Video'),
1215                 '$setloc'       => DI::l10n()->t('Set your location'),
1216                 '$shortsetloc'  => DI::l10n()->t('set location'),
1217                 '$noloc'        => DI::l10n()->t('Clear browser location'),
1218                 '$shortnoloc'   => DI::l10n()->t('clear location'),
1219                 '$title'        => $x['title'] ?? '',
1220                 '$placeholdertitle' => DI::l10n()->t('Set title'),
1221                 '$category'     => $x['category'] ?? '',
1222                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1223                 '$wait'         => DI::l10n()->t('Please wait'),
1224                 '$permset'      => DI::l10n()->t('Permission settings'),
1225                 '$shortpermset' => DI::l10n()->t('Permissions'),
1226                 '$wall'         => $notes_cid ? 0 : 1,
1227                 '$posttype'     => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1228                 '$content'      => $x['content'] ?? '',
1229                 '$post_id'      => $x['post_id'] ?? '',
1230                 '$baseurl'      => DI::baseUrl()->get(true),
1231                 '$defloc'       => $x['default_location'],
1232                 '$visitor'      => $x['visitor'],
1233                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1234                 '$public'       => DI::l10n()->t('Public post'),
1235                 '$lockstate'    => $x['lockstate'],
1236                 '$bang'         => $x['bang'],
1237                 '$profile_uid'  => $x['profile_uid'],
1238                 '$preview'      => DI::l10n()->t('Preview'),
1239                 '$jotplugins'   => $jotplugins,
1240                 '$notes_cid'    => $notes_cid,
1241                 '$sourceapp'    => DI::l10n()->t($a->sourcename),
1242                 '$cancel'       => DI::l10n()->t('Cancel'),
1243                 '$rand_num'     => Crypto::randomDigits(12),
1244
1245                 // ACL permissions box
1246                 '$acl'           => $x['acl'],
1247
1248                 //jot nav tab (used in some themes)
1249                 '$message' => DI::l10n()->t('Message'),
1250                 '$browser' => DI::l10n()->t('Browser'),
1251
1252                 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1253         ]);
1254
1255
1256         if ($popup == true) {
1257                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1258         }
1259
1260         return $o;
1261 }
1262
1263 /**
1264  * Plucks the children of the given parent from a given item list.
1265  *
1266  * @param array $item_list
1267  * @param array $parent
1268  * @param bool  $recursive
1269  * @return array
1270  */
1271 function get_item_children(array &$item_list, array $parent, $recursive = true)
1272 {
1273         $children = [];
1274         foreach ($item_list as $i => $item) {
1275                 if ($item['gravity'] != GRAVITY_PARENT) {
1276                         if ($recursive) {
1277                                 // Fallback to parent-uri if thr-parent is not set
1278                                 $thr_parent = $item['thr-parent-id'];
1279                                 if ($thr_parent == '') {
1280                                         $thr_parent = $item['parent-uri-id'];
1281                                 }
1282
1283                                 if ($thr_parent == $parent['uri-id']) {
1284                                         $item['children'] = get_item_children($item_list, $item);
1285                                         $children[] = $item;
1286                                         unset($item_list[$i]);
1287                                 }
1288                         } elseif ($item['parent-uri-id'] == $parent['uri-id']) {
1289                                 $children[] = $item;
1290                                 unset($item_list[$i]);
1291                         }
1292                 }
1293         }
1294         return $children;
1295 }
1296
1297 /**
1298  * Recursively sorts a tree-like item array
1299  *
1300  * @param array $items
1301  * @return array
1302  */
1303 function sort_item_children(array $items)
1304 {
1305         $result = $items;
1306         usort($result, 'sort_thr_received_rev');
1307         foreach ($result as $k => $i) {
1308                 if (isset($result[$k]['children'])) {
1309                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1310                 }
1311         }
1312         return $result;
1313 }
1314
1315 /**
1316  * Recursively add all children items at the top level of a list
1317  *
1318  * @param array $children List of items to append
1319  * @param array $item_list
1320  */
1321 function add_children_to_list(array $children, array &$item_list)
1322 {
1323         foreach ($children as $child) {
1324                 $item_list[] = $child;
1325                 if (isset($child['children'])) {
1326                         add_children_to_list($child['children'], $item_list);
1327                 }
1328         }
1329 }
1330
1331 /**
1332  * Selectively flattens a tree-like item structure to prevent threading stairs
1333  *
1334  * This recursive function takes the item tree structure created by conv_sort() and
1335  * flatten the extraneous depth levels when people reply sequentially, removing the
1336  * stairs effect in threaded conversations limiting the available content width.
1337  *
1338  * The basic principle is the following: if a post item has only one reply and is
1339  * the last reply of its parent, then the reply is moved to the parent.
1340  *
1341  * This process is rendered somewhat more complicated because items can be either
1342  * replies or likes, and these don't factor at all in the reply count/last reply.
1343  *
1344  * @param array $parent A tree-like array of items
1345  * @return array
1346  */
1347 function smart_flatten_conversation(array $parent)
1348 {
1349         if (!isset($parent['children']) || count($parent['children']) == 0) {
1350                 return $parent;
1351         }
1352
1353         // We use a for loop to ensure we process the newly-moved items
1354         for ($i = 0; $i < count($parent['children']); $i++) {
1355                 $child = $parent['children'][$i];
1356
1357                 if (isset($child['children']) && count($child['children'])) {
1358                         // This helps counting only the regular posts
1359                         $count_post_closure = function($var) {
1360                                 return $var['verb'] === Activity::POST;
1361                         };
1362
1363                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1364
1365                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1366
1367                         // If there's only one child's children post and this is the last child post
1368                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1369
1370                                 // Searches the post item in the children
1371                                 $j = 0;
1372                                 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1373                                         $j ++;
1374                                 }
1375
1376                                 $moved_item = $child['children'][$j];
1377                                 unset($parent['children'][$i]['children'][$j]);
1378                                 $parent['children'][] = $moved_item;
1379                         } else {
1380                                 $parent['children'][$i] = smart_flatten_conversation($child);
1381                         }
1382                 }
1383         }
1384
1385         return $parent;
1386 }
1387
1388
1389 /**
1390  * Expands a flat list of items into corresponding tree-like conversation structures.
1391  *
1392  * sort the top-level posts either on "received" or "commented", and finally
1393  * append all the items at the top level (???)
1394  *
1395  * @param array  $item_list A list of items belonging to one or more conversations
1396  * @param string $order     Either on "received" or "commented"
1397  * @return array
1398  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1399  */
1400 function conv_sort(array $item_list, $order)
1401 {
1402         $parents = [];
1403
1404         if (!(is_array($item_list) && count($item_list))) {
1405                 return $parents;
1406         }
1407
1408         $blocklist = conv_get_blocklist();
1409
1410         $item_array = [];
1411
1412         // Dedupes the item list on the uri to prevent infinite loops
1413         foreach ($item_list as $item) {
1414                 if (in_array($item['author-id'], $blocklist)) {
1415                         continue;
1416                 }
1417
1418                 $item_array[$item['uri-id']] = $item;
1419         }
1420
1421         // Extract the top level items
1422         foreach ($item_array as $item) {
1423                 if ($item['gravity'] == GRAVITY_PARENT) {
1424                         $parents[] = $item;
1425                 }
1426         }
1427
1428         if (stristr($order, 'pinned_received')) {
1429                 usort($parents, 'sort_thr_pinned_received');
1430         } elseif (stristr($order, 'received')) {
1431                 usort($parents, 'sort_thr_received');
1432         } elseif (stristr($order, 'commented')) {
1433                 usort($parents, 'sort_thr_commented');
1434         }
1435
1436         /*
1437          * Plucks children from the item_array, second pass collects eventual orphan
1438          * items and add them as children of their top-level post.
1439          */
1440         foreach ($parents as $i => $parent) {
1441                 $parents[$i]['children'] =
1442                         array_merge(get_item_children($item_array, $parent, true),
1443                                 get_item_children($item_array, $parent, false));
1444         }
1445
1446         foreach ($parents as $i => $parent) {
1447                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1448         }
1449
1450         if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1451                 foreach ($parents as $i => $parent) {
1452                         $parents[$i] = smart_flatten_conversation($parent);
1453                 }
1454         }
1455
1456         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1457         /// However, this apparently ensures responses (likes, attendance) display (?!)
1458         foreach ($parents as $parent) {
1459                 if (count($parent['children'])) {
1460                         add_children_to_list($parent['children'], $parents);
1461                 }
1462         }
1463
1464         return $parents;
1465 }
1466
1467 /**
1468  * usort() callback to sort item arrays by pinned and the received key
1469  *
1470  * @param array $a
1471  * @param array $b
1472  * @return int
1473  */
1474 function sort_thr_pinned_received(array $a, array $b)
1475 {
1476         if ($b['pinned'] && !$a['pinned']) {
1477                 return 1;
1478         } elseif (!$b['pinned'] && $a['pinned']) {
1479                 return -1;
1480         }
1481
1482         return strcmp($b['received'], $a['received']);
1483 }
1484
1485 /**
1486  * usort() callback to sort item arrays by the received key
1487  *
1488  * @param array $a
1489  * @param array $b
1490  * @return int
1491  */
1492 function sort_thr_received(array $a, array $b)
1493 {
1494         return strcmp($b['received'], $a['received']);
1495 }
1496
1497 /**
1498  * usort() callback to reverse sort item arrays by the received key
1499  *
1500  * @param array $a
1501  * @param array $b
1502  * @return int
1503  */
1504 function sort_thr_received_rev(array $a, array $b)
1505 {
1506         return strcmp($a['received'], $b['received']);
1507 }
1508
1509 /**
1510  * usort() callback to sort item arrays by the commented key
1511  *
1512  * @param array $a
1513  * @param array $b
1514  * @return int
1515  */
1516 function sort_thr_commented(array $a, array $b)
1517 {
1518         return strcmp($b['commented'], $a['commented']);
1519 }