3 * @file include/conversation.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Pager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Item;
21 use Friendica\Model\Profile;
22 use Friendica\Model\Term;
23 use Friendica\Object\Post;
24 use Friendica\Object\Thread;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Proxy as ProxyUtils;
27 use Friendica\Util\Temporal;
28 use Friendica\Util\XML;
30 function item_extract_images($body) {
37 $img_start = strpos($orig_body, '[img');
38 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
39 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
40 while (($img_st_close !== false) && ($img_end !== false)) {
42 $img_st_close++; // make it point to AFTER the closing bracket
43 $img_end += $img_start;
45 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
46 // This is an embedded image
48 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
49 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
53 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
56 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
58 if ($orig_body === false) {
59 // in case the body ends on a closing image tag
63 $img_start = strpos($orig_body, '[img');
64 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
65 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
68 $new_body = $new_body . $orig_body;
70 return ['body' => $new_body, 'images' => $saved_image];
73 function item_redir_and_replace_images($body, $images, $cid) {
79 $pos = BBCode::getTagPosition($origbody, 'url', 0);
80 while ($pos !== false && $cnt < 1000) {
82 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
83 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
84 . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
86 $newbody .= substr($origbody, 0, $pos['start']['open']);
87 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
88 $origbody = substr($origbody, $pos['end']['close']);
89 if ($origbody === false) {
93 $subject = preg_replace($search, $replace, $subject);
97 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
98 $pos = BBCode::getTagPosition($origbody, 'url', 0);
100 $newbody .= $origbody;
103 foreach ($images as $image) {
105 * We're depending on the property of 'foreach' (specified on the PHP website) that
106 * it loops over the array starting from the first element and going sequentially
107 * to the last element.
109 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
116 * Render actions localized
118 function localize_item(&$item)
120 $extracted = item_extract_images($item['body']);
121 if ($extracted['images']) {
122 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
126 heluecht 2018-06-19: from my point of view this whole code part is useless.
127 It just renders the body message of technical posts (Like, dislike, ...).
128 But: The body isn't visible at all. So we do this stuff just because we can.
129 Even if these messages were visible, this would only mean that something went wrong.
130 During the further steps of the database restructuring I would like to address this issue.
133 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
134 if (activity_match($item['verb'], ACTIVITY_LIKE)
135 || activity_match($item['verb'], ACTIVITY_DISLIKE)
136 || activity_match($item['verb'], ACTIVITY_ATTEND)
137 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
138 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
140 $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink'];
141 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
142 if (!DBA::isResult($obj)) {
146 $author = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
147 $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
149 switch ($obj['verb']) {
151 switch ($obj['object-type']) {
152 case ACTIVITY_OBJ_EVENT:
153 $post_type = L10n::t('event');
156 $post_type = L10n::t('status');
160 if ($obj['resource-id']) {
161 $post_type = L10n::t('photo');
163 preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
164 $rr['plink'] = $m[1];
166 $post_type = L10n::t('status');
170 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
172 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
173 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
174 } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
175 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
176 } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
177 $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
178 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
179 $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
180 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
181 $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
184 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
187 if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
189 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
191 $Aname = $item['author-name'];
192 $Alink = $item['author-link'];
194 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
196 $obj = XML::parseString($xmlhead.$item['object']);
197 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
199 $Bname = $obj->title;
202 foreach ($links->link as $l) {
203 $atts = $l->attributes();
204 switch ($atts['rel']) {
205 case "alternate": $Blink = $atts['href'];
206 case "photo": $Bphoto = $atts['href'];
210 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
211 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
213 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
216 $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
219 if (stristr($item['verb'], ACTIVITY_POKE)) {
220 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
224 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
228 $Aname = $item['author-name'];
229 $Alink = $item['author-link'];
231 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
233 $obj = XML::parseString($xmlhead.$item['object']);
235 $Bname = $obj->title;
239 foreach ($obj->link as $l) {
240 $atts = $l->attributes();
241 switch ($atts['rel']) {
242 case "alternate": $Blink = $atts['href'];
243 case "photo": $Bphoto = $atts['href'];
247 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
248 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
250 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
254 * we can't have a translation string with three positions but no distinguishable text
255 * So here is the translate string.
257 $txt = L10n::t('%1$s poked %2$s');
259 // now translate the verb
260 $poked_t = trim(sprintf($txt, "", ""));
261 $txt = str_replace($poked_t, L10n::t($verb), $txt);
263 // then do the sprintf on the translation string
265 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
269 if (activity_match($item['verb'], ACTIVITY_TAG)) {
270 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
271 'verb', 'object-type', 'resource-id', 'body', 'plink'];
272 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
273 if (!DBA::isResult($obj)) {
277 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
278 'network' => $item['author-network'], 'url' => $item['author-link']];
279 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
281 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
282 'network' => $obj['author-network'], 'url' => $obj['author-link']];
283 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
285 switch ($obj['verb']) {
287 switch ($obj['object-type']) {
288 case ACTIVITY_OBJ_EVENT:
289 $post_type = L10n::t('event');
292 $post_type = L10n::t('status');
296 if ($obj['resource-id']) {
297 $post_type = L10n::t('photo');
298 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
299 $rr['plink'] = $m[1];
301 $post_type = L10n::t('status');
303 // Let's break everthing ... ;-)
306 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
308 $parsedobj = XML::parseString($xmlhead.$item['object']);
310 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
311 $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
314 if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
315 if ($item['object-type'] == "") {
319 $Aname = $item['author-name'];
320 $Alink = $item['author-link'];
322 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
324 $obj = XML::parseString($xmlhead.$item['object']);
325 if (strlen($obj->id)) {
326 $fields = ['author-link', 'author-name', 'plink'];
327 $target = Item::selectFirst($fields, ['uri' => $obj->id, 'uid' => $item['uid']]);
328 if (DBA::isResult($target) && $target['plink']) {
329 $Bname = $target['author-name'];
330 $Blink = $target['author-link'];
331 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
332 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
333 $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
334 $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
339 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
340 foreach ($matches as $mtch) {
341 if (!strpos($mtch[1], 'zrl=')) {
342 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
347 // add zrl's to public images
348 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
349 if (preg_match($photo_pattern, $item['body'])) {
350 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
351 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
354 // add sparkle links to appropriate permalinks
355 $author = ['uid' => 0, 'id' => $item['author-id'],
356 'network' => $item['author-network'], 'url' => $item['author-link']];
358 // Only create a redirection to a magic link when logged in
359 if (!empty($item['plink']) && (local_user() || remote_user())) {
360 $item['plink'] = Contact::magicLinkbyContact($author, $item['plink']);
365 * Count the total of comments on this item and its desendants
366 * @TODO proper type-hint + doc-tag
368 function count_descendants($item) {
369 $total = count($item['children']);
372 foreach ($item['children'] as $child) {
373 if (!visible_activity($child)) {
376 $total += count_descendants($child);
383 function visible_activity($item) {
386 * likes (etc.) can apply to other things besides posts. Check if they are post children,
387 * in which case we handle them specially
389 $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
390 foreach ($hidden_activities as $act) {
391 if (activity_match($item['verb'], $act)) {
396 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
397 if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
404 function conv_get_blocklist()
410 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
411 if (empty($str_blocked)) {
417 foreach (explode(',', $str_blocked) as $entry) {
418 // The 4th parameter guarantees that there always will be a public contact entry
419 $cid = Contact::getIdForURL(trim($entry), 0, true, ['url' => trim($entry)]);
429 * "Render" a conversation or list of items for HTML display.
430 * There are two major forms of display:
431 * - Sequential or unthreaded ("New Item View" or search results)
432 * - conversation view
433 * The $mode parameter decides between the various renderings and also
434 * figures out how to determine page owner and other contextual items
435 * that are based on unique features of the calling module.
438 function conversation(App $a, array $items, Pager $pager, $mode, $update, $preview = false, $order = 'commented', $uid = 0)
440 $ssl_state = (local_user() ? true : false);
443 $live_update_div = '';
445 $blocklist = conv_get_blocklist();
447 $previewing = (($preview) ? ' preview ' : '');
449 if ($mode === 'network') {
450 $items = conversation_add_children($items, false, $order, $uid);
451 $profile_owner = local_user();
454 * The special div is needed for liveUpdate to kick in for this page.
455 * We only launch liveUpdate if you aren't filtering in some incompatible
456 * way and also you aren't writing a comment (discovered in javascript).
458 $live_update_div = '<div id="live-network"></div>' . "\r\n"
459 . "<script> var profile_uid = " . $_SESSION['uid']
460 . "; var netargs = '" . substr($a->cmd, 8)
462 . ((x($_GET, 'cid')) ? '&cid=' . $_GET['cid'] : '')
463 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
464 . ((x($_GET, 'star')) ? '&star=' . $_GET['star'] : '')
465 . ((x($_GET, 'order')) ? '&order=' . $_GET['order'] : '')
466 . ((x($_GET, 'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
467 . ((x($_GET, 'liked')) ? '&liked=' . $_GET['liked'] : '')
468 . ((x($_GET, 'conv')) ? '&conv=' . $_GET['conv'] : '')
469 . ((x($_GET, 'nets')) ? '&nets=' . $_GET['nets'] : '')
470 . ((x($_GET, 'cmin')) ? '&cmin=' . $_GET['cmin'] : '')
471 . ((x($_GET, 'cmax')) ? '&cmax=' . $_GET['cmax'] : '')
472 . ((x($_GET, 'file')) ? '&file=' . $_GET['file'] : '')
474 . "'; var profile_page = " . $pager->getPage() . "; </script>\r\n";
476 } elseif ($mode === 'profile') {
477 $items = conversation_add_children($items, false, $order, $uid);
478 $profile_owner = $a->profile['profile_uid'];
482 if (x($_GET, 'tab')) {
483 $tab = notags(trim($_GET['tab']));
485 if ($tab === 'posts') {
487 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
488 * because browser prefetching might change it on us. We have to deliver it with the page.
491 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
492 . "<script> var profile_uid = " . $a->profile['profile_uid']
493 . "; var netargs = '?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
496 } elseif ($mode === 'notes') {
497 $items = conversation_add_children($items, false, $order, $uid);
498 $profile_owner = local_user();
501 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
502 . "<script> var profile_uid = " . local_user()
503 . "; var netargs = '/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
505 } elseif ($mode === 'display') {
506 $items = conversation_add_children($items, false, $order, $uid);
507 $profile_owner = $a->profile['uid'];
510 $live_update_div = '<div id="live-display"></div>' . "\r\n"
511 . "<script> var profile_uid = " . defaults($_SESSION, 'uid', 0) . ";"
512 . " var profile_page = 1; </script>";
514 } elseif ($mode === 'community') {
515 $items = conversation_add_children($items, true, $order, $uid);
519 $live_update_div = '<div id="live-community"></div>' . "\r\n"
520 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
521 ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
523 } elseif ($mode === 'contacts') {
524 $items = conversation_add_children($items, true, $order, $uid);
528 $live_update_div = '<div id="live-contacts"></div>' . "\r\n"
529 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 9)
530 ."/?f='; var profile_page = " . $pager->getPage() . "; </script>\r\n";
532 } elseif ($mode === 'search') {
533 $live_update_div = '<div id="live-search"></div>' . "\r\n";
536 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
539 $_SESSION['return_path'] = $a->query_string;
542 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
543 Addon::callHooks('conversation_start',$cb);
545 $items = $cb['items'];
548 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
549 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
552 // array with html for each thread (parent+comments)
556 $page_template = get_markup_template("conversation.tpl");
558 if (!empty($items)) {
559 if (in_array($mode, ['community', 'contacts'])) {
562 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
569 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
572 * "New Item View" on network page or search page results
573 * - just loop through the items and format them minimally for display
576 $tpl = 'search_item.tpl';
578 foreach ($items as $item) {
580 if (!visible_activity($item)) {
584 if (in_array($item['author-id'], $blocklist)) {
594 // prevent private email from leaking.
595 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
599 $profile_name = $item['author-name'];
600 if (!empty($item['author-link']) && empty($item['author-name'])) {
601 $profile_name = $item['author-link'];
604 $tags = Term::populateTagsFromItem($item);
606 $author = ['uid' => 0, 'id' => $item['author-id'],
607 'network' => $item['author-network'], 'url' => $item['author-link']];
608 $profile_link = Contact::magicLinkbyContact($author);
610 if (strpos($profile_link, 'redir/') === 0) {
611 $sparkle = ' sparkle';
614 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
615 Addon::callHooks('render_location',$locate);
617 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
619 localize_item($item);
620 if ($mode === 'network-new') {
627 'dropping' => $dropping,
628 'pagedrop' => $page_dropping,
629 'select' => L10n::t('Select'),
630 'delete' => L10n::t('Delete'),
634 $isstarred = "unstarred";
637 $likebuttons = false;
639 $body = prepare_body($item, true, $preview);
641 list($categories, $folders) = get_cats_and_terms($item);
643 $profile_name_e = $profile_name;
645 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
646 $title_e = ucfirst($item['content-warning']);
648 $title_e = $item['title'];
652 $tags_e = $tags['tags'];
653 $hashtags_e = $tags['hashtags'];
654 $mentions_e = $tags['mentions'];
655 $location_e = $location;
656 $owner_name_e = $owner_name;
660 'id' => ($preview ? 'P0' : $item['id']),
661 'guid' => ($preview ? 'Q0' : $item['guid']),
662 'network' => $item['network'],
663 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
664 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
665 'profile_url' => $profile_link,
666 'item_photo_menu' => item_photo_menu($item),
667 'name' => $profile_name_e,
668 'sparkle' => $sparkle,
670 'thumb' => System::removedBaseUrl(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
674 'hashtags' => $hashtags_e,
675 'mentions' => $mentions_e,
676 'txt_cats' => L10n::t('Categories:'),
677 'txt_folders' => L10n::t('Filed under:'),
678 'has_cats' => ((count($categories)) ? 'true' : ''),
679 'has_folders' => ((count($folders)) ? 'true' : ''),
680 'categories' => $categories,
681 'folders' => $folders,
682 'text' => strip_tags($body_e),
683 'localtime' => DateTimeFormat::local($item['created'], 'r'),
684 'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
685 'location' => $location_e,
687 'owner_name' => $owner_name_e,
688 'owner_url' => $owner_url,
689 'owner_photo' => System::removedBaseUrl(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
690 'plink' => get_plink($item),
692 'isstarred' => $isstarred,
695 'vote' => $likebuttons,
699 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
700 'previewing' => $previewing,
701 'wait' => L10n::t('Please wait'),
705 $arr = ['item' => $item, 'output' => $tmp_item];
706 Addon::callHooks('display_item', $arr);
708 $threads[$threadsid]['id'] = $item['id'];
709 $threads[$threadsid]['network'] = $item['network'];
710 $threads[$threadsid]['items'] = [$arr['output']];
715 $page_template = get_markup_template("threaded_conversation.tpl");
717 $conv = new Thread($mode, $preview, $writable);
720 * get all the topmost parents
721 * this shouldn't be needed, as we should have only them in our array
722 * But for now, this array respects the old style, just in case
724 foreach ($items as $item) {
725 if (in_array($item['author-id'], $blocklist)) {
729 // Can we put this after the visibility check?
730 builtin_activity_puller($item, $conv_responses);
732 // Only add what is visible
733 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
737 if (!visible_activity($item)) {
741 /// @todo Check if this call is needed or not
742 $arr = ['item' => $item];
743 Addon::callHooks('display_item', $arr);
745 $item['pagedrop'] = $page_dropping;
747 if ($item['id'] == $item['parent']) {
748 $item_object = new Post($item);
749 $conv->addParent($item_object);
753 $threads = $conv->getTemplateData($conv_responses);
755 Logger::log('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
761 $o = replace_macros($page_template, [
762 '$baseurl' => System::baseUrl($ssl_state),
763 '$return_path' => $a->query_string,
764 '$live_update' => $live_update_div,
765 '$remove' => L10n::t('remove'),
768 '$threads' => $threads,
769 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? L10n::t('Delete Selected Items') : False),
776 * @brief Add comments to top level entries that had been fetched before
778 * The system will fetch the comments for the local user whenever possible.
779 * This behaviour is currently needed to allow commenting on Friendica posts.
781 * @param array $parents Parent items
783 * @return array items with parents and comments
785 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
786 $max_comments = Config::get('system', 'max_comments', 100);
788 $params = ['order' => ['uid', 'commented' => true]];
790 if ($max_comments > 0) {
791 $params['limit'] = $max_comments;
796 foreach ($parents AS $parent) {
797 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
798 $parent['uri'], local_user()];
799 if ($block_authors) {
800 $condition[0] .= "AND NOT `author`.`hidden`";
802 $thread_items = Item::selectForUser(local_user(), [], $condition, $params);
804 $comments = Item::inArray($thread_items);
806 if (count($comments) != 0) {
807 $items = array_merge($items, $comments);
811 foreach ($items as $index => $item) {
812 if ($item['uid'] == 0) {
813 $items[$index]['writable'] = in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
817 $items = conv_sort($items, $order);
822 function item_photo_menu($item) {
831 if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
832 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
835 $author = ['uid' => 0, 'id' => $item['author-id'],
836 'network' => $item['author-network'], 'url' => $item['author-link']];
837 $profile_link = Contact::magicLinkbyContact($author);
838 $sparkle = (strpos($profile_link, 'redir/') === 0);
843 $condition = ['uid' => local_user(), 'nurl' => normalise_link($item['author-link'])];
844 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
845 if (DBA::isResult($contact)) {
846 $cid = $contact['id'];
847 $network = $contact['network'];
848 $rel = $contact['rel'];
852 $status_link = $profile_link . '?url=status';
853 $photos_link = $profile_link . '?url=photos';
854 $profile_link = $profile_link . '?url=profile';
857 if ($cid && !$item['self']) {
858 $poke_link = 'poke/?f=&c=' . $cid;
859 $contact_url = 'contact/' . $cid;
860 $posts_link = 'contact/' . $cid . '/posts';
862 if (in_array($network, [Protocol::DFRN, Protocol::DIASPORA])) {
863 $pm_url = 'message/new/' . $cid;
869 L10n::t('Follow Thread') => $sub_link,
870 L10n::t('View Status') => $status_link,
871 L10n::t('View Profile') => $profile_link,
872 L10n::t('View Photos') => $photos_link,
873 L10n::t('Network Posts') => $posts_link,
874 L10n::t('View Contact') => $contact_url,
875 L10n::t('Send PM') => $pm_url
878 if ($network == Protocol::DFRN) {
879 $menu[L10n::t("Poke")] = $poke_link;
882 if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
883 in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
884 $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
887 $menu = [L10n::t('View Profile') => $item['author-link']];
890 $args = ['item' => $item, 'menu' => $menu];
892 Addon::callHooks('item_photo_menu', $args);
894 $menu = $args['menu'];
897 foreach ($menu as $k => $v) {
898 if (strpos($v, 'javascript:') === 0) {
900 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
902 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
909 * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
910 * Increments the count of each matching activity and adds a link to the author as needed.
913 * @param array &$conv_responses (already created with builtin activity structure)
916 function builtin_activity_puller($item, &$conv_responses) {
917 foreach ($conv_responses as $mode => $v) {
923 $verb = ACTIVITY_LIKE;
926 $verb = ACTIVITY_DISLIKE;
929 $verb = ACTIVITY_ATTEND;
932 $verb = ACTIVITY_ATTENDNO;
935 $verb = ACTIVITY_ATTENDMAYBE;
941 if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
942 $author = ['uid' => 0, 'id' => $item['author-id'],
943 'network' => $item['author-network'], 'url' => $item['author-link']];
944 $url = Contact::magicLinkbyContact($author);
945 if (strpos($url, 'redir/') === 0) {
946 $sparkle = ' class="sparkle" ';
949 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
951 if (!x($item, 'thr-parent')) {
952 $item['thr-parent'] = $item['parent-uri'];
955 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
956 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
957 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
960 // only list each unique author once
961 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
965 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
966 $conv_responses[$mode][$item['thr-parent']] = 1;
968 $conv_responses[$mode][$item['thr-parent']] ++;
971 if (public_contact() == $item['author-id']) {
972 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
975 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
977 // there can only be one activity verb per item so if we found anything, we can stop looking
984 * Format the vote text for a profile item
985 * @param int $cnt = number of people who vote the item
986 * @param array $arr = array of pre-linked names of likers/dislikers
987 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
988 * @param int $id = item id
989 * @return string formatted text
991 function format_like($cnt, array $arr, $type, $id) {
998 // Phrase if there is only one liker. In other cases it will be uses for the expanded
999 // list which show all likers
1002 $phrase = L10n::t('%s likes this.', $likers);
1005 $phrase = L10n::t('%s doesn\'t like this.', $likers);
1008 $phrase = L10n::t('%s attends.', $likers);
1011 $phrase = L10n::t('%s doesn\'t attend.', $likers);
1013 case 'attendmaybe' :
1014 $phrase = L10n::t('%s attends maybe.', $likers);
1020 $total = count($arr);
1021 if ($total >= MAX_LIKERS) {
1022 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1024 if ($total < MAX_LIKERS) {
1025 $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1026 $arr2 = array_slice($arr, 0, -1);
1027 $str = implode(', ', $arr2) . ' ' . $last;
1029 if ($total >= MAX_LIKERS) {
1030 $str = implode(', ', $arr);
1031 $str .= L10n::t('and %d other people', $total - MAX_LIKERS);
1036 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1040 $phrase = L10n::t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1041 $explikers = L10n::t('%s like this.', $likers);
1044 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1045 $explikers = L10n::t('%s don\'t like this.', $likers);
1048 $phrase = L10n::t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1049 $explikers = L10n::t('%s attend.', $likers);
1052 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1053 $explikers = L10n::t('%s don\'t attend.', $likers);
1056 $phrase = L10n::t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1057 $explikers = L10n::t('%s attend maybe.', $likers);
1061 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1065 $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), [
1066 '$phrase' => $phrase,
1075 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1079 $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), []) : '';
1081 $tpl = get_markup_template('jot-header.tpl');
1082 $a->page['htmlhead'] .= replace_macros($tpl, [
1083 '$newpost' => 'true',
1084 '$baseurl' => System::baseUrl(true),
1085 '$geotag' => $geotag,
1086 '$nickname' => $x['nickname'],
1087 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1088 '$linkurl' => L10n::t('Please enter a image/video/audio/webpage URL:'),
1089 '$term' => L10n::t('Tag term:'),
1090 '$fileas' => L10n::t('Save to Folder:'),
1091 '$whereareu' => L10n::t('Where are you right now?'),
1092 '$delitems' => L10n::t("Delete item\x28s\x29?")
1096 Addon::callHooks('jot_tool', $jotplugins);
1098 // Private/public post links for the non-JS ACL form
1100 if (x($_REQUEST, 'public')) {
1104 $query_str = $a->query_string;
1105 if (strpos($query_str, 'public=1') !== false) {
1106 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1110 * I think $a->query_string may never have ? in it, but I could be wrong
1111 * It looks like it's from the index.php?q=[etc] rewrite that the web
1112 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1114 if (strpos($query_str, '?') === false) {
1115 $public_post_link = '?public=1';
1117 $public_post_link = '&public=1';
1120 // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1121 $tpl = get_markup_template("jot.tpl");
1123 $o .= replace_macros($tpl,[
1124 '$new_post' => L10n::t('New Post'),
1125 '$return_path' => $query_str,
1126 '$action' => 'item',
1127 '$share' => defaults($x, 'button', L10n::t('Share')),
1128 '$upload' => L10n::t('Upload photo'),
1129 '$shortupload' => L10n::t('upload photo'),
1130 '$attach' => L10n::t('Attach file'),
1131 '$shortattach' => L10n::t('attach file'),
1132 '$edbold' => L10n::t('Bold'),
1133 '$editalic' => L10n::t('Italic'),
1134 '$eduline' => L10n::t('Underline'),
1135 '$edquote' => L10n::t('Quote'),
1136 '$edcode' => L10n::t('Code'),
1137 '$edimg' => L10n::t('Image'),
1138 '$edurl' => L10n::t('Link'),
1139 '$edattach' => L10n::t('Link or Media'),
1140 '$setloc' => L10n::t('Set your location'),
1141 '$shortsetloc' => L10n::t('set location'),
1142 '$noloc' => L10n::t('Clear browser location'),
1143 '$shortnoloc' => L10n::t('clear location'),
1144 '$title' => defaults($x, 'title', ''),
1145 '$placeholdertitle' => L10n::t('Set title'),
1146 '$category' => defaults($x, 'category', ''),
1147 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1148 '$wait' => L10n::t('Please wait'),
1149 '$permset' => L10n::t('Permission settings'),
1150 '$shortpermset' => L10n::t('permissions'),
1151 '$wall' => $notes_cid ? 0 : 1,
1152 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1153 '$content' => defaults($x, 'content', ''),
1154 '$post_id' => defaults($x, 'post_id', ''),
1155 '$baseurl' => System::baseUrl(true),
1156 '$defloc' => $x['default_location'],
1157 '$visitor' => $x['visitor'],
1158 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1159 '$public' => L10n::t('Public post'),
1160 '$lockstate' => $x['lockstate'],
1161 '$bang' => $x['bang'],
1162 '$profile_uid' => $x['profile_uid'],
1163 '$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? L10n::t('Preview') : '',
1164 '$jotplugins' => $jotplugins,
1165 '$notes_cid' => $notes_cid,
1166 '$sourceapp' => L10n::t($a->sourcename),
1167 '$cancel' => L10n::t('Cancel'),
1168 '$rand_num' => random_digits(12),
1170 // ACL permissions box
1171 '$acl' => $x['acl'],
1172 '$group_perms' => L10n::t('Post to Groups'),
1173 '$contact_perms' => L10n::t('Post to Contacts'),
1174 '$private' => L10n::t('Private post'),
1175 '$is_private' => $private_post,
1176 '$public_link' => $public_post_link,
1178 //jot nav tab (used in some themes)
1179 '$message' => L10n::t('Message'),
1180 '$browser' => L10n::t('Browser'),
1184 if ($popup == true) {
1185 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1192 * Plucks the children of the given parent from a given item list.
1194 * @brief Plucks all the children in the given item list of the given parent
1196 * @param array $item_list
1197 * @param array $parent
1198 * @param bool $recursive
1201 function get_item_children(array &$item_list, array $parent, $recursive = true)
1204 foreach ($item_list as $i => $item) {
1205 if ($item['id'] != $item['parent']) {
1207 // Fallback to parent-uri if thr-parent is not set
1208 $thr_parent = $item['thr-parent'];
1209 if ($thr_parent == '') {
1210 $thr_parent = $item['parent-uri'];
1213 if ($thr_parent == $parent['uri']) {
1214 $item['children'] = get_item_children($item_list, $item);
1215 $children[] = $item;
1216 unset($item_list[$i]);
1218 } elseif ($item['parent'] == $parent['id']) {
1219 $children[] = $item;
1220 unset($item_list[$i]);
1228 * @brief Recursively sorts a tree-like item array
1230 * @param array $items
1233 function sort_item_children(array $items)
1236 usort($result, 'sort_thr_created_rev');
1237 foreach ($result as $k => $i) {
1238 if (isset($result[$k]['children'])) {
1239 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1246 * @brief Recursively add all children items at the top level of a list
1248 * @param array $children List of items to append
1249 * @param array $item_list
1251 function add_children_to_list(array $children, array &$item_list)
1253 foreach ($children as $child) {
1254 $item_list[] = $child;
1255 if (isset($child['children'])) {
1256 add_children_to_list($child['children'], $item_list);
1262 * This recursive function takes the item tree structure created by conv_sort() and
1263 * flatten the extraneous depth levels when people reply sequentially, removing the
1264 * stairs effect in threaded conversations limiting the available content width.
1266 * The basic principle is the following: if a post item has only one reply and is
1267 * the last reply of its parent, then the reply is moved to the parent.
1269 * This process is rendered somewhat more complicated because items can be either
1270 * replies or likes, and these don't factor at all in the reply count/last reply.
1272 * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1274 * @param array $parent A tree-like array of items
1277 function smart_flatten_conversation(array $parent)
1279 if (!isset($parent['children']) || count($parent['children']) == 0) {
1283 // We use a for loop to ensure we process the newly-moved items
1284 for ($i = 0; $i < count($parent['children']); $i++) {
1285 $child = $parent['children'][$i];
1287 if (isset($child['children']) && count($child['children'])) {
1288 // This helps counting only the regular posts
1289 $count_post_closure = function($var) {
1290 return $var['verb'] === ACTIVITY_POST;
1293 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1295 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1297 // If there's only one child's children post and this is the last child post
1298 if ($child_post_count == 1 && $remaining_post_count == 1) {
1300 // Searches the post item in the children
1302 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1306 $moved_item = $child['children'][$j];
1307 unset($parent['children'][$i]['children'][$j]);
1308 $parent['children'][] = $moved_item;
1310 $parent['children'][$i] = smart_flatten_conversation($child);
1320 * Expands a flat list of items into corresponding tree-like conversation structures,
1321 * sort the top-level posts either on "created" or "commented", and finally
1322 * append all the items at the top level (???)
1324 * @brief Expands a flat item list into a conversation array for display
1326 * @param array $item_list A list of items belonging to one or more conversations
1327 * @param string $order Either on "created" or "commented"
1330 function conv_sort(array $item_list, $order)
1334 if (!(is_array($item_list) && count($item_list))) {
1338 $blocklist = conv_get_blocklist();
1342 // Dedupes the item list on the uri to prevent infinite loops
1343 foreach ($item_list as $item) {
1344 if (in_array($item['author-id'], $blocklist)) {
1348 $item_array[$item['uri']] = $item;
1351 // Extract the top level items
1352 foreach ($item_array as $item) {
1353 if ($item['id'] == $item['parent']) {
1358 if (stristr($order, 'created')) {
1359 usort($parents, 'sort_thr_created');
1360 } elseif (stristr($order, 'commented')) {
1361 usort($parents, 'sort_thr_commented');
1365 * Plucks children from the item_array, second pass collects eventual orphan
1366 * items and add them as children of their top-level post.
1368 foreach ($parents as $i => $parent) {
1369 $parents[$i]['children'] =
1370 array_merge(get_item_children($item_array, $parent, true),
1371 get_item_children($item_array, $parent, false));
1374 foreach ($parents as $i => $parent) {
1375 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1378 if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1379 foreach ($parents as $i => $parent) {
1380 $parents[$i] = smart_flatten_conversation($parent);
1384 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1385 /// However, this apparently ensures responses (likes, attendance) display (?!)
1386 foreach ($parents as $parent) {
1387 if (count($parent['children'])) {
1388 add_children_to_list($parent['children'], $parents);
1396 * @brief usort() callback to sort item arrays by the created key
1402 function sort_thr_created(array $a, array $b)
1404 return strcmp($b['created'], $a['created']);
1408 * @brief usort() callback to reverse sort item arrays by the created key
1414 function sort_thr_created_rev(array $a, array $b)
1416 return strcmp($a['created'], $b['created']);
1420 * @brief usort() callback to sort item arrays by the commented key
1426 function sort_thr_commented(array $a, array $b)
1428 return strcmp($b['commented'], $a['commented']);
1431 function render_location_dummy(array $item) {
1432 if (x($item, 'location') && !empty($item['location'])) {
1433 return $item['location'];
1436 if (x($item, 'coord') && !empty($item['coord'])) {
1437 return $item['coord'];
1441 function get_responses(array $conv_responses, array $response_verbs, $ob, array $item) {
1443 foreach ($response_verbs as $v) {
1445 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], 0);
1446 $ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', []);
1447 $ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1448 if (count($ret[$v]['list']) > MAX_LIKERS) {
1449 $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1450 array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1451 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1453 $ret[$v]['list_part'] = '';
1455 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1456 $ret[$v]['title'] = $conv_responses[$v]['title'];
1460 foreach ($ret as $key) {
1461 if ($key['count'] == true) {
1465 $ret['count'] = $count;
1470 function get_response_button_text($v, $count)
1474 $return = L10n::tt('Like', 'Likes', $count);
1477 $return = L10n::tt('Dislike', 'Dislikes', $count);
1480 $return = L10n::tt('Attending', 'Attending', $count);
1483 $return = L10n::tt('Not Attending', 'Not Attending', $count);
1486 $return = L10n::tt('Undecided', 'Undecided', $count);