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