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