3 * @file include/conversation.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Item;
18 use Friendica\Model\Profile;
19 use Friendica\Model\Term;
20 use Friendica\Object\Post;
21 use Friendica\Object\Thread;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Temporal;
24 use Friendica\Util\XML;
26 function item_extract_images($body) {
33 $img_start = strpos($orig_body, '[img');
34 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
35 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
36 while (($img_st_close !== false) && ($img_end !== false)) {
38 $img_st_close++; // make it point to AFTER the closing bracket
39 $img_end += $img_start;
41 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
42 // This is an embedded image
44 $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
45 $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
49 $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
52 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
54 if ($orig_body === false) {
55 // in case the body ends on a closing image tag
59 $img_start = strpos($orig_body, '[img');
60 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
61 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
64 $new_body = $new_body . $orig_body;
66 return ['body' => $new_body, 'images' => $saved_image];
69 function item_redir_and_replace_images($body, $images, $cid) {
75 $pos = BBCode::getTagPosition($origbody, 'url', 0);
76 while ($pos !== false && $cnt < 1000) {
78 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
79 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
80 . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
82 $newbody .= substr($origbody, 0, $pos['start']['open']);
83 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
84 $origbody = substr($origbody, $pos['end']['close']);
85 if ($origbody === false) {
89 $subject = preg_replace($search, $replace, $subject);
93 // Isn't this supposed to use $cnt value for $occurrences? - @MrPetovan
94 $pos = BBCode::getTagPosition($origbody, 'url', 0);
96 $newbody .= $origbody;
99 foreach ($images as $image) {
101 * We're depending on the property of 'foreach' (specified on the PHP website) that
102 * it loops over the array starting from the first element and going sequentially
103 * to the last element.
105 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
112 * Render actions localized
114 function localize_item(&$item)
116 $extracted = item_extract_images($item['body']);
117 if ($extracted['images']) {
118 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
122 heluecht 2018-06-19: from my point of view this whole code part is useless.
123 It just renders the body message of technical posts (Like, dislike, ...).
124 But: The body isn't visible at all. So we do this stuff just because we can.
125 Even if these messages were visible, this would only mean that something went wrong.
126 During the further steps of the database restructuring I would like to address this issue.
129 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
130 if (activity_match($item['verb'], ACTIVITY_LIKE)
131 || activity_match($item['verb'], ACTIVITY_DISLIKE)
132 || activity_match($item['verb'], ACTIVITY_ATTEND)
133 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
134 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
136 $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink'];
137 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
138 if (!DBA::is_result($obj)) {
142 $author = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
143 $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
145 switch ($obj['verb']) {
147 switch ($obj['object-type']) {
148 case ACTIVITY_OBJ_EVENT:
149 $post_type = L10n::t('event');
152 $post_type = L10n::t('status');
156 if ($obj['resource-id']) {
157 $post_type = L10n::t('photo');
159 preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
160 $rr['plink'] = $m[1];
162 $post_type = L10n::t('status');
166 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
168 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
169 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
170 } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
171 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
172 } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
173 $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
174 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
175 $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
176 } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
177 $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
180 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
183 if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
185 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
187 $Aname = $item['author-name'];
188 $Alink = $item['author-link'];
190 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
192 $obj = XML::parseString($xmlhead.$item['object']);
193 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
195 $Bname = $obj->title;
198 foreach ($links->link as $l) {
199 $atts = $l->attributes();
200 switch ($atts['rel']) {
201 case "alternate": $Blink = $atts['href'];
202 case "photo": $Bphoto = $atts['href'];
206 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
207 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
209 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img]' . $Bphoto . '[/img][/url]';
212 $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto;
215 if (stristr($item['verb'], ACTIVITY_POKE)) {
216 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
220 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
224 $Aname = $item['author-name'];
225 $Alink = $item['author-link'];
227 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
229 $obj = XML::parseString($xmlhead.$item['object']);
230 $links = XML::parseString($xmlhead."<links>".unxmlify($obj->link)."</links>");
232 $Bname = $obj->title;
235 foreach ($links->link as $l) {
236 $atts = $l->attributes();
237 switch ($atts['rel']) {
238 case "alternate": $Blink = $atts['href'];
239 case "photo": $Bphoto = $atts['href'];
243 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
244 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
246 $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
250 * we can't have a translation string with three positions but no distinguishable text
251 * So here is the translate string.
253 $txt = L10n::t('%1$s poked %2$s');
255 // now translate the verb
256 $poked_t = trim(sprintf($txt, "", ""));
257 $txt = str_replace($poked_t, L10n::t($verb), $txt);
259 // then do the sprintf on the translation string
261 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
265 if (activity_match($item['verb'], ACTIVITY_TAG)) {
266 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
267 'verb', 'object-type', 'resource-id', 'body', 'plink'];
268 $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]);
269 if (!DBA::is_result($obj)) {
273 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
274 'network' => $item['author-network'], 'url' => $item['author-link']];
275 $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
277 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
278 'network' => $obj['author-network'], 'url' => $obj['author-link']];
279 $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
281 switch ($obj['verb']) {
283 switch ($obj['object-type']) {
284 case ACTIVITY_OBJ_EVENT:
285 $post_type = L10n::t('event');
288 $post_type = L10n::t('status');
292 if ($obj['resource-id']) {
293 $post_type = L10n::t('photo');
294 $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
295 $rr['plink'] = $m[1];
297 $post_type = L10n::t('status');
299 // Let's break everthing ... ;-)
302 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
304 $parsedobj = XML::parseString($xmlhead.$item['object']);
306 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
307 $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
310 if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
311 if ($item['object-type'] == "") {
315 $Aname = $item['author-name'];
316 $Alink = $item['author-link'];
318 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
320 $obj = XML::parseString($xmlhead.$item['object']);
321 if (strlen($obj->id)) {
322 $fields = ['author-link', 'author-name', 'plink'];
323 $target = Item::selectFirst($fields, ['uri' => $obj->id, 'uid' => $item['uid']]);
324 if (DBA::is_result($target) && $target['plink']) {
325 $Bname = $target['author-name'];
326 $Blink = $target['author-link'];
327 $A = '[url=' . Contact::magicLink($Alink) . ']' . $Aname . '[/url]';
328 $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
329 $P = '[url=' . $target['plink'] . ']' . L10n::t('post/item') . '[/url]';
330 $item['body'] = L10n::t('%1$s marked %2$s\'s %3$s as favorite', $A, $B, $P)."\n";
335 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
336 foreach ($matches as $mtch) {
337 if (!strpos($mtch[1], 'zrl=')) {
338 $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
343 // add zrl's to public images
344 $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
345 if (preg_match($photo_pattern, $item['body'])) {
346 $photo_replace = '[url=' . Profile::zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5' . '[/img][/url]';
347 $item['body'] = BBCode::pregReplaceInTag($photo_pattern, $photo_replace, 'url', $item['body']);
350 // add sparkle links to appropriate permalinks
351 $author = ['uid' => 0, 'id' => $item['author-id'],
352 'network' => $item['author-network'], 'url' => $item['author-link']];
354 if (!empty($item['plink'])) {
355 $item['plink'] = Contact::magicLinkbyContact($author, $item['plink']);
360 * Count the total of comments on this item and its desendants
361 * @TODO proper type-hint + doc-tag
363 function count_descendants($item) {
364 $total = count($item['children']);
367 foreach ($item['children'] as $child) {
368 if (!visible_activity($child)) {
371 $total += count_descendants($child);
378 function visible_activity($item) {
381 * likes (etc.) can apply to other things besides posts. Check if they are post children,
382 * in which case we handle them specially
384 $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
385 foreach ($hidden_activities as $act) {
386 if (activity_match($item['verb'], $act)) {
391 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
392 if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
400 * "Render" a conversation or list of items for HTML display.
401 * There are two major forms of display:
402 * - Sequential or unthreaded ("New Item View" or search results)
403 * - conversation view
404 * The $mode parameter decides between the various renderings and also
405 * figures out how to determine page owner and other contextual items
406 * that are based on unique features of the calling module.
409 function conversation(App $a, array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0) {
410 require_once 'mod/proxy.php';
412 $ssl_state = ((local_user()) ? true : false);
415 $live_update_div = '';
420 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
422 $arr_blocked = explode(',', $str_blocked);
423 for ($x = 0; $x < count($arr_blocked); $x ++) {
424 $arr_blocked[$x] = trim($arr_blocked[$x]);
430 $previewing = (($preview) ? ' preview ' : '');
432 if ($mode === 'network') {
433 $items = conversation_add_children($items, false, $order, $uid);
434 $profile_owner = local_user();
437 * The special div is needed for liveUpdate to kick in for this page.
438 * We only launch liveUpdate if you aren't filtering in some incompatible
439 * way and also you aren't writing a comment (discovered in javascript).
441 $live_update_div = '<div id="live-network"></div>' . "\r\n"
442 . "<script> var profile_uid = " . $_SESSION['uid']
443 . "; var netargs = '" . substr($a->cmd, 8)
445 . ((x($_GET, 'cid')) ? '&cid=' . $_GET['cid'] : '')
446 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
447 . ((x($_GET, 'star')) ? '&star=' . $_GET['star'] : '')
448 . ((x($_GET, 'order')) ? '&order=' . $_GET['order'] : '')
449 . ((x($_GET, 'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
450 . ((x($_GET, 'liked')) ? '&liked=' . $_GET['liked'] : '')
451 . ((x($_GET, 'conv')) ? '&conv=' . $_GET['conv'] : '')
452 . ((x($_GET, 'nets')) ? '&nets=' . $_GET['nets'] : '')
453 . ((x($_GET, 'cmin')) ? '&cmin=' . $_GET['cmin'] : '')
454 . ((x($_GET, 'cmax')) ? '&cmax=' . $_GET['cmax'] : '')
455 . ((x($_GET, 'file')) ? '&file=' . $_GET['file'] : '')
457 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
459 } elseif ($mode === 'profile') {
460 $profile_owner = $a->profile['profile_uid'];
464 if (x($_GET, 'tab')) {
465 $tab = notags(trim($_GET['tab']));
467 if ($tab === 'posts') {
469 * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
470 * because browser prefetching might change it on us. We have to deliver it with the page.
473 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
474 . "<script> var profile_uid = " . $a->profile['profile_uid']
475 . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
478 } elseif ($mode === 'notes') {
479 $profile_owner = local_user();
481 $live_update_div = '<div id="live-notes"></div>' . "\r\n"
482 . "<script> var profile_uid = " . local_user()
483 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
485 } elseif ($mode === 'display') {
486 $profile_owner = $a->profile['uid'];
488 $live_update_div = '<div id="live-display"></div>' . "\r\n"
489 . "<script> var profile_uid = " . defaults($_SESSION, 'uid', 0) . ";"
490 . " var profile_page = 1; </script>";
492 } elseif ($mode === 'community') {
493 $items = conversation_add_children($items, true, $order, $uid);
496 $live_update_div = '<div id="live-community"></div>' . "\r\n"
497 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
498 ."/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
500 } elseif ($mode === 'search') {
501 $live_update_div = '<div id="live-search"></div>' . "\r\n";
504 $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
507 $_SESSION['return_url'] = $a->query_string;
510 $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
511 Addon::callHooks('conversation_start',$cb);
513 $items = $cb['items'];
516 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
517 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
520 // array with html for each thread (parent+comments)
524 $page_template = get_markup_template("conversation.tpl");
526 if ($items && count($items)) {
527 if ($mode === 'community') {
530 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
537 if (in_array($mode, ['network-new', 'search', 'contact-posts'])) {
540 * "New Item View" on network page or search page results
541 * - just loop through the items and format them minimally for display
544 $tpl = 'search_item.tpl';
546 foreach ($items as $item) {
548 if (!visible_activity($item)) {
554 foreach ($arr_blocked as $b) {
555 if ($b && link_compare($item['author-link'], $b)) {
572 // prevent private email from leaking.
573 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
577 $profile_name = $item['author-name'];
578 if (!empty($item['author-link']) && empty($item['author-name'])) {
579 $profile_name = $item['author-link'];
582 $tags = Term::populateTagsFromItem($item);
584 $author = ['uid' => 0, 'id' => $item['author-id'],
585 'network' => $item['author-network'], 'url' => $item['author-link']];
586 $profile_link = Contact::magicLinkbyContact($author);
588 if (strpos($profile_link, 'redir/') === 0) {
589 $sparkle = ' sparkle';
592 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
593 Addon::callHooks('render_location',$locate);
595 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
597 localize_item($item);
598 if ($mode === 'network-new') {
605 'dropping' => $dropping,
606 'pagedrop' => $page_dropping,
607 'select' => L10n::t('Select'),
608 'delete' => L10n::t('Delete'),
612 $isstarred = "unstarred";
615 $likebuttons = false;
617 $body = prepare_body($item, true, $preview);
619 list($categories, $folders) = get_cats_and_terms($item);
621 $profile_name_e = $profile_name;
623 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
624 $title_e = ucfirst($item['content-warning']);
626 $title_e = $item['title'];
630 $tags_e = $tags['tags'];
631 $hashtags_e = $tags['hashtags'];
632 $mentions_e = $tags['mentions'];
633 $location_e = $location;
634 $owner_name_e = $owner_name;
638 'id' => ($preview ? 'P0' : $item['id']),
639 'guid' => ($preview ? 'Q0' : $item['guid']),
640 'network' => $item['network'],
641 'network_name' => ContactSelector::networkToName($item['network'], $profile_link),
642 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
643 'profile_url' => $profile_link,
644 'item_photo_menu' => item_photo_menu($item),
645 'name' => $profile_name_e,
646 'sparkle' => $sparkle,
648 'thumb' => System::removedBaseUrl(proxy_url($item['author-avatar'], false, PROXY_SIZE_THUMB)),
652 'hashtags' => $hashtags_e,
653 'mentions' => $mentions_e,
654 'txt_cats' => L10n::t('Categories:'),
655 'txt_folders' => L10n::t('Filed under:'),
656 'has_cats' => ((count($categories)) ? 'true' : ''),
657 'has_folders' => ((count($folders)) ? 'true' : ''),
658 'categories' => $categories,
659 'folders' => $folders,
660 'text' => strip_tags($body_e),
661 'localtime' => DateTimeFormat::local($item['created'], 'r'),
662 'ago' => (($item['app']) ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']),$item['app']) : Temporal::getRelativeDate($item['created'])),
663 'location' => $location_e,
665 'owner_name' => $owner_name_e,
666 'owner_url' => $owner_url,
667 'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-avatar'], false, PROXY_SIZE_THUMB)),
668 'plink' => get_plink($item),
670 'isstarred' => $isstarred,
673 'vote' => $likebuttons,
677 'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
678 'previewing' => $previewing,
679 'wait' => L10n::t('Please wait'),
683 $arr = ['item' => $item, 'output' => $tmp_item];
684 Addon::callHooks('display_item', $arr);
686 $threads[$threadsid]['id'] = $item['id'];
687 $threads[$threadsid]['network'] = $item['network'];
688 $threads[$threadsid]['items'] = [$arr['output']];
693 $page_template = get_markup_template("threaded_conversation.tpl");
695 $conv = new Thread($mode, $preview, $writable);
698 * get all the topmost parents
699 * this shouldn't be needed, as we should have only them in our array
700 * But for now, this array respects the old style, just in case
702 foreach ($items as $item) {
705 foreach ($arr_blocked as $b) {
706 if ($b && link_compare($item['author-link'], $b)) {
716 // Can we put this after the visibility check?
717 builtin_activity_puller($item, $conv_responses);
719 // Only add what is visible
720 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
724 if (!visible_activity($item)) {
728 /// @todo Check if this call is needed or not
729 $arr = ['item' => $item];
730 Addon::callHooks('display_item', $arr);
732 $item['pagedrop'] = $page_dropping;
734 if ($item['id'] == $item['parent']) {
735 $item_object = new Post($item);
736 $conv->addParent($item_object);
740 $threads = $conv->getTemplateData($conv_responses);
742 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
748 $o = replace_macros($page_template, [
749 '$baseurl' => System::baseUrl($ssl_state),
750 '$return_path' => $a->query_string,
751 '$live_update' => $live_update_div,
752 '$remove' => L10n::t('remove'),
755 '$threads' => $threads,
756 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? L10n::t('Delete Selected Items') : False),
763 * @brief Add comments to top level entries that had been fetched before
765 * The system will fetch the comments for the local user whenever possible.
766 * This behaviour is currently needed to allow commenting on Friendica posts.
768 * @param array $parents Parent items
770 * @return array items with parents and comments
772 function conversation_add_children(array $parents, $block_authors, $order, $uid) {
773 $max_comments = Config::get('system', 'max_comments', 100);
775 $params = ['order' => ['uid', 'commented' => true]];
777 if ($max_comments > 0) {
778 $params['limit'] = $max_comments;
783 foreach ($parents AS $parent) {
784 $condition = ["`item`.`parent-uri` = ? AND `item`.`uid` IN (0, ?) ",
785 $parent['uri'], local_user()];
786 if ($block_authors) {
787 $condition[0] .= "AND NOT `author`.`hidden`";
789 $thread_items = Item::selectForUser(local_user(), [], $condition, $params);
791 $comments = Item::inArray($thread_items);
793 if (count($comments) != 0) {
794 $items = array_merge($items, $comments);
798 foreach ($items as $index => $item) {
799 if ($item['uid'] == 0) {
800 $items[$index]['writable'] = in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
804 $items = conv_sort($items, $order);
809 function item_photo_menu($item) {
818 if (local_user() && local_user() == $item['uid'] && $item['parent'] == $item['id'] && !$item['self']) {
819 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
822 $author = ['uid' => 0, 'id' => $item['author-id'],
823 'network' => $item['author-network'], 'url' => $item['author-link']];
824 $profile_link = Contact::magicLinkbyContact($author);
825 $sparkle = (strpos($profile_link, 'redir/') === 0);
830 $condition = ['uid' => local_user(), 'nurl' => normalise_link($item['author-link'])];
831 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
832 if (DBA::is_result($contact)) {
833 $cid = $contact['id'];
834 $network = $contact['network'];
835 $rel = $contact['rel'];
839 $status_link = $profile_link . '?url=status';
840 $photos_link = $profile_link . '?url=photos';
841 $profile_link = $profile_link . '?url=profile';
844 if ($cid && !$item['self']) {
845 $poke_link = 'poke/?f=&c=' . $cid;
846 $contact_url = 'contacts/' . $cid;
847 $posts_link = 'contacts/' . $cid . '/posts';
849 if (in_array($network, [NETWORK_DFRN, NETWORK_DIASPORA])) {
850 $pm_url = 'message/new/' . $cid;
856 L10n::t('Follow Thread') => $sub_link,
857 L10n::t('View Status') => $status_link,
858 L10n::t('View Profile') => $profile_link,
859 L10n::t('View Photos') => $photos_link,
860 L10n::t('Network Posts') => $posts_link,
861 L10n::t('View Contact') => $contact_url,
862 L10n::t('Send PM') => $pm_url
865 if ($network == NETWORK_DFRN) {
866 $menu[L10n::t("Poke")] = $poke_link;
869 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
870 in_array($item['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
871 $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
874 $menu = [L10n::t('View Profile') => $item['author-link']];
877 $args = ['item' => $item, 'menu' => $menu];
879 Addon::callHooks('item_photo_menu', $args);
881 $menu = $args['menu'];
884 foreach ($menu as $k => $v) {
885 if (strpos($v, 'javascript:') === 0) {
887 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
889 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
896 * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
897 * Increments the count of each matching activity and adds a link to the author as needed.
900 * @param array &$conv_responses (already created with builtin activity structure)
903 function builtin_activity_puller($item, &$conv_responses) {
904 foreach ($conv_responses as $mode => $v) {
910 $verb = ACTIVITY_LIKE;
913 $verb = ACTIVITY_DISLIKE;
916 $verb = ACTIVITY_ATTEND;
919 $verb = ACTIVITY_ATTENDNO;
922 $verb = ACTIVITY_ATTENDMAYBE;
928 if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) {
929 $author = ['uid' => 0, 'id' => $item['author-id'],
930 'network' => $item['author-network'], 'url' => $item['author-link']];
931 $url = Contact::magicLinkbyContact($author);
932 if (strpos($url, 'redir/') === 0) {
933 $sparkle = ' class="sparkle" ';
936 $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
938 if (!x($item, 'thr-parent')) {
939 $item['thr-parent'] = $item['parent-uri'];
942 if (!(isset($conv_responses[$mode][$item['thr-parent'] . '-l'])
943 && is_array($conv_responses[$mode][$item['thr-parent'] . '-l']))) {
944 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
947 // only list each unique author once
948 if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
952 if (!isset($conv_responses[$mode][$item['thr-parent']])) {
953 $conv_responses[$mode][$item['thr-parent']] = 1;
955 $conv_responses[$mode][$item['thr-parent']] ++;
958 if (public_contact() == $item['author-id']) {
959 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
962 $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
964 // there can only be one activity verb per item so if we found anything, we can stop looking
971 * Format the vote text for a profile item
972 * @param int $cnt = number of people who vote the item
973 * @param array $arr = array of pre-linked names of likers/dislikers
974 * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
975 * @param int $id = item id
976 * @return string formatted text
978 function format_like($cnt, array $arr, $type, $id) {
985 // Phrase if there is only one liker. In other cases it will be uses for the expanded
986 // list which show all likers
989 $phrase = L10n::t('%s likes this.', $likers);
992 $phrase = L10n::t('%s doesn\'t like this.', $likers);
995 $phrase = L10n::t('%s attends.', $likers);
998 $phrase = L10n::t('%s doesn\'t attend.', $likers);
1000 case 'attendmaybe' :
1001 $phrase = L10n::t('%s attends maybe.', $likers);
1007 $total = count($arr);
1008 if ($total >= MAX_LIKERS) {
1009 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1011 if ($total < MAX_LIKERS) {
1012 $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1013 $arr2 = array_slice($arr, 0, -1);
1014 $str = implode(', ', $arr2) . ' ' . $last;
1016 if ($total >= MAX_LIKERS) {
1017 $str = implode(', ', $arr);
1018 $str .= L10n::t('and %d other people', $total - MAX_LIKERS);
1023 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1027 $phrase = L10n::t('<span %1$s>%2$d people</span> like this', $spanatts, $cnt);
1028 $explikers = L10n::t('%s like this.', $likers);
1031 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1032 $explikers = L10n::t('%s don\'t like this.', $likers);
1035 $phrase = L10n::t('<span %1$s>%2$d people</span> attend', $spanatts, $cnt);
1036 $explikers = L10n::t('%s attend.', $likers);
1039 $phrase = L10n::t('<span %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1040 $explikers = L10n::t('%s don\'t attend.', $likers);
1043 $phrase = L10n::t('<span %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1044 $explikers = L10n::t('%s attend maybe.', $likers);
1048 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1052 $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), [
1053 '$phrase' => $phrase,
1062 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1066 $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), []) : '';
1068 $tpl = get_markup_template('jot-header.tpl');
1069 $a->page['htmlhead'] .= replace_macros($tpl, [
1070 '$newpost' => 'true',
1071 '$baseurl' => System::baseUrl(true),
1072 '$geotag' => $geotag,
1073 '$nickname' => $x['nickname'],
1074 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1075 '$linkurl' => L10n::t('Please enter a link URL:'),
1076 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1077 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1078 '$term' => L10n::t('Tag term:'),
1079 '$fileas' => L10n::t('Save to Folder:'),
1080 '$whereareu' => L10n::t('Where are you right now?'),
1081 '$delitems' => L10n::t("Delete item\x28s\x29?")
1084 $tpl = get_markup_template('jot-end.tpl');
1085 $a->page['end'] .= replace_macros($tpl, [
1086 '$newpost' => 'true',
1087 '$baseurl' => System::baseUrl(true),
1088 '$geotag' => $geotag,
1089 '$nickname' => $x['nickname'],
1090 '$ispublic' => L10n::t('Visible to <strong>everybody</strong>'),
1091 '$linkurl' => L10n::t('Please enter a link URL:'),
1092 '$vidurl' => L10n::t("Please enter a video link/URL:"),
1093 '$audurl' => L10n::t("Please enter an audio link/URL:"),
1094 '$term' => L10n::t('Tag term:'),
1095 '$fileas' => L10n::t('Save to Folder:'),
1096 '$whereareu' => L10n::t('Where are you right now?')
1100 Addon::callHooks('jot_tool', $jotplugins);
1102 // Private/public post links for the non-JS ACL form
1104 if (x($_REQUEST, 'public')) {
1108 $query_str = $a->query_string;
1109 if (strpos($query_str, 'public=1') !== false) {
1110 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1114 * I think $a->query_string may never have ? in it, but I could be wrong
1115 * It looks like it's from the index.php?q=[etc] rewrite that the web
1116 * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1118 if (strpos($query_str, '?') === false) {
1119 $public_post_link = '?public=1';
1121 $public_post_link = '&public=1';
1124 // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1125 $tpl = get_markup_template("jot.tpl");
1127 $o .= replace_macros($tpl,[
1128 '$new_post' => L10n::t('New Post'),
1129 '$return_path' => $query_str,
1130 '$action' => 'item',
1131 '$share' => defaults($x, 'button', L10n::t('Share')),
1132 '$upload' => L10n::t('Upload photo'),
1133 '$shortupload' => L10n::t('upload photo'),
1134 '$attach' => L10n::t('Attach file'),
1135 '$shortattach' => L10n::t('attach file'),
1136 '$weblink' => L10n::t('Insert web link'),
1137 '$shortweblink' => L10n::t('web link'),
1138 '$video' => L10n::t('Insert video link'),
1139 '$shortvideo' => L10n::t('video link'),
1140 '$audio' => L10n::t('Insert audio link'),
1141 '$shortaudio' => L10n::t('audio link'),
1142 '$setloc' => L10n::t('Set your location'),
1143 '$shortsetloc' => L10n::t('set location'),
1144 '$noloc' => L10n::t('Clear browser location'),
1145 '$shortnoloc' => L10n::t('clear location'),
1146 '$title' => defaults($x, 'title', ''),
1147 '$placeholdertitle' => L10n::t('Set title'),
1148 '$category' => defaults($x, 'category', ''),
1149 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1150 '$wait' => L10n::t('Please wait'),
1151 '$permset' => L10n::t('Permission settings'),
1152 '$shortpermset' => L10n::t('permissions'),
1153 '$wall' => $notes_cid ? 0 : 1,
1154 '$posttype' => $notes_cid ? Item::PT_PERSONAL_NOTE : Item::PT_ARTICLE,
1155 '$content' => defaults($x, 'content', ''),
1156 '$post_id' => defaults($x, 'post_id', ''),
1157 '$baseurl' => System::baseUrl(true),
1158 '$defloc' => $x['default_location'],
1159 '$visitor' => $x['visitor'],
1160 '$pvisit' => $notes_cid ? 'none' : $x['visitor'],
1161 '$public' => L10n::t('Public post'),
1162 '$lockstate' => $x['lockstate'],
1163 '$bang' => $x['bang'],
1164 '$profile_uid' => $x['profile_uid'],
1165 '$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? L10n::t('Preview') : '',
1166 '$jotplugins' => $jotplugins,
1167 '$notes_cid' => $notes_cid,
1168 '$sourceapp' => L10n::t($a->sourcename),
1169 '$cancel' => L10n::t('Cancel'),
1170 '$rand_num' => random_digits(12),
1172 // ACL permissions box
1173 '$acl' => $x['acl'],
1174 '$group_perms' => L10n::t('Post to Groups'),
1175 '$contact_perms' => L10n::t('Post to Contacts'),
1176 '$private' => L10n::t('Private post'),
1177 '$is_private' => $private_post,
1178 '$public_link' => $public_post_link,
1180 //jot nav tab (used in some themes)
1181 '$message' => L10n::t('Message'),
1182 '$browser' => L10n::t('Browser'),
1186 if ($popup == true) {
1187 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1194 * Plucks the children of the given parent from a given item list.
1196 * @brief Plucks all the children in the given item list of the given parent
1198 * @param array $item_list
1199 * @param array $parent
1200 * @param bool $recursive
1203 function get_item_children(array &$item_list, array $parent, $recursive = true)
1206 foreach ($item_list as $i => $item) {
1207 if ($item['id'] != $item['parent']) {
1209 // Fallback to parent-uri if thr-parent is not set
1210 $thr_parent = $item['thr-parent'];
1211 if ($thr_parent == '') {
1212 $thr_parent = $item['parent-uri'];
1215 if ($thr_parent == $parent['uri']) {
1216 $item['children'] = get_item_children($item_list, $item);
1217 $children[] = $item;
1218 unset($item_list[$i]);
1220 } elseif ($item['parent'] == $parent['id']) {
1221 $children[] = $item;
1222 unset($item_list[$i]);
1230 * @brief Recursively sorts a tree-like item array
1232 * @param array $items
1235 function sort_item_children(array $items)
1238 usort($result, 'sort_thr_created_rev');
1239 foreach ($result as $k => $i) {
1240 if (isset($result[$k]['children'])) {
1241 $result[$k]['children'] = sort_item_children($result[$k]['children']);
1248 * @brief Recursively add all children items at the top level of a list
1250 * @param array $children List of items to append
1251 * @param array $item_list
1253 function add_children_to_list(array $children, array &$item_list)
1255 foreach ($children as $child) {
1256 $item_list[] = $child;
1257 if (isset($child['children'])) {
1258 add_children_to_list($child['children'], $item_list);
1264 * This recursive function takes the item tree structure created by conv_sort() and
1265 * flatten the extraneous depth levels when people reply sequentially, removing the
1266 * stairs effect in threaded conversations limiting the available content width.
1268 * The basic principle is the following: if a post item has only one reply and is
1269 * the last reply of its parent, then the reply is moved to the parent.
1271 * This process is rendered somewhat more complicated because items can be either
1272 * replies or likes, and these don't factor at all in the reply count/last reply.
1274 * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1276 * @param array $parent A tree-like array of items
1279 function smart_flatten_conversation(array $parent)
1281 if (!isset($parent['children']) || count($parent['children']) == 0) {
1285 // We use a for loop to ensure we process the newly-moved items
1286 for ($i = 0; $i < count($parent['children']); $i++) {
1287 $child = $parent['children'][$i];
1289 if (isset($child['children']) && count($child['children'])) {
1290 // This helps counting only the regular posts
1291 $count_post_closure = function($var) {
1292 return $var['verb'] === ACTIVITY_POST;
1295 $child_post_count = count(array_filter($child['children'], $count_post_closure));
1297 $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1299 // If there's only one child's children post and this is the last child post
1300 if ($child_post_count == 1 && $remaining_post_count == 1) {
1302 // Searches the post item in the children
1304 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1308 $moved_item = $child['children'][$j];
1309 unset($parent['children'][$i]['children'][$j]);
1310 $parent['children'][] = $moved_item;
1312 $parent['children'][$i] = smart_flatten_conversation($child);
1322 * Expands a flat list of items into corresponding tree-like conversation structures,
1323 * sort the top-level posts either on "created" or "commented", and finally
1324 * append all the items at the top level (???)
1326 * @brief Expands a flat item list into a conversation array for display
1328 * @param array $item_list A list of items belonging to one or more conversations
1329 * @param string $order Either on "created" or "commented"
1332 function conv_sort(array $item_list, $order)
1336 if (!(is_array($item_list) && count($item_list))) {
1342 // Dedupes the item list on the uri to prevent infinite loops
1343 foreach ($item_list as $item) {
1344 $item_array[$item['uri']] = $item;
1347 // Extract the top level items
1348 foreach ($item_array as $item) {
1349 if ($item['id'] == $item['parent']) {
1354 if (stristr($order, 'created')) {
1355 usort($parents, 'sort_thr_created');
1356 } elseif (stristr($order, 'commented')) {
1357 usort($parents, 'sort_thr_commented');
1361 * Plucks children from the item_array, second pass collects eventual orphan
1362 * items and add them as children of their top-level post.
1364 foreach ($parents as $i => $parent) {
1365 $parents[$i]['children'] =
1366 array_merge(get_item_children($item_array, $parent, true),
1367 get_item_children($item_array, $parent, false));
1370 foreach ($parents as $i => $parent) {
1371 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1374 if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1375 foreach ($parents as $i => $parent) {
1376 $parents[$i] = smart_flatten_conversation($parent);
1380 /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1381 /// However, this apparently ensures responses (likes, attendance) display (?!)
1382 foreach ($parents as $parent) {
1383 if (count($parent['children'])) {
1384 add_children_to_list($parent['children'], $parents);
1392 * @brief usort() callback to sort item arrays by the created key
1398 function sort_thr_created(array $a, array $b)
1400 return strcmp($b['created'], $a['created']);
1404 * @brief usort() callback to reverse sort item arrays by the created key
1410 function sort_thr_created_rev(array $a, array $b)
1412 return strcmp($a['created'], $b['created']);
1416 * @brief usort() callback to sort item arrays by the commented key
1422 function sort_thr_commented(array $a, array $b)
1424 return strcmp($b['commented'], $a['commented']);
1427 function render_location_dummy(array $item) {
1428 if (x($item, 'location') && !empty($item['location'])) {
1429 return $item['location'];
1432 if (x($item, 'coord') && !empty($item['coord'])) {
1433 return $item['coord'];
1437 function get_responses(array $conv_responses, array $response_verbs, $ob, array $item) {
1439 foreach ($response_verbs as $v) {
1441 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1442 $ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', []);
1443 $ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1444 if (count($ret[$v]['list']) > MAX_LIKERS) {
1445 $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1446 array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1447 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1449 $ret[$v]['list_part'] = '';
1451 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1452 $ret[$v]['title'] = $conv_responses[$v]['title'];
1456 foreach ($ret as $key) {
1457 if ($key['count'] == true) {
1461 $ret['count'] = $count;
1466 function get_response_button_text($v, $count)
1470 $return = L10n::tt('Like', 'Likes', $count);
1473 $return = L10n::tt('Dislike', 'Dislikes', $count);
1476 $return = L10n::tt('Attending', 'Attending', $count);
1479 $return = L10n::tt('Not Attending', 'Not Attending', $count);
1482 $return = L10n::tt('Undecided', 'Undecided', $count);