3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
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;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Tag;
39 use Friendica\Model\Verb;
40 use Friendica\Object\Post as PostObject;
41 use Friendica\Object\Thread;
42 use Friendica\Protocol\Activity;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Strings;
46 use Friendica\Util\Temporal;
47 use Friendica\Util\XML;
49 function item_extract_images($body) {
56 $img_start = strpos($orig_body, '[img');
57 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
58 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
59 while (($img_st_close !== false) && ($img_end !== false)) {
61 $img_st_close++; // make it point to AFTER the closing bracket
62 $img_end += $img_start;
64 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
65 // This is an embedded image
67 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
68 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
72 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
75 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
77 if ($orig_body === false) {
78 // in case the body ends on a closing image tag
82 $img_start = strpos($orig_body, '[img');
83 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
84 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
87 $new_body = $new_body . $orig_body;
89 return ['body' => $new_body, 'images' => $saved_image];
92 function item_redir_and_replace_images($body, $images, $cid) {
98 $pos = BBCode::getTagPosition($origbody, 'url', 0);
99 while ($pos !== false && $cnt < 1000) {
101 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
102 $replace = '[url=' . DI::baseUrl() . '/redir/' . $cid
103 . '?url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
105 $newbody .= substr($origbody, 0, $pos['start']['open']);
106 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
107 $origbody = substr($origbody, $pos['end']['close']);
108 if ($origbody === false) {
112 $subject = preg_replace($search, $replace, $subject);
113 $newbody .= $subject;
116 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
117 $pos = BBCode::getTagPosition($origbody, 'url', 0);
119 $newbody .= $origbody;
122 foreach ($images as $image) {
124 * We're depending on the property of 'foreach' (specified on the PHP website) that
125 * it loops over the array starting from the first element and going sequentially
126 * to the last element.
128 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
135 * Render actions localized
138 * @throws ImagickException
139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 function localize_item(&$item)
143 $extracted = item_extract_images($item['body']);
144 if ($extracted['images']) {
145 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
148 /// @todo The following functionality needs to be cleaned up.
149 if (!empty($item['verb'])) {
150 $activity = DI::activity();
152 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
154 if (stristr($item['verb'], Activity::POKE)) {
155 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
159 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
163 $Aname = $item['author-name'];
164 $Alink = $item['author-link'];
166 $obj = XML::parseString($xmlhead . $item['object']);
168 $Bname = $obj->title;
172 foreach ($obj->link as $l) {
173 $atts = $l->attributes();
174 switch ($atts['rel']) {
175 case "alternate": $Blink = $atts['href'];
176 case "photo": $Bphoto = $atts['href'];
180 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
181 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
183 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
187 * we can't have a translation string with three positions but no distinguishable text
188 * So here is the translate string.
190 $txt = DI::l10n()->t('%1$s poked %2$s');
192 // now translate the verb
193 $poked_t = trim(sprintf($txt, '', ''));
194 $txt = str_replace($poked_t, DI::l10n()->t($verb), $txt);
196 // then do the sprintf on the translation string
198 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
202 if ($activity->match($item['verb'], Activity::TAG)) {
203 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
204 'verb', 'object-type', 'resource-id', 'body', 'plink'];
205 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
206 if (!DBA::isResult($obj)) {
210 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
211 'network' => $item['author-network'], 'url' => $item['author-link']];
212 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
214 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
215 'network' => $obj['author-network'], 'url' => $obj['author-link']];
216 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
218 switch ($obj['verb']) {
220 switch ($obj['object-type']) {
221 case Activity\ObjectType::EVENT:
222 $post_type = DI::l10n()->t('event');
225 $post_type = DI::l10n()->t('status');
229 if ($obj['resource-id']) {
230 $post_type = DI::l10n()->t('photo');
231 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
232 $rr['plink'] = $m[1];
234 $post_type = DI::l10n()->t('status');
236 // Let's break everthing ... ;-)
239 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
241 $parsedobj = XML::parseString($xmlhead . $item['object']);
243 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
244 $item['body'] = DI::l10n()->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
249 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
250 foreach ($matches as $mtch) {
251 if (!strpos($mtch[1], 'zrl=')) {
252 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
257 // add zrl's to public images
258 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
259 if (preg_match($photo_pattern, $item['body'])) {
260 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' , true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
261 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
264 // add sparkle links to appropriate permalinks
265 $author = ['uid' => 0, 'id' => $item['author-id'],
266 'network' => $item['author-network'], 'url' => $item['author-link']];
268 // Only create a redirection to a magic link when logged in
269 if (!empty($item['plink']) && Session::isAuthenticated()) {
270 $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
275 * Count the total of comments on this item and its desendants
276 * @TODO proper type-hint + doc-tag
280 function count_descendants($item) {
281 $total = count($item['children']);
284 foreach ($item['children'] as $child) {
285 if (!visible_activity($child)) {
288 $total += count_descendants($child);
295 function visible_activity($item) {
297 $activity = DI::activity();
299 if (empty($item['verb']) || $activity->isHidden($item['verb'])) {
303 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
304 if ($activity->match($item['verb'], Activity::FOLLOW) &&
305 $item['object-type'] === Activity\ObjectType::NOTE &&
306 empty($item['self']) &&
307 $item['uid'] == local_user()) {
314 function conv_get_blocklist()
320 $str_blocked = str_replace(["\n", "\r"], ",", DI::pConfig()->get(local_user(), 'system', 'blocked'));
321 if (empty($str_blocked)) {
327 foreach (explode(',', $str_blocked) as $entry) {
328 $cid = Contact::getIdForURL(trim($entry), 0, false);
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.
346 * @param array $items
349 * @param bool $preview
350 * @param string $order
353 * @throws ImagickException
354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
360 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
361 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
362 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
363 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
365 $ssl_state = (local_user() ? true : false);
368 $live_update_div = '';
370 $blocklist = conv_get_blocklist();
372 $previewing = (($preview) ? ' preview ' : '');
374 if ($mode === 'network') {
375 $items = conversation_add_children($items, false, $order, $uid);
376 $profile_owner = local_user();
379 * The special div is needed for liveUpdate to kick in for this page.
380 * We only launch liveUpdate if you aren't filtering in some incompatible
381 * way and also you aren't writing a comment (discovered in javascript).
383 $live_update_div = '<div id="live-network"></div>' . "\r\n"
384 . "<script> var profile_uid = " . $_SESSION['uid']
385 . "; var netargs = '" . substr(DI::args()->getCommand(), 8)
387 . (!empty($_GET['contactid']) ? '&contactid=' . rawurlencode($_GET['contactid']) : '')
388 . (!empty($_GET['search']) ? '&search=' . rawurlencode($_GET['search']) : '')
389 . (!empty($_GET['star']) ? '&star=' . rawurlencode($_GET['star']) : '')
390 . (!empty($_GET['order']) ? '&order=' . rawurlencode($_GET['order']) : '')
391 . (!empty($_GET['bmark']) ? '&bmark=' . rawurlencode($_GET['bmark']) : '')
392 . (!empty($_GET['liked']) ? '&liked=' . rawurlencode($_GET['liked']) : '')
393 . (!empty($_GET['conv']) ? '&conv=' . rawurlencode($_GET['conv']) : '')
394 . (!empty($_GET['nets']) ? '&nets=' . rawurlencode($_GET['nets']) : '')
395 . (!empty($_GET['cmin']) ? '&cmin=' . rawurlencode($_GET['cmin']) : '')
396 . (!empty($_GET['cmax']) ? '&cmax=' . rawurlencode($_GET['cmax']) : '')
397 . (!empty($_GET['file']) ? '&file=' . rawurlencode($_GET['file']) : '')
399 . "'; </script>\r\n";
401 } elseif ($mode === 'profile') {
402 $items = conversation_add_children($items, false, $order, $uid);
403 $profile_owner = $a->profile['uid'];
407 if (!empty($_GET['tab'])) {
408 $tab = Strings::escapeTags(trim($_GET['tab']));
410 if ($tab === 'posts') {
412 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
413 * because browser prefetching might change it on us. We have to deliver it with the page.
416 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
417 . "<script> var profile_uid = " . $a->profile['uid']
418 . "; var netargs = '?f='; </script>\r\n";
421 } elseif ($mode === 'notes') {
422 $items = conversation_add_children($items, false, $order, local_user());
423 $profile_owner = local_user();
426 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
427 . "<script> var profile_uid = " . local_user()
428 . "; var netargs = '/?f='; </script>\r\n";
430 } elseif ($mode === 'display') {
431 $items = conversation_add_children($items, false, $order, $uid);
432 $profile_owner = $a->profile['uid'];
435 $live_update_div = '<div id="live-display"></div>' . "\r\n"
436 . "<script> var profile_uid = " . Session::get('uid', 0) . ";"
439 } elseif ($mode === 'community') {
440 $items = conversation_add_children($items, true, $order, $uid);
444 $live_update_div = '<div id="live-community"></div>' . "\r\n"
445 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 10)
447 . (!empty($_GET['no_sharer']) ? '&no_sharer=' . rawurlencode($_GET['no_sharer']) : '')
448 . "'; </script>\r\n";
450 } elseif ($mode === 'contacts') {
451 $items = conversation_add_children($items, false, $order, $uid);
455 $live_update_div = '<div id="live-contact"></div>' . "\r\n"
456 . "<script> var profile_uid = -1; var netargs = '" . substr(DI::args()->getCommand(), 8)
457 ."/?f='; </script>\r\n";
459 } elseif ($mode === 'search') {
460 $live_update_div = '<div id="live-search"></div>' . "\r\n";
463 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
466 $_SESSION['return_path'] = DI::args()->getQueryString();
469 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
470 Hook::callAll('conversation_start', $cb);
472 $items = $cb['items'];
483 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
484 unset($conv_responses['dislike']);
487 // array with html for each thread (parent+comments)
491 $page_template = Renderer::getMarkupTemplate("conversation.tpl");
493 if (!empty($items)) {
494 if (in_array($mode, ['community', 'contacts'])) {
497 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], Protocol::FEDERATED);
504 if (in_array($mode, ['filed', 'search', 'contact-posts'])) {
507 * "New Item View" on network page or search page results
508 * - just loop through the items and format them minimally for display
511 $tpl = 'search_item.tpl';
513 foreach ($items as $item) {
515 if (!visible_activity($item)) {
519 if (in_array($item['author-id'], $blocklist)) {
525 // prevent private email from leaking.
526 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
530 $profile_name = $item['author-name'];
531 if (!empty($item['author-link']) && empty($item['author-name'])) {
532 $profile_name = $item['author-link'];
535 $tags = Tag::populateFromItem($item);
537 $author = ['uid' => 0, 'id' => $item['author-id'],
538 'network' => $item['author-network'], 'url' => $item['author-link']];
539 $profile_link = Contact::magicLinkByContact($author);
542 if (strpos($profile_link, 'redir/') === 0) {
543 $sparkle = ' sparkle';
546 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
547 Hook::callAll('render_location', $locate);
548 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
550 localize_item($item);
551 if ($mode === 'filed') {
558 'dropping' => $dropping,
559 'pagedrop' => $page_dropping,
560 'select' => DI::l10n()->t('Select'),
561 'delete' => DI::l10n()->t('Delete'),
571 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
572 unset($likebuttons['dislike']);
575 $body_html = Item::prepareBody($item, true, $preview);
577 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
579 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
580 $title = ucfirst($item['content-warning']);
582 $title = $item['title'];
587 'id' => ($preview ? 'P0' : $item['id']),
588 'guid' => ($preview ? 'Q0' : $item['guid']),
589 'commented' => $item['commented'],
590 'received' => $item['received'],
591 'created_date' => $item['created'],
592 'uriid' => $item['uri-id'],
593 'network' => $item['network'],
594 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
595 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link']),
596 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
597 'profile_url' => $profile_link,
598 'item_photo_menu_html' => item_photo_menu($item),
599 'name' => $profile_name,
600 'sparkle' => $sparkle,
602 'thumb' => DI::baseUrl()->remove($item['author-avatar']),
604 'body_html' => $body_html,
605 'tags' => $tags['tags'],
606 'hashtags' => $tags['hashtags'],
607 'mentions' => $tags['mentions'],
608 'implicit_mentions' => $tags['implicit_mentions'],
609 'txt_cats' => DI::l10n()->t('Categories:'),
610 'txt_folders' => DI::l10n()->t('Filed under:'),
611 'has_cats' => ((count($categories)) ? 'true' : ''),
612 'has_folders' => ((count($folders)) ? 'true' : ''),
613 'categories' => $categories,
614 'folders' => $folders,
615 'text' => strip_tags($body_html),
616 'localtime' => DateTimeFormat::local($item['created'], 'r'),
617 'ago' => (($item['app']) ? DI::l10n()->t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created'])),
618 'location_html' => $location_html,
622 'owner_photo' => DI::baseUrl()->remove($item['owner-avatar']),
623 'plink' => Item::getPlink($item),
625 'isstarred' => 'unstarred',
628 'vote' => $likebuttons,
630 'dislike_html' => '',
631 'comment_html' => '',
632 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> DI::l10n()->t('View in context')]),
633 'previewing' => $previewing,
634 'wait' => DI::l10n()->t('Please wait'),
638 $arr = ['item' => $item, 'output' => $tmp_item];
639 Hook::callAll('display_item', $arr);
641 $threads[$threadsid]['id'] = $item['id'];
642 $threads[$threadsid]['network'] = $item['network'];
643 $threads[$threadsid]['items'] = [$arr['output']];
648 $page_template = Renderer::getMarkupTemplate("threaded_conversation.tpl");
650 $conv = new Thread($mode, $preview, $writable);
653 * get all the topmost parents
654 * this shouldn't be needed, as we should have only them in our array
655 * But for now, this array respects the old style, just in case
657 foreach ($items as $item) {
658 if (in_array($item['author-id'], $blocklist)) {
662 // Can we put this after the visibility check?
663 builtin_activity_puller($item, $conv_responses);
665 // Only add what is visible
666 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
670 if (!visible_activity($item)) {
674 /// @todo Check if this call is needed or not
675 $arr = ['item' => $item];
676 Hook::callAll('display_item', $arr);
678 $item['pagedrop'] = $page_dropping;
680 if ($item['gravity'] == GRAVITY_PARENT) {
681 $item_object = new PostObject($item);
682 $conv->addParent($item_object);
686 $threads = $conv->getTemplateData($conv_responses);
688 Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
694 $o = Renderer::replaceMacros($page_template, [
695 '$baseurl' => DI::baseUrl()->get($ssl_state),
696 '$return_path' => DI::args()->getQueryString(),
697 '$live_update' => $live_update_div,
698 '$remove' => DI::l10n()->t('remove'),
700 '$update' => $update,
702 '$threads' => $threads,
703 '$dropping' => ($page_dropping ? DI::l10n()->t('Delete Selected Items') : False),
710 * Fetch all comments from a query. Additionally set the newest resharer as thread owner.
712 * @param mixed $thread_items Database statement with thread posts
713 * @param boolean $pinned Is the item pinned?
714 * @param array $activity Contact data of the resharer
716 * @return array items with parents and comments
718 function conversation_fetch_comments($thread_items, bool $pinned, array $activity) {
721 while ($row = Item::fetch($thread_items)) {
722 if (!empty($activity)) {
723 if (($row['gravity'] == GRAVITY_PARENT)) {
724 $row['post-type'] = Item::PT_ANNOUNCEMENT;
725 $row = array_merge($row, $activity);
726 $contact = Contact::getById($activity['causer-id'], ['url', 'name', 'thumb']);
727 $row['causer-link'] = $contact['url'];
728 $row['causer-avatar'] = $contact['thumb'];
729 $row['causer-name'] = $contact['name'];
730 } elseif (($row['gravity'] == GRAVITY_ACTIVITY) && ($row['verb'] == Activity::ANNOUNCE) &&
731 ($row['author-id'] == $activity['causer-id'])) {
736 $name = $row['causer-contact-type'] == Contact::TYPE_RELAY ? $row['causer-link'] : $row['causer-name'];
738 switch ($row['post-type']) {
740 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'to')];
743 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'cc')];
746 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bto')];
749 $row['direction'] = ['direction' => 7, 'title' => DI::l10n()->t('You had been addressed (%s).', 'bcc')];
751 case Item::PT_FOLLOWER:
752 $row['direction'] = ['direction' => 6, 'title' => DI::l10n()->t('You are following %s.', $row['author-name'])];
755 $row['direction'] = ['direction' => 4, 'title' => DI::l10n()->t('Tagged')];
757 case Item::PT_ANNOUNCEMENT:
758 if (!empty($row['causer-id']) && DI::pConfig()->get(local_user(), 'system', 'display_resharer')) {
759 $row['owner-id'] = $row['causer-id'];
760 $row['owner-link'] = $row['causer-link'];
761 $row['owner-avatar'] = $row['causer-avatar'];
762 $row['owner-name'] = $row['causer-name'];
765 if (($row['gravity'] == GRAVITY_PARENT) && !empty($row['causer-id'])) {
766 $row['reshared'] = DI::l10n()->t('%s reshared this.', '<a href="'. htmlentities(Contact::magicLinkById($row['causer-id'])) .'">' . htmlentities($name) . '</a>');
768 $row['direction'] = ['direction' => 3, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Reshared') : DI::l10n()->t('Reshared by %s', $name))];
770 case Item::PT_COMMENT:
771 $row['direction'] = ['direction' => 5, 'title' => DI::l10n()->t('%s is participating in this thread.', $row['author-name'])];
773 case Item::PT_STORED:
774 $row['direction'] = ['direction' => 8, 'title' => DI::l10n()->t('Stored')];
776 case Item::PT_GLOBAL:
777 $row['direction'] = ['direction' => 9, 'title' => DI::l10n()->t('Global')];
780 $row['direction'] = ['direction' => 10, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Relayed') : DI::l10n()->t('Relayed by %s.', $name))];
782 case Item::PT_FETCHED:
783 $row['direction'] = ['direction' => 2, 'title' => (empty($row['causer-id']) ? DI::l10n()->t('Fetched') : DI::l10n()->t('Fetched because of %s', $name))];
787 if ($row['gravity'] == GRAVITY_PARENT) {
788 $row['pinned'] = $pinned;
794 DBA::close($thread_items);
800 * Add comments to top level entries that had been fetched before
802 * The system will fetch the comments for the local user whenever possible.
803 * This behaviour is currently needed to allow commenting on Friendica posts.
805 * @param array $parents Parent items
807 * @param $block_authors
810 * @return array items with parents and comments
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
814 if (count($parents) > 1) {
815 $max_comments = DI::config()->get('system', 'max_comments', 100);
817 $max_comments = DI::config()->get('system', 'max_display_comments', 1000);
820 $params = ['order' => ['gravity', 'uid', 'commented' => true]];
822 if ($max_comments > 0) {
823 $params['limit'] = $max_comments;
828 foreach ($parents AS $parent) {
829 if (!empty($parent['thr-parent-id']) && !empty($parent['gravity']) && ($parent['gravity'] == GRAVITY_ACTIVITY)) {
830 $condition = ["`item`.`parent-uri-id` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
831 $parent['thr-parent-id'], $uid, Verb::getID(Activity::FOLLOW)];
832 if (!empty($parent['author-id'])) {
833 $activity = ['causer-id' => $parent['author-id']];
834 foreach (['commented', 'received', 'created'] as $orderfields) {
835 if (!empty($parent[$orderfields])) {
836 $activity[$orderfields] = $parent[$orderfields];
841 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) AND (`vid` != ? OR `vid` IS NULL)",
842 $parent['uri'], $uid, Verb::getID(Activity::FOLLOW)];
845 $items = conversation_fetch_items($parent, $items, $condition, $block_authors, $params, $activity);
848 foreach ($items as $index => $item) {
849 if ($item['uid'] == 0) {
850 $items[$index]['writable'] = in_array($item['network'], Protocol::FEDERATED);
854 $items = conv_sort($items, $order);
860 * Fetch conversation items
862 * @param array $parent Parent Item array
863 * @param array $items Item array
864 * @param array $condition SQL condition
865 * @param boolean $block_authors Don't show posts from contacts that are hidden (used on the community page)
866 * @param array $params SQL parameters
867 * @param array $activity Contact data of the resharer
870 function conversation_fetch_items(array $parent, array $items, array $condition, bool $block_authors, array $params, array $activity) {
871 if ($block_authors) {
872 $condition[0] .= " AND NOT `author`.`hidden`";
875 $thread_items = Item::selectForUser(local_user(), array_merge(Item::DISPLAY_FIELDLIST, ['pinned', 'contact-uid', 'gravity', 'post-type']), $condition, $params);
877 $comments = conversation_fetch_comments($thread_items, $parent['pinned'] ?? false, $activity);
879 if (count($comments) != 0) {
880 $items = array_merge($items, $comments);
885 function item_photo_menu($item) {
896 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self']) {
897 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
900 $author = ['uid' => 0, 'id' => $item['author-id'],
901 'network' => $item['author-network'], 'url' => $item['author-link']];
902 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
903 $sparkle = (strpos($profile_link, 'redir/') === 0);
906 $pcid = Contact::getIdForURL($item['author-link'], 0, false);
909 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
910 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
911 if (DBA::isResult($contact)) {
912 $cid = $contact['id'];
913 $network = $contact['network'];
914 $rel = $contact['rel'];
918 $status_link = $profile_link . '/status';
919 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
920 $profile_link = $profile_link . '/profile';
924 $contact_url = 'contact/' . $pcid;
925 $posts_link = $contact_url . '/posts';
926 $block_link = $contact_url . '/block';
927 $ignore_link = $contact_url . '/ignore';
930 if ($cid && !$item['self']) {
931 $contact_url = 'contact/' . $cid;
932 $poke_link = $contact_url . '/poke';
933 $posts_link = $contact_url . '/posts';
935 if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
936 $pm_url = 'message/new/' . $cid;
942 DI::l10n()->t('Follow Thread') => $sub_link,
943 DI::l10n()->t('View Status') => $status_link,
944 DI::l10n()->t('View Profile') => $profile_link,
945 DI::l10n()->t('View Photos') => $photos_link,
946 DI::l10n()->t('Network Posts') => $posts_link,
947 DI::l10n()->t('View Contact') => $contact_url,
948 DI::l10n()->t('Send PM') => $pm_url,
949 DI::l10n()->t('Block') => $block_link,
950 DI::l10n()->t('Ignore') => $ignore_link
953 if (!empty($item['language'])) {
954 $menu[DI::l10n()->t('Languages')] = 'javascript:alert(\'' . Item::getLanguageMessage($item) . '\');';
957 if ($network == Protocol::DFRN) {
958 $menu[DI::l10n()->t("Poke")] = $poke_link;
961 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
962 in_array($item['network'], Protocol::FEDERATED)) {
963 $menu[DI::l10n()->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
966 $menu = [DI::l10n()->t('View Profile') => $item['author-link']];
969 $args = ['item' => $item, 'menu' => $menu];
971 Hook::callAll('item_photo_menu', $args);
973 $menu = $args['menu'];
976 foreach ($menu as $k => $v) {
977 if (strpos($v, 'javascript:') === 0) {
979 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
981 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
988 * Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
990 * Increments the count of each matching activity and adds a link to the author as needed.
992 * @param array $activity
993 * @param array &$conv_responses (already created with builtin activity structure)
995 * @throws ImagickException
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
998 function builtin_activity_puller(array $activity, array &$conv_responses)
1000 foreach ($conv_responses as $mode => $v) {
1005 $verb = Activity::LIKE;
1008 $verb = Activity::DISLIKE;
1011 $verb = Activity::ATTEND;
1014 $verb = Activity::ATTENDNO;
1017 $verb = Activity::ATTENDMAYBE;
1020 $verb = Activity::ANNOUNCE;
1026 if (!empty($activity['verb']) && DI::activity()->match($activity['verb'], $verb) && ($activity['gravity'] != GRAVITY_PARENT)) {
1029 'id' => $activity['author-id'],
1030 'network' => $activity['author-network'],
1031 'url' => $activity['author-link']
1033 $url = Contact::magicLinkByContact($author);
1034 if (strpos($url, 'redir/') === 0) {
1035 $sparkle = ' class="sparkle" ';
1038 $link = '<a href="' . $url . '"' . $sparkle . '>' . htmlentities($activity['author-name']) . '</a>';
1040 if (empty($activity['thr-parent'])) {
1041 $activity['thr-parent'] = $activity['parent-uri'];
1044 // Skip when the causer of the parent is the same than the author of the announce
1045 if (($verb == Activity::ANNOUNCE) && Post::exists(['uri' => $activity['thr-parent'],
1046 'uid' => $activity['uid'], 'causer-id' => $activity['author-id'], 'gravity' => GRAVITY_PARENT])) {
1050 if (!isset($conv_responses[$mode][$activity['thr-parent']])) {
1051 $conv_responses[$mode][$activity['thr-parent']] = [
1055 } elseif (in_array($link, $conv_responses[$mode][$activity['thr-parent']]['links'])) {
1056 // only list each unique author once
1060 if (public_contact() == $activity['author-id']) {
1061 $conv_responses[$mode][$activity['thr-parent']]['self'] = 1;
1064 $conv_responses[$mode][$activity['thr-parent']]['links'][] = $link;
1066 // there can only be one activity verb per item so if we found anything, we can stop looking
1073 * Format the activity text for an item/photo/video
1075 * @param array $links = array of pre-linked names of actors
1076 * @param string $verb = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1077 * @param int $id = item id
1078 * @return string formatted text
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081 function format_activity(array $links, $verb, $id) {
1086 $total = count($links);
1088 $likers = $links[0];
1090 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1091 // list which show all likers
1094 $phrase = DI::l10n()->t('%s likes this.', $likers);
1097 $phrase = DI::l10n()->t('%s doesn\'t like this.', $likers);
1100 $phrase = DI::l10n()->t('%s attends.', $likers);
1103 $phrase = DI::l10n()->t('%s doesn\'t attend.', $likers);
1105 case 'attendmaybe' :
1106 $phrase = DI::l10n()->t('%s attends maybe.', $likers);
1109 $phrase = DI::l10n()->t('%s reshared this.', $likers);
1112 } elseif ($total > 1) {
1113 if ($total < MAX_LIKERS) {
1114 $likers = implode(', ', array_slice($links, 0, -1));
1115 $likers .= ' ' . DI::l10n()->t('and') . ' ' . $links[count($links)-1];
1117 $likers = implode(', ', array_slice($links, 0, MAX_LIKERS - 1));
1118 $likers .= ' ' . DI::l10n()->t('and %d other people', $total - MAX_LIKERS);
1121 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$verb}list-$id');\"";
1126 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> like this', $spanatts, $total);
1127 $explikers = DI::l10n()->t('%s like this.', $likers);
1130 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $total);
1131 $explikers = DI::l10n()->t('%s don\'t like this.', $likers);
1134 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend', $spanatts, $total);
1135 $explikers = DI::l10n()->t('%s attend.', $likers);
1138 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $total);
1139 $explikers = DI::l10n()->t('%s don\'t attend.', $likers);
1142 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $total);
1143 $explikers = DI::l10n()->t('%s attend maybe.', $likers);
1146 $phrase = DI::l10n()->t('<span %1$s>%2$d people</span> reshared this', $spanatts, $total);
1147 $explikers = DI::l10n()->t('%s reshared this.', $likers);
1151 $expanded .= "\t" . '<p class="wall-item-' . $verb . '-expanded" id="' . $verb . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</p>';
1154 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('voting_fakelink.tpl'), [
1155 '$phrase' => $phrase,
1164 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1168 $geotag = !empty($x['allow_location']) ? Renderer::replaceMacros(Renderer::getMarkupTemplate('jot_geotag.tpl'), []) : '';
1170 $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
1171 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
1172 '$newpost' => 'true',
1173 '$baseurl' => DI::baseUrl()->get(true),
1174 '$geotag' => $geotag,
1175 '$nickname' => $x['nickname'],
1176 '$ispublic' => DI::l10n()->t('Visible to <strong>everybody</strong>'),
1177 '$linkurl' => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
1178 '$term' => DI::l10n()->t('Tag term:'),
1179 '$fileas' => DI::l10n()->t('Save to Folder:'),
1180 '$whereareu' => DI::l10n()->t('Where are you right now?'),
1181 '$delitems' => DI::l10n()->t("Delete item\x28s\x29?"),
1182 '$is_mobile' => DI::mode()->isMobile(),
1186 Hook::callAll('jot_tool', $jotplugins);
1188 $tpl = Renderer::getMarkupTemplate("jot.tpl");
1190 $o .= Renderer::replaceMacros($tpl, [
1191 '$new_post' => DI::l10n()->t('New Post'),
1192 '$return_path' => DI::args()->getQueryString(),
1193 '$action' => 'item',
1194 '$share' => ($x['button'] ?? '') ?: DI::l10n()->t('Share'),
1195 '$loading' => DI::l10n()->t('Loading...'),
1196 '$upload' => DI::l10n()->t('Upload photo'),
1197 '$shortupload' => DI::l10n()->t('upload photo'),
1198 '$attach' => DI::l10n()->t('Attach file'),
1199 '$shortattach' => DI::l10n()->t('attach file'),
1200 '$edbold' => DI::l10n()->t('Bold'),
1201 '$editalic' => DI::l10n()->t('Italic'),
1202 '$eduline' => DI::l10n()->t('Underline'),
1203 '$edquote' => DI::l10n()->t('Quote'),
1204 '$edcode' => DI::l10n()->t('Code'),
1205 '$edimg' => DI::l10n()->t('Image'),
1206 '$edurl' => DI::l10n()->t('Link'),
1207 '$edattach' => DI::l10n()->t('Link or Media'),
1208 '$setloc' => DI::l10n()->t('Set your location'),
1209 '$shortsetloc' => DI::l10n()->t('set location'),
1210 '$noloc' => DI::l10n()->t('Clear browser location'),
1211 '$shortnoloc' => DI::l10n()->t('clear location'),
1212 '$title' => $x['title'] ?? '',
1213 '$placeholdertitle' => DI::l10n()->t('Set title'),
1214 '$category' => $x['category'] ?? '',
1215 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? DI::l10n()->t("Categories \x28comma-separated list\x29") : '',
1216 '$wait' => DI::l10n()->t('Please wait'),
1217 '$permset' => DI::l10n()->t('Permission settings'),
1218 '$shortpermset' => DI::l10n()->t('Permissions'),
1219 '$wall' => $notes_cid ? 0 : 1,
1220 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1221 '$content' => $x['content'] ?? '',
1222 '$post_id' => $x['post_id'] ?? '',
1223 '$baseurl' => DI::baseUrl()->get(true),
1224 '$defloc' => $x['default_location'],
1225 '$visitor' => $x['visitor'],
1226 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1227 '$public' => DI::l10n()->t('Public post'),
1228 '$lockstate' => $x['lockstate'],
1229 '$bang' => $x['bang'],
1230 '$profile_uid' => $x['profile_uid'],
1231 '$preview' => DI::l10n()->t('Preview'),
1232 '$jotplugins' => $jotplugins,
1233 '$notes_cid' => $notes_cid,
1234 '$sourceapp' => DI::l10n()->t($a->sourcename),
1235 '$cancel' => DI::l10n()->t('Cancel'),
1236 '$rand_num' => Crypto::randomDigits(12),
1238 // ACL permissions box
1239 '$acl' => $x['acl'],
1241 //jot nav tab (used in some themes)
1242 '$message' => DI::l10n()->t('Message'),
1243 '$browser' => DI::l10n()->t('Browser'),
1245 '$compose_link_title' => DI::l10n()->t('Open Compose page'),
1249 if ($popup == true) {
1250 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1257 * Plucks the children of the given parent from a given item list.
1259 * @param array $item_list
1260 * @param array $parent
1261 * @param bool $recursive
1264 function get_item_children(array &$item_list, array $parent, $recursive = true)
1267 foreach ($item_list as $i => $item) {
1268 if ($item['gravity'] != GRAVITY_PARENT) {
1270 // Fallback to parent-uri if thr-parent is not set
1271 $thr_parent = $item['thr-parent'];
1272 if ($thr_parent == '') {
1273 $thr_parent = $item['parent-uri'];
1276 if ($thr_parent == $parent['uri']) {
1277 $item['children'] = get_item_children($item_list, $item);
1278 $children[] = $item;
1279 unset($item_list[$i]);
1281 } elseif ($item['parent'] == $parent['id']) {
1282 $children[] = $item;
1283 unset($item_list[$i]);
1291 * Recursively sorts a tree-like item array
1293 * @param array $items
1296 function sort_item_children(array $items)
1299 usort($result, 'sort_thr_received_rev');
1300 foreach ($result as $k => $i) {
1301 if (isset($result[$k]['children'])) {
1302 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1309 * Recursively add all children items at the top level of a list
1311 * @param array $children List of items to append
1312 * @param array $item_list
1314 function add_children_to_list(array $children, array &$item_list)
1316 foreach ($children as $child) {
1317 $item_list[] = $child;
1318 if (isset($child['children'])) {
1319 add_children_to_list($child['children'], $item_list);
1325 * Selectively flattens a tree-like item structure to prevent threading stairs
1327 * This recursive function takes the item tree structure created by conv_sort() and
1328 * flatten the extraneous depth levels when people reply sequentially, removing the
1329 * stairs effect in threaded conversations limiting the available content width.
1331 * The basic principle is the following: if a post item has only one reply and is
1332 * the last reply of its parent, then the reply is moved to the parent.
1334 * This process is rendered somewhat more complicated because items can be either
1335 * replies or likes, and these don't factor at all in the reply count/last reply.
1337 * @param array $parent A tree-like array of items
1340 function smart_flatten_conversation(array $parent)
1342 if (!isset($parent['children']) || count($parent['children']) == 0) {
1346 // We use a for loop to ensure we process the newly-moved items
1347 for ($i = 0; $i < count($parent['children']); $i++) {
1348 $child = $parent['children'][$i];
1350 if (isset($child['children']) && count($child['children'])) {
1351 // This helps counting only the regular posts
1352 $count_post_closure = function($var) {
1353 return $var['verb'] === Activity::POST;
1356 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1358 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1360 // If there's only one child's children post and this is the last child post
1361 if ($child_post_count == 1 && $remaining_post_count == 1) {
1363 // Searches the post item in the children
1365 while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) {
1369 $moved_item = $child['children'][$j];
1370 unset($parent['children'][$i]['children'][$j]);
1371 $parent['children'][] = $moved_item;
1373 $parent['children'][$i] = smart_flatten_conversation($child);
1383 * Expands a flat list of items into corresponding tree-like conversation structures.
1385 * sort the top-level posts either on "received" or "commented", and finally
1386 * append all the items at the top level (???)
1388 * @param array $item_list A list of items belonging to one or more conversations
1389 * @param string $order Either on "received" or "commented"
1391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1393 function conv_sort(array $item_list, $order)
1397 if (!(is_array($item_list) && count($item_list))) {
1401 $blocklist = conv_get_blocklist();
1405 // Dedupes the item list on the uri to prevent infinite loops
1406 foreach ($item_list as $item) {
1407 if (in_array($item['author-id'], $blocklist)) {
1411 $item_array[$item['uri']] = $item;
1414 // Extract the top level items
1415 foreach ($item_array as $item) {
1416 if ($item['gravity'] == GRAVITY_PARENT) {
1421 if (stristr($order, 'pinned_received')) {
1422 usort($parents, 'sort_thr_pinned_received');
1423 } elseif (stristr($order, 'received')) {
1424 usort($parents, 'sort_thr_received');
1425 } elseif (stristr($order, 'commented')) {
1426 usort($parents, 'sort_thr_commented');
1430 * Plucks children from the item_array, second pass collects eventual orphan
1431 * items and add them as children of their top-level post.
1433 foreach ($parents as $i => $parent) {
1434 $parents[$i]['children'] =
1435 array_merge(get_item_children($item_array, $parent, true),
1436 get_item_children($item_array, $parent, false));
1439 foreach ($parents as $i => $parent) {
1440 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1443 if (!DI::pConfig()->get(local_user(), 'system', 'no_smart_threading', 0)) {
1444 foreach ($parents as $i => $parent) {
1445 $parents[$i] = smart_flatten_conversation($parent);
1449 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1450 /// However, this apparently ensures responses (likes, attendance) display (?!)
1451 foreach ($parents as $parent) {
1452 if (count($parent['children'])) {
1453 add_children_to_list($parent['children'], $parents);
1461 * usort() callback to sort item arrays by pinned and the received key
1467 function sort_thr_pinned_received(array $a, array $b)
1469 if ($b['pinned'] && !$a['pinned']) {
1471 } elseif (!$b['pinned'] && $a['pinned']) {
1475 return strcmp($b['received'], $a['received']);
1479 * usort() callback to sort item arrays by the received key
1485 function sort_thr_received(array $a, array $b)
1487 return strcmp($b['received'], $a['received']);
1491 * usort() callback to reverse sort item arrays by the received key
1497 function sort_thr_received_rev(array $a, array $b)
1499 return strcmp($a['received'], $b['received']);
1503 * usort() callback to sort item arrays by the commented key
1509 function sort_thr_commented(array $a, array $b)
1511 return strcmp($b['commented'], $a['commented']);