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