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