]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #4167 from MrPetovan/bug/4155-remove-proxy-oembed
[friendica.git] / include / conversation.php
1 <?php
2 /**
3  * @file include/conversation.php
4  */
5 use Friendica\App;
6 use Friendica\Content\Feature;
7 use Friendica\Core\Config;
8 use Friendica\Core\PConfig;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Object\Thread;
13 use Friendica\Object\Post;
14
15 require_once "include/bbcode.php";
16 require_once "include/acl_selectors.php";
17
18 function item_extract_images($body) {
19
20         $saved_image = array();
21         $orig_body = $body;
22         $new_body = '';
23
24         $cnt = 0;
25         $img_start = strpos($orig_body, '[img');
26         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
27         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
28         while (($img_st_close !== false) && ($img_end !== false)) {
29
30                 $img_st_close++; // make it point to AFTER the closing bracket
31                 $img_end += $img_start;
32
33                 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
34                         // This is an embedded image
35
36                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
37                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
38
39                         $cnt++;
40                 } else {
41                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
42                 }
43
44                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
45
46                 if ($orig_body === false) {
47                         // in case the body ends on a closing image tag
48                         $orig_body = '';
49                 }
50
51                 $img_start = strpos($orig_body, '[img');
52                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
53                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
54         }
55
56         $new_body = $new_body . $orig_body;
57
58         return array('body' => $new_body, 'images' => $saved_image);
59 }
60
61 function item_redir_and_replace_images($body, $images, $cid) {
62
63         $origbody = $body;
64         $newbody = '';
65
66         $cnt = 1;
67         $pos = get_bb_tag_pos($origbody, 'url', 1);
68         while ($pos !== false && $cnt < 1000) {
69
70                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
71                 $replace = '[url=' . System::baseUrl() . '/redir/' . $cid
72                                    . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
73
74                 $newbody .= substr($origbody, 0, $pos['start']['open']);
75                 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
76                 $origbody = substr($origbody, $pos['end']['close']);
77                 if ($origbody === false) {
78                         $origbody = '';
79                 }
80
81                 $subject = preg_replace($search, $replace, $subject);
82                 $newbody .= $subject;
83
84                 $cnt++;
85                 $pos = get_bb_tag_pos($origbody, 'url', 1);
86         }
87         $newbody .= $origbody;
88
89         $cnt = 0;
90         foreach ($images as $image) {
91                 /*
92                  * We're depending on the property of 'foreach' (specified on the PHP website) that
93                  * it loops over the array starting from the first element and going sequentially
94                  * to the last element.
95                  */
96                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
97                 $cnt++;
98         }
99         return $newbody;
100 }
101
102 /**
103  * Render actions localized
104  */
105 function localize_item(&$item) {
106
107         $extracted = item_extract_images($item['body']);
108         if ($extracted['images']) {
109                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
110         }
111
112         /// @Separted ???
113         $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
114         if (activity_match($item['verb'], ACTIVITY_LIKE)
115                 || activity_match($item['verb'], ACTIVITY_DISLIKE)
116                 || activity_match($item['verb'], ACTIVITY_ATTEND)
117                 || activity_match($item['verb'], ACTIVITY_ATTENDNO)
118                 || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
119
120                 /// @TODO may hurt performance
121                 $r = q("SELECT * FROM `item`, `contact`
122                         WHERE `item`.`contact-id`=`contact`.`id`
123                         AND `item`.`uri`='%s'",
124                         dbesc($item['parent-uri']));
125                 if (!DBM::is_result($r)) {
126                         return;
127                 }
128                 $obj = $r[0];
129
130                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
131                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
132
133                 switch ($obj['verb']) {
134                         case ACTIVITY_POST:
135                                 switch ($obj['object-type']) {
136                                         case ACTIVITY_OBJ_EVENT:
137                                                 $post_type = t('event');
138                                                 break;
139                                         default:
140                                                 $post_type = t('status');
141                                 }
142                                 break;
143                         default:
144                                 if ($obj['resource-id']) {
145                                         $post_type = t('photo');
146                                         $m = array();
147                                         preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
148                                         $rr['plink'] = $m[1];
149                                 } else {
150                                         $post_type = t('status');
151                                 }
152                 }
153
154                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
155
156                 if (activity_match($item['verb'], ACTIVITY_LIKE)) {
157                         $bodyverb = t('%1$s likes %2$s\'s %3$s');
158                 }
159                 elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
160                         $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
161                 }
162                 elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
163                         $bodyverb = t('%1$s attends %2$s\'s %3$s');
164                 }
165                 elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
166                         $bodyverb = t('%1$s doesn\'t attend %2$s\'s %3$s');
167                 }
168                 elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
169                         $bodyverb = t('%1$s attends maybe %2$s\'s %3$s');
170                 }
171                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
172
173         }
174         if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
175
176                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
177
178                 $Aname = $item['author-name'];
179                 $Alink = $item['author-link'];
180
181                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
182
183                 $obj = parse_xml_string($xmlhead.$item['object']);
184                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
185
186                 $Bname = $obj->title;
187                 $Blink = ""; $Bphoto = "";
188                 foreach ($links->link as $l) {
189                         $atts = $l->attributes();
190                         switch ($atts['rel']) {
191                                 case "alternate": $Blink = $atts['href'];
192                                 case "photo": $Bphoto = $atts['href'];
193                         }
194                 }
195
196                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
197                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
198                 if ($Bphoto != "") {
199                         $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
200                 }
201
202                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
203
204         }
205         if (stristr($item['verb'], ACTIVITY_POKE)) {
206                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
207                 if (! $verb) {
208                         return;
209                 }
210                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) {
211                         return;
212                 }
213
214                 $Aname = $item['author-name'];
215                 $Alink = $item['author-link'];
216
217                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
218
219                 $obj = parse_xml_string($xmlhead.$item['object']);
220                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
221
222                 $Bname = $obj->title;
223                 $Blink = "";
224                 $Bphoto = "";
225                 foreach ($links->link as $l) {
226                         $atts = $l->attributes();
227                         switch ($atts['rel']) {
228                                 case "alternate": $Blink = $atts['href'];
229                                 case "photo": $Bphoto = $atts['href'];
230                         }
231                 }
232
233                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
234                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
235                 if ($Bphoto != "") {
236                         $Bphoto = '[url=' . zrl($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
237                 }
238
239                 /*
240                  * we can't have a translation string with three positions but no distinguishable text
241                  * So here is the translate string.
242                  */
243                 $txt = t('%1$s poked %2$s');
244
245                 // now translate the verb
246                 $poked_t = trim(sprintf($txt, "", ""));
247                 $txt = str_replace( $poked_t, t($verb), $txt);
248
249                 // then do the sprintf on the translation string
250
251                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
252
253         }
254
255         if (activity_match($item['verb'], ACTIVITY_TAG)) {
256                 /// @TODO may hurt performance "joining" two tables + asterisk
257                 $r = q("SELECT * FROM `item`, `contact`
258                         WHERE `item`.`contact-id`=`contact`.`id`
259                         AND `item`.`uri`='%s'",
260                         dbesc($item['parent-uri']));
261
262                 if (!DBM::is_result($r)) {
263                         return;
264                 }
265
266                 $obj = $r[0];
267
268                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
269                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
270
271                 switch ($obj['verb']) {
272                         case ACTIVITY_POST:
273                                 switch ($obj['object-type']) {
274                                         case ACTIVITY_OBJ_EVENT:
275                                                 $post_type = t('event');
276                                                 break;
277                                         default:
278                                                 $post_type = t('status');
279                                 }
280                                 break;
281                         default:
282                                 if ($obj['resource-id']) {
283                                         $post_type = t('photo');
284                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
285                                         $rr['plink'] = $m[1];
286                                 } else {
287                                         $post_type = t('status');
288                                 }
289                                 // Let's break everthing ... ;-)
290                                 break;
291                 }
292                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
293
294                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
295
296                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
297                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
298
299         }
300         if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
301
302                 if ($item['object-type'] == "") {
303                         return;
304                 }
305
306                 $Aname = $item['author-name'];
307                 $Alink = $item['author-link'];
308
309                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
310
311                 $obj = parse_xml_string($xmlhead.$item['object']);
312                 if (strlen($obj->id)) {
313                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
314                                         dbesc($obj->id),
315                                         intval($item['uid'])
316                         );
317
318                         if (DBM::is_result($r) && $r[0]['plink']) {
319                                 $target = $r[0];
320                                 $Bname = $target['author-name'];
321                                 $Blink = $target['author-link'];
322                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
323                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
324                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
325                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
326                         }
327                 }
328         }
329         $matches = null;
330         if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
331                 foreach ($matches as $mtch) {
332                         if (! strpos($mtch[1], 'zrl=')) {
333                                 $item['body'] = str_replace($mtch[0], '@[url=' . zrl($mtch[1]) . ']', $item['body']);
334                         }
335                 }
336         }
337
338         // add zrl's to public images
339         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
340         if (preg_match($photo_pattern, $item['body'])) {
341                 $photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
342                 $item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
343         }
344
345         // add sparkle links to appropriate permalinks
346
347         $x = stristr($item['plink'],'/display/');
348         if ($x) {
349                 $sparkle = false;
350                 $y = best_link_url($item, $sparkle);
351
352                 if (strstr($y, '/redir/')) {
353                         $item['plink'] = $y . '?f=&url=' . $item['plink'];
354                 }
355         }
356 }
357
358 /**
359  * Count the total of comments on this item and its desendants
360  * @TODO proper type-hint + doc-tag
361  */
362 function count_descendants($item) {
363         $total = count($item['children']);
364
365         if ($total > 0) {
366                 foreach ($item['children'] as $child) {
367                         if (! visible_activity($child)) {
368                                 $total --;
369                         }
370                         $total += count_descendants($child);
371                 }
372         }
373
374         return $total;
375 }
376
377 function visible_activity($item) {
378
379         /*
380          * likes (etc.) can apply to other things besides posts. Check if they are post children,
381          * in which case we handle them specially
382          */
383         $hidden_activities = array(ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
384         foreach ($hidden_activities as $act) {
385                 if (activity_match($item['verb'], $act)) {
386                         return false;
387                 }
388         }
389
390         if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
391                 if (! (($item['self']) && ($item['uid'] == local_user()))) {
392                         return false;
393                 }
394         }
395
396         return true;
397 }
398
399 /**
400  * @brief SQL query for items
401  */
402 function item_query() {
403         return "SELECT " . item_fieldlists() . " FROM `item` " .
404                 item_joins() . " WHERE " . item_condition();
405 }
406
407 /**
408  * @brief List of all data fields that are needed for displaying items
409  */
410 function item_fieldlists() {
411
412 /*
413 These Fields are not added below (yet). They are here to for bug search.
414 `item`.`type`,
415 `item`.`extid`,
416 `item`.`changed`,
417 `item`.`moderated`,
418 `item`.`target-type`,
419 `item`.`target`,
420 `item`.`resource-id`,
421 `item`.`tag`,
422 `item`.`inform`,
423 `item`.`pubmail`,
424 `item`.`visible`,
425 `item`.`spam`,
426 `item`.`bookmark`,
427 `item`.`unseen`,
428 `item`.`deleted`,
429 `item`.`origin`,
430 `item`.`forum_mode`,
431 `item`.`last-child`,
432 `item`.`mention`,
433 `item`.`global`,
434 `item`.`gcontact-id`,
435 `item`.`shadow`,
436 */
437
438         return "`item`.`author-id`, `item`.`author-link`, `item`.`author-name`, `item`.`author-avatar`,
439                 `item`.`owner-id`, `item`.`owner-link`, `item`.`owner-name`, `item`.`owner-avatar`,
440                 `item`.`contact-id`, `item`.`uid`, `item`.`id`, `item`.`parent`,
441                 `item`.`uri`, `item`.`thr-parent`, `item`.`parent-uri`,
442                 `item`.`commented`, `item`.`created`, `item`.`edited`, `item`.`received`,
443                 `item`.`verb`, `item`.`object-type`, `item`.`postopts`, `item`.`plink`,
444                 `item`.`guid`, `item`.`wall`, `item`.`private`, `item`.`starred`,
445                 `item`.`title`, `item`.`body`, `item`.`file`, `item`.`event-id`,
446                 `item`.`location`, `item`.`coord`, `item`.`app`, `item`.`attach`,
447                 `item`.`rendered-hash`, `item`.`rendered-html`, `item`.`object`,
448                 `item`.`allow_cid`, `item`.`allow_gid`, `item`.`deny_cid`, `item`.`deny_gid`,
449                 `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
450
451                 `author`.`thumb` AS `author-thumb`, `owner`.`thumb` AS `owner-thumb`,
452
453                 `contact`.`network`, `contact`.`url`, `contact`.`name`, `contact`.`writable`,
454                 `contact`.`self`, `contact`.`id` AS `cid`, `contact`.`alias`,
455
456                 `event`.`created` AS `event-created`, `event`.`edited` AS `event-edited`,
457                 `event`.`start` AS `event-start`,`event`.`finish` AS `event-finish`,
458                 `event`.`summary` AS `event-summary`,`event`.`desc` AS `event-desc`,
459                 `event`.`location` AS `event-location`, `event`.`type` AS `event-type`,
460                 `event`.`nofinish` AS `event-nofinish`,`event`.`adjust` AS `event-adjust`,
461                 `event`.`ignore` AS `event-ignore`, `event`.`id` AS `event-id`";
462 }
463
464 /**
465  * @brief SQL join for contacts that are needed for displaying items
466  */
467 function item_joins() {
468         return "STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND
469                 (NOT `contact`.`blocked` OR `contact`.`pending`)
470                 LEFT JOIN `contact` AS `author` ON `author`.`id`=`item`.`author-id`
471                 LEFT JOIN `contact` AS `owner` ON `owner`.`id`=`item`.`owner-id`
472                 LEFT JOIN `event` ON `event-id` = `event`.`id`";
473 }
474
475 /**
476  * @brief SQL condition for items that are needed for displaying items
477  */
478 function item_condition() {
479         return "`item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`";
480 }
481
482 /**
483  * "Render" a conversation or list of items for HTML display.
484  * There are two major forms of display:
485  *      - Sequential or unthreaded ("New Item View" or search results)
486  *      - conversation view
487  * The $mode parameter decides between the various renderings and also
488  * figures out how to determine page owner and other contextual items
489  * that are based on unique features of the calling module.
490  *
491  */
492 function conversation(App $a, $items, $mode, $update, $preview = false) {
493         require_once 'include/bbcode.php';
494         require_once 'mod/proxy.php';
495
496         $ssl_state = ((local_user()) ? true : false);
497
498         $profile_owner = 0;
499         $live_update_div = '';
500
501         $arr_blocked = null;
502
503         if (local_user()) {
504                 $str_blocked = PConfig::get(local_user(), 'system', 'blocked');
505                 if ($str_blocked) {
506                         $arr_blocked = explode(',', $str_blocked);
507                         for ($x = 0; $x < count($arr_blocked); $x ++) {
508                                 $arr_blocked[$x] = trim($arr_blocked[$x]);
509                         }
510                 }
511
512         }
513
514         $previewing = (($preview) ? ' preview ' : '');
515
516         if ($mode === 'network') {
517                 $profile_owner = local_user();
518                 if (!$update) {
519                         /*
520                          * The special div is needed for liveUpdate to kick in for this page.
521                          * We only launch liveUpdate if you aren't filtering in some incompatible
522                          * way and also you aren't writing a comment (discovered in javascript).
523                          */
524                         $live_update_div = '<div id="live-network"></div>' . "\r\n"
525                                 . "<script> var profile_uid = " . $_SESSION['uid']
526                                 . "; var netargs = '" . substr($a->cmd, 8)
527                                 . '?f='
528                                 . ((x($_GET, 'cid'))    ? '&cid='    . $_GET['cid']    : '')
529                                 . ((x($_GET, 'search')) ? '&search=' . $_GET['search'] : '')
530                                 . ((x($_GET, 'star'))   ? '&star='   . $_GET['star']   : '')
531                                 . ((x($_GET, 'order'))  ? '&order='  . $_GET['order']  : '')
532                                 . ((x($_GET, 'bmark'))  ? '&bmark='  . $_GET['bmark']  : '')
533                                 . ((x($_GET, 'liked'))  ? '&liked='  . $_GET['liked']  : '')
534                                 . ((x($_GET, 'conv'))   ? '&conv='   . $_GET['conv']   : '')
535                                 . ((x($_GET, 'spam'))   ? '&spam='   . $_GET['spam']   : '')
536                                 . ((x($_GET, 'nets'))   ? '&nets='   . $_GET['nets']   : '')
537                                 . ((x($_GET, 'cmin'))   ? '&cmin='   . $_GET['cmin']   : '')
538                                 . ((x($_GET, 'cmax'))   ? '&cmax='   . $_GET['cmax']   : '')
539                                 . ((x($_GET, 'file'))   ? '&file='   . $_GET['file']   : '')
540
541                                 . "'; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
542                 }
543         } elseif ($mode === 'profile') {
544                 $profile_owner = $a->profile['profile_uid'];
545
546                 if (!$update) {
547                         $tab = 'posts';
548                         if (x($_GET, 'tab')) {
549                                 $tab = notags(trim($_GET['tab']));
550                         }
551                         if ($tab === 'posts') {
552                                 /*
553                                  * This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
554                                  * because browser prefetching might change it on us. We have to deliver it with the page.
555                                  */
556
557                                 $live_update_div = '<div id="live-profile"></div>' . "\r\n"
558                                         . "<script> var profile_uid = " . $a->profile['profile_uid']
559                                         . "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
560                         }
561                 }
562         } elseif ($mode === 'notes') {
563                 $profile_owner = local_user();
564                 if (!$update) {
565                         $live_update_div = '<div id="live-notes"></div>' . "\r\n"
566                                 . "<script> var profile_uid = " . local_user()
567                                 . "; var netargs = '/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
568                 }
569         } elseif ($mode === 'display') {
570                 $profile_owner = $a->profile['uid'];
571                 if (!$update) {
572                         $live_update_div = '<div id="live-display"></div>' . "\r\n"
573                                 . "<script> var profile_uid = " . $_SESSION['uid'] . ";"
574                                 . " var profile_page = 1; </script>";
575                 }
576         } elseif ($mode === 'community') {
577                 if (!$community_readonly) {
578                         $items = community_add_items($items);
579                 }
580                 $profile_owner = 0;
581                 if (!$update) {
582                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
583                                 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
584                                 ."/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
585                 }
586         } elseif ($mode === 'search') {
587                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
588         }
589
590         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
591
592
593         if ($update) {
594                 $return_url = $_SESSION['return_url'];
595         } else {
596                 $return_url = $_SESSION['return_url'] = $a->query_string;
597         }
598
599         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
600         call_hooks('conversation_start',$cb);
601
602         $items = $cb['items'];
603
604         $cmnt_tpl    = get_markup_template('comment_item.tpl');
605         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
606
607         $conv_responses = array(
608                 'like' => array('title' => t('Likes','title')), 'dislike' => array('title' => t('Dislikes','title')),
609                 'attendyes' => array('title' => t('Attending','title')), 'attendno' => array('title' => t('Not attending','title')), 'attendmaybe' => array('title' => t('Might attend','title'))
610         );
611
612         // array with html for each thread (parent+comments)
613         $threads = array();
614         $threadsid = -1;
615
616         $page_template = get_markup_template("conversation.tpl");
617
618         if ($items && count($items)) {
619                 $community_readonly = ($mode === 'community');
620
621                 // Currently behind a config value. This allows the commenting and sharing of every public item.
622                 if (Config::get('system', 'comment_public')) {
623                         if ($mode === 'community') {
624                                 $community_readonly = false;
625                                 $writable = true;
626                         } else {
627                                 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], array(NETWORK_OSTATUS, NETWORK_DIASPORA));
628                         }
629                 } else {
630                         $writable = false;
631                 }
632
633                 if (!local_user()) {
634                         $writable = false;
635                 }
636
637                 if ($mode === 'network-new' || $mode === 'search' || $community_readonly) {
638
639                         /*
640                          * "New Item View" on network page or search page results
641                          * - just loop through the items and format them minimally for display
642                          */
643
644                         /// @TODO old lost code?
645                         // $tpl = get_markup_template('search_item.tpl');
646                         $tpl = 'search_item.tpl';
647
648                         foreach ($items as $item) {
649
650                                 if ($arr_blocked) {
651                                         $blocked = false;
652                                         foreach ($arr_blocked as $b) {
653                                                 if ($b && link_compare($item['author-link'], $b)) {
654                                                         $blocked = true;
655                                                         break;
656                                                 }
657                                         }
658                                         if ($blocked) {
659                                                 continue;
660                                         }
661                                 }
662
663
664                                 $threadsid++;
665
666                                 $owner_url   = '';
667                                 $owner_name  = '';
668                                 $sparkle     = '';
669
670                                 // prevent private email from leaking.
671                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
672                                         continue;
673                                 }
674
675                                 $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
676                                 if ($item['author-link'] && (! $item['author-name'])) {
677                                         $profile_name = $item['author-link'];
678                                 }
679
680                                 $tags = array();
681                                 $hashtags = array();
682                                 $mentions = array();
683
684                                 $searchpath = System::baseUrl()."/search?tag=";
685
686                                 $taglist = dba::select('term', array('type', 'term', 'url'),
687                                                         array("`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION),
688                                                         array('order' => array('tid')));
689
690                                 while ($tag = dba::fetch($taglist)) {
691                                         if ($tag["url"] == "") {
692                                                 $tag["url"] = $searchpath . strtolower($tag["term"]);
693                                         }
694
695                                         $tag["url"] = best_link_url($item, $sp, $tag["url"]);
696
697                                         if ($tag["type"] == TERM_HASHTAG) {
698                                                 $hashtags[] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
699                                                 $prefix = "#";
700                                         } elseif ($tag["type"] == TERM_MENTION) {
701                                                 $mentions[] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
702                                                 $prefix = "@";
703                                         }
704                                         $tags[] = $prefix."<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
705                                 }
706                                 dba::close($taglist);
707
708                                 $sp = false;
709                                 $profile_link = best_link_url($item, $sp);
710                                 if ($profile_link === 'mailbox') {
711                                         $profile_link = '';
712                                 }
713
714                                 if ($sp) {
715                                         $sparkle = ' sparkle';
716                                 } else {
717                                         $profile_link = zrl($profile_link);
718                                 }
719
720                                 if (!x($item, 'author-thumb') || ($item['author-thumb'] == "")) {
721                                         $author_contact = Contact::getDetailsByURL($item['author-link'], $profile_owner);
722                                         if ($author_contact["thumb"]) {
723                                                 $item['author-thumb'] = $author_contact["thumb"];
724                                         } else {
725                                                 $item['author-thumb'] = $item['author-avatar'];
726                                         }
727                                 }
728
729                                 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
730                                         $owner_contact = Contact::getDetailsByURL($item['owner-link'], $profile_owner);
731                                         if ($owner_contact["thumb"]) {
732                                                 $item['owner-thumb'] = $owner_contact["thumb"];
733                                         } else {
734                                                 $item['owner-thumb'] = $item['owner-avatar'];
735                                         }
736                                 }
737
738                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
739                                 call_hooks('render_location',$locate);
740
741                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
742
743                                 localize_item($item);
744                                 if ($mode === 'network-new') {
745                                         $dropping = true;
746                                 } else {
747                                         $dropping = false;
748                                 }
749
750                                 $drop = array(
751                                         'dropping' => $dropping,
752                                         'pagedrop' => $page_dropping,
753                                         'select' => t('Select'),
754                                         'delete' => t('Delete'),
755                                 );
756
757                                 $star = false;
758                                 $isstarred = "unstarred";
759
760                                 $lock = false;
761                                 $likebuttons = false;
762                                 $shareable = false;
763
764                                 $body = prepare_body($item, true, $preview);
765
766                                 list($categories, $folders) = get_cats_and_terms($item);
767
768                                 $profile_name_e = $profile_name;
769                                 $item['title_e'] = $item['title'];
770                                 $body_e = $body;
771                                 $tags_e = $tags;
772                                 $hashtags_e = $hashtags;
773                                 $mentions_e = $mentions;
774                                 $location_e = $location;
775                                 $owner_name_e = $owner_name;
776
777                                 if ($item['item_network'] == "") {
778                                         $item['item_network'] = $item['network'];
779                                 }
780
781                                 $tmp_item = array(
782                                         'template' => $tpl,
783                                         'id' => (($preview) ? 'P0' : $item['item_id']),
784                                         'guid' => (($preview) ? 'Q0' : $item['guid']),
785                                         'network' => $item['item_network'],
786                                         'network_name' => network_to_name($item['item_network'], $profile_link),
787                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
788                                         'profile_url' => $profile_link,
789                                         'item_photo_menu' => item_photo_menu($item),
790                                         'name' => $profile_name_e,
791                                         'sparkle' => $sparkle,
792                                         'lock' => $lock,
793                                         'thumb' => System::removedBaseUrl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
794                                         'title' => $item['title_e'],
795                                         'body' => $body_e,
796                                         'tags' => $tags_e,
797                                         'hashtags' => $hashtags_e,
798                                         'mentions' => $mentions_e,
799                                         'txt_cats' => t('Categories:'),
800                                         'txt_folders' => t('Filed under:'),
801                                         'has_cats' => ((count($categories)) ? 'true' : ''),
802                                         'has_folders' => ((count($folders)) ? 'true' : ''),
803                                         'categories' => $categories,
804                                         'folders' => $folders,
805                                         'text' => strip_tags($body_e),
806                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
807                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
808                                         'location' => $location_e,
809                                         'indent' => '',
810                                         'owner_name' => $owner_name_e,
811                                         'owner_url' => $owner_url,
812                                         'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
813                                         'plink' => get_plink($item),
814                                         'edpost' => false,
815                                         'isstarred' => $isstarred,
816                                         'star' => $star,
817                                         'drop' => $drop,
818                                         'vote' => $likebuttons,
819                                         'like' => '',
820                                         'dislike' => '',
821                                         'comment' => '',
822                                         'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
823                                         'previewing' => $previewing,
824                                         'wait' => t('Please wait'),
825                                         'thread_level' => 1,
826                                 );
827
828                                 $arr = array('item' => $item, 'output' => $tmp_item);
829                                 call_hooks('display_item', $arr);
830
831                                 $threads[$threadsid]['id'] = $item['item_id'];
832                                 $threads[$threadsid]['network'] = $item['item_network'];
833                                 $threads[$threadsid]['items'] = array($arr['output']);
834
835                         }
836                 } else {
837                         // Normal View
838                         $page_template = get_markup_template("threaded_conversation.tpl");
839
840                         $conv = new Thread($mode, $preview, $writable);
841
842                         /*
843                          * get all the topmost parents
844                          * this shouldn't be needed, as we should have only them in our array
845                          * But for now, this array respects the old style, just in case
846                          */
847                         $threads = array();
848                         foreach ($items as $item) {
849
850                                 if ($arr_blocked) {
851                                         $blocked = false;
852                                         foreach ($arr_blocked as $b) {
853                                                 if ($b && link_compare($item['author-link'], $b)) {
854                                                         $blocked = true;
855                                                         break;
856                                                 }
857                                         }
858                                         if ($blocked) {
859                                                 continue;
860                                         }
861                                 }
862
863                                 // Can we put this after the visibility check?
864                                 builtin_activity_puller($item, $conv_responses);
865
866                                 // Only add what is visible
867                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
868                                         continue;
869                                 }
870
871                                 if (! visible_activity($item)) {
872                                         continue;
873                                 }
874
875                                 call_hooks('display_item', $arr);
876
877                                 $item['pagedrop'] = $page_dropping;
878
879                                 if ($item['id'] == $item['parent']) {
880                                         $item_object = new Post($item);
881                                         $conv->addParent($item_object);
882                                 }
883                         }
884
885                         $threads = $conv->getTemplateData($conv_responses);
886
887                         if (!$threads) {
888                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
889                                 $threads = array();
890                         }
891                 }
892         }
893
894         $o = replace_macros($page_template, array(
895                 '$baseurl' => System::baseUrl($ssl_state),
896                 '$return_path' => $a->query_string,
897                 '$live_update' => $live_update_div,
898                 '$remove' => t('remove'),
899                 '$mode' => $mode,
900                 '$user' => $a->user,
901                 '$threads' => $threads,
902                 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? t('Delete Selected Items') : False),
903         ));
904
905         return $o;
906 }
907
908 /**
909  * @brief Add comments to top level entries that had been fetched before
910  *
911  * The system will fetch the comments for the local user whenever possible.
912  * This behaviour is currently needed to allow commenting on Friendica posts.
913  *
914  * @param array $parents Parent items
915  *
916  * @return array items with parents and comments
917  */
918 function community_add_items($parents) {
919         $max_comments = Config::get("system", "max_comments", 100);
920
921         $items = array();
922
923         foreach ($parents AS $parent) {
924                 $thread_items = dba::p(item_query()." AND `item`.`uid` = ?
925                         AND `item`.`parent-uri` = ?
926                         ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
927                         local_user(),
928                         $parent['uri']
929                 );
930                 $comments = dba::inArray($thread_items);
931
932                 if (count($comments) == 0) {
933                         $thread_items = dba::p(item_query()." AND `item`.`uid` = 0
934                                 AND `item`.`parent-uri` = ?
935                                 ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
936                                 $parent['uri']
937                         );
938                         $comments = dba::inArray($thread_items);
939                 }
940
941                 if (count($comments) != 0) {
942                         $items = array_merge($items, $comments);
943                 }
944         }
945
946         foreach ($items as $index => $item) {
947                 if ($item['uid'] == 0) {
948                         $items[$index]['writable'] = in_array($item['network'], [NETWORK_DIASPORA, NETWORK_OSTATUS]);
949                 }
950         }
951
952         $items = conv_sort($items, "`commented`");
953
954         return $items;
955 }
956
957 function best_link_url($item, &$sparkle, $url = '') {
958
959         $best_url = '';
960         $sparkle  = false;
961
962         $clean_url = normalise_link($item['author-link']);
963
964         if (local_user()) {
965                 $r = dba::select('contact', array('id'),
966                         array('network' => NETWORK_DFRN, 'uid' => local_user(), 'nurl' => normalise_link($clean_url), 'pending' => false),
967                         array('limit' => 1));
968                 if (DBM::is_result($r)) {
969                         $best_url = 'redir/' . $r['id'];
970                         $sparkle = true;
971                         if ($url != '') {
972                                 $hostname = get_app()->get_hostname();
973                                 if (!strstr($url, $hostname)) {
974                                         $best_url .= "?url=".$url;
975                                 } else {
976                                         $best_url = $url;
977                                 }
978                         }
979                 }
980         }
981         if (! $best_url) {
982                 if ($url != '') {
983                         $best_url = $url;
984                 } elseif (strlen($item['author-link'])) {
985                         $best_url = $item['author-link'];
986                 } else {
987                         $best_url = $item['url'];
988                 }
989         }
990
991         return $best_url;
992 }
993
994
995 function item_photo_menu($item) {
996         $sub_link = '';
997         $poke_link = '';
998         $contact_url = '';
999         $pm_url = '';
1000         $status_link = '';
1001         $photos_link = '';
1002         $posts_link = '';
1003         $network = '';
1004
1005         if ((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
1006                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
1007         }
1008
1009         $sparkle = false;
1010         $profile_link = best_link_url($item, $sparkle);
1011         if ($profile_link === 'mailbox') {
1012                 $profile_link = '';
1013         }
1014
1015         $cid = 0;
1016         $network = '';
1017         $rel = 0;
1018         $r = dba::select('contact', array('id', 'network', 'rel'), array('uid' => local_user(), 'nurl' => normalise_link($item['author-link'])), array('limit' => 1));
1019         if (DBM::is_result($r)) {
1020                 $cid = $r['id'];
1021                 $network = $r['network'];
1022                 $rel = $r['rel'];
1023         }
1024
1025         if ($sparkle) {
1026                 $status_link = $profile_link . '?url=status';
1027                 $photos_link = $profile_link . '?url=photos';
1028                 $profile_link = $profile_link . '?url=profile';
1029                 $zurl = '';
1030         } else {
1031                 $profile_link = zrl($profile_link);
1032         }
1033
1034         if ($cid && !$item['self']) {
1035                 $poke_link = 'poke/?f=&c=' . $cid;
1036                 $contact_url = 'contacts/' . $cid;
1037                 $posts_link = 'contacts/' . $cid . '/posts';
1038
1039                 if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA))) {
1040                         $pm_url = 'message/new/' . $cid;
1041                 }
1042         }
1043
1044         if (local_user()) {
1045                 $menu = array(
1046                         t('Follow Thread') => $sub_link,
1047                         t('View Status') => $status_link,
1048                         t('View Profile') => $profile_link,
1049                         t('View Photos') => $photos_link,
1050                         t('Network Posts') => $posts_link,
1051                         t('View Contact') => $contact_url,
1052                         t('Send PM') => $pm_url
1053                 );
1054
1055                 if ($network == NETWORK_DFRN) {
1056                         $menu[t("Poke")] = $poke_link;
1057                 }
1058
1059                 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
1060                         in_array($item['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
1061                         $menu[t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
1062                 }
1063         } else {
1064                 $menu = array(t('View Profile') => $item['author-link']);
1065         }
1066
1067         $args = array('item' => $item, 'menu' => $menu);
1068
1069         call_hooks('item_photo_menu', $args);
1070
1071         $menu = $args['menu'];
1072
1073         $o = '';
1074         foreach ($menu as $k => $v) {
1075                 if (strpos($v, 'javascript:') === 0) {
1076                         $v = substr($v, 11);
1077                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1078                 } elseif ($v!='') {
1079                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1080                 }
1081         }
1082         return $o;
1083 }
1084
1085 /**
1086  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
1087  * Increments the count of each matching activity and adds a link to the author as needed.
1088  *
1089  * @param array $item
1090  * @param array &$conv_responses (already created with builtin activity structure)
1091  * @return void
1092  */
1093 function builtin_activity_puller($item, &$conv_responses) {
1094         foreach ($conv_responses as $mode => $v) {
1095                 $url = '';
1096                 $sparkle = '';
1097
1098                 switch ($mode) {
1099                         case 'like':
1100                                 $verb = ACTIVITY_LIKE;
1101                                 break;
1102                         case 'dislike':
1103                                 $verb = ACTIVITY_DISLIKE;
1104                                 break;
1105                         case 'attendyes':
1106                                 $verb = ACTIVITY_ATTEND;
1107                                 break;
1108                         case 'attendno':
1109                                 $verb = ACTIVITY_ATTENDNO;
1110                                 break;
1111                         case 'attendmaybe':
1112                                 $verb = ACTIVITY_ATTENDMAYBE;
1113                                 break;
1114                         default:
1115                                 return;
1116                                 break;
1117                 }
1118
1119                 if ((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
1120                         $url = $item['author-link'];
1121                         if ((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'], $item['url']))) {
1122                                 $url = 'redir/' . $item['contact-id'];
1123                                 $sparkle = ' class="sparkle" ';
1124                         } else {
1125                                 $url = zrl($url);
1126                         }
1127
1128                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1129
1130                         if (! $item['thr-parent']) {
1131                                 $item['thr-parent'] = $item['parent-uri'];
1132                         }
1133
1134                         if (! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
1135                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l'])))) {
1136                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = array();
1137                         }
1138
1139                         // only list each unique author once
1140                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1141                                 continue;
1142                         }
1143
1144                         if (! isset($conv_responses[$mode][$item['thr-parent']])) {
1145                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1146                         } else {
1147                                 $conv_responses[$mode][$item['thr-parent']] ++;
1148                         }
1149
1150                         if (public_contact() == $item['author-id']) {
1151                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1152                         }
1153
1154                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1155
1156                         // there can only be one activity verb per item so if we found anything, we can stop looking
1157                         return;
1158                 }
1159         }
1160 }
1161
1162 /**
1163  * Format the vote text for a profile item
1164  * @param int $cnt = number of people who vote the item
1165  * @param array $arr = array of pre-linked names of likers/dislikers
1166  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1167  * @param int $id  = item id
1168  * @return formatted text
1169  */
1170 function format_like($cnt, array $arr, $type, $id) {
1171         $o = '';
1172         $expanded = '';
1173
1174         if ($cnt == 1) {
1175                 $likers = $arr[0];
1176
1177                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1178                 // list which show all likers
1179                 switch ($type) {
1180                         case 'like' :
1181                                 $phrase = sprintf( t('%s likes this.'), $likers);
1182                                 break;
1183                         case 'dislike' :
1184                                 $phrase = sprintf( t('%s doesn\'t like this.'), $likers);
1185                                 break;
1186                         case 'attendyes' :
1187                                 $phrase = sprintf( t('%s attends.'), $likers);
1188                                 break;
1189                         case 'attendno' :
1190                                 $phrase = sprintf( t('%s doesn\'t attend.'), $likers);
1191                                 break;
1192                         case 'attendmaybe' :
1193                                 $phrase = sprintf( t('%s attends maybe.'), $likers);
1194                                 break;
1195                 }
1196         }
1197
1198         if ($cnt > 1) {
1199                 $total = count($arr);
1200                 if ($total >= MAX_LIKERS) {
1201                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1202                 }
1203                 if ($total < MAX_LIKERS) {
1204                         $last = t('and') . ' ' . $arr[count($arr)-1];
1205                         $arr2 = array_slice($arr, 0, -1);
1206                         $str = implode(', ', $arr2) . ' ' . $last;
1207                 }
1208                 if ($total >= MAX_LIKERS) {
1209                         $str = implode(', ', $arr);
1210                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
1211                 }
1212
1213                 $likers = $str;
1214
1215                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1216
1217                 switch ($type) {
1218                         case 'like':
1219                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> like this'), $spanatts, $cnt);
1220                                 $explikers = sprintf( t('%s like this.'), $likers);
1221                                 break;
1222                         case 'dislike':
1223                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t like this'), $spanatts, $cnt);
1224                                 $explikers = sprintf( t('%s don\'t like this.'), $likers);
1225                                 break;
1226                         case 'attendyes':
1227                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend'), $spanatts, $cnt);
1228                                 $explikers = sprintf( t('%s attend.'), $likers);
1229                                 break;
1230                         case 'attendno':
1231                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> don\'t attend'), $spanatts, $cnt);
1232                                 $explikers = sprintf( t('%s don\'t attend.'), $likers);
1233                                 break;
1234                         case 'attendmaybe':
1235                                 $phrase = sprintf( t('<span  %1$s>%2$d people</span> attend maybe'), $spanatts, $cnt);
1236                                 $explikers = sprintf( t('%s anttend maybe.'), $likers);
1237                                 break;
1238                 }
1239
1240                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1241         }
1242
1243         $phrase .= EOL ;
1244         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), array(
1245                 '$phrase' => $phrase,
1246                 '$type' => $type,
1247                 '$id' => $id
1248         ));
1249         $o .= $expanded;
1250
1251         return $o;
1252 }
1253
1254 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1255 {
1256         $o = '';
1257
1258         $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '';
1259
1260         $tpl = get_markup_template('jot-header.tpl');
1261         $a->page['htmlhead'] .= replace_macros($tpl, array(
1262                 '$newpost'   => 'true',
1263                 '$baseurl'   => System::baseUrl(true),
1264                 '$geotag'    => $geotag,
1265                 '$nickname'  => $x['nickname'],
1266                 '$ispublic'  => t('Visible to <strong>everybody</strong>'),
1267                 '$linkurl'   => t('Please enter a link URL:'),
1268                 '$vidurl'    => t("Please enter a video link/URL:"),
1269                 '$audurl'    => t("Please enter an audio link/URL:"),
1270                 '$term'      => t('Tag term:'),
1271                 '$fileas'    => t('Save to Folder:'),
1272                 '$whereareu' => t('Where are you right now?'),
1273                 '$delitems'  => t('Delete item(s)?')
1274         ));
1275
1276         $tpl = get_markup_template('jot-end.tpl');
1277         $a->page['end'] .= replace_macros($tpl, array(
1278                 '$newpost'   => 'true',
1279                 '$baseurl'   => System::baseUrl(true),
1280                 '$geotag'    => $geotag,
1281                 '$nickname'  => $x['nickname'],
1282                 '$ispublic'  => t('Visible to <strong>everybody</strong>'),
1283                 '$linkurl'   => t('Please enter a link URL:'),
1284                 '$vidurl'    => t("Please enter a video link/URL:"),
1285                 '$audurl'    => t("Please enter an audio link/URL:"),
1286                 '$term'      => t('Tag term:'),
1287                 '$fileas'    => t('Save to Folder:'),
1288                 '$whereareu' => t('Where are you right now?')
1289         ));
1290
1291         $jotplugins = '';
1292         call_hooks('jot_tool', $jotplugins);
1293
1294         // Private/public post links for the non-JS ACL form
1295         $private_post = 1;
1296         if (x($_REQUEST, 'public')) {
1297                 $private_post = 0;
1298         }
1299
1300         $query_str = $a->query_string;
1301         if (strpos($query_str, 'public=1') !== false) {
1302                 $query_str = str_replace(array('?public=1', '&public=1'), array('', ''), $query_str);
1303         }
1304
1305         /*
1306          * I think $a->query_string may never have ? in it, but I could be wrong
1307          * It looks like it's from the index.php?q=[etc] rewrite that the web
1308          * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1309          */
1310         if (strpos($query_str, '?') === false) {
1311                 $public_post_link = '?public=1';
1312         } else {
1313                 $public_post_link = '&public=1';
1314         }
1315
1316         // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1317         $tpl = get_markup_template("jot.tpl");
1318
1319         $o .= replace_macros($tpl,array(
1320                 '$return_path'  => $query_str,
1321                 '$action'       => 'item',
1322                 '$share'        => defaults($x, 'button', t('Share')),
1323                 '$upload'       => t('Upload photo'),
1324                 '$shortupload'  => t('upload photo'),
1325                 '$attach'       => t('Attach file'),
1326                 '$shortattach'  => t('attach file'),
1327                 '$weblink'      => t('Insert web link'),
1328                 '$shortweblink' => t('web link'),
1329                 '$video'        => t('Insert video link'),
1330                 '$shortvideo'   => t('video link'),
1331                 '$audio'        => t('Insert audio link'),
1332                 '$shortaudio'   => t('audio link'),
1333                 '$setloc'       => t('Set your location'),
1334                 '$shortsetloc'  => t('set location'),
1335                 '$noloc'        => t('Clear browser location'),
1336                 '$shortnoloc'   => t('clear location'),
1337                 '$title'        => defaults($x, 'title', ''),
1338                 '$placeholdertitle' => t('Set title'),
1339                 '$category'     => defaults($x, 'category', ''),
1340                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : '',
1341                 '$wait'         => t('Please wait'),
1342                 '$permset'      => t('Permission settings'),
1343                 '$shortpermset' => t('permissions'),
1344                 '$ptyp'         => $notes_cid ? 'note' : 'wall',
1345                 '$content'      => defaults($x, 'content', ''),
1346                 '$post_id'      => defaults($x, 'post_id', ''),
1347                 '$baseurl'      => System::baseUrl(true),
1348                 '$defloc'       => $x['default_location'],
1349                 '$visitor'      => $x['visitor'],
1350                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1351                 '$public'       => t('Public post'),
1352                 '$lockstate'    => $x['lockstate'],
1353                 '$bang'         => $x['bang'],
1354                 '$profile_uid'  => $x['profile_uid'],
1355                 '$preview'      => Feature::isEnabled($x['profile_uid'], 'preview') ? t('Preview') : '',
1356                 '$jotplugins'   => $jotplugins,
1357                 '$notes_cid'    => $notes_cid,
1358                 '$sourceapp'    => t($a->sourcename),
1359                 '$cancel'       => t('Cancel'),
1360                 '$rand_num'     => random_digits(12),
1361
1362                 // ACL permissions box
1363                 '$acl'           => $x['acl'],
1364                 '$acl_data'      => $x['acl_data'],
1365                 '$group_perms'   => t('Post to Groups'),
1366                 '$contact_perms' => t('Post to Contacts'),
1367                 '$private'       => t('Private post'),
1368                 '$is_private'    => $private_post,
1369                 '$public_link'   => $public_post_link,
1370
1371                 //jot nav tab (used in some themes)
1372                 '$message' => t('Message'),
1373                 '$browser' => t('Browser'),
1374         ));
1375
1376
1377         if ($popup == true) {
1378                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1379         }
1380
1381         return $o;
1382 }
1383
1384 /**
1385  * Plucks the children of the given parent from a given item list.
1386  *
1387  * @brief Plucks all the children in the given item list of the given parent
1388  *
1389  * @param array $item_list
1390  * @param array $parent
1391  * @param bool $recursive
1392  * @return type
1393  */
1394 function get_item_children(array &$item_list, array $parent, $recursive = true)
1395 {
1396         $children = [];
1397         foreach ($item_list as $i => $item) {
1398                 if ($item['id'] != $item['parent']) {
1399                         if ($recursive) {
1400                                 // Fallback to parent-uri if thr-parent is not set
1401                                 $thr_parent = $item['thr-parent'];
1402                                 if ($thr_parent == '') {
1403                                         $thr_parent = $item['parent-uri'];
1404                                 }
1405
1406                                 if ($thr_parent == $parent['uri']) {
1407                                         $item['children'] = get_item_children($item_list, $item);
1408                                         $children[] = $item;
1409                                         unset($item_list[$i]);
1410                                 }
1411                         } elseif ($item['parent'] == $parent['id']) {
1412                                 $children[] = $item;
1413                                 unset($item_list[$i]);
1414                         }
1415                 }
1416         }
1417         return $children;
1418 }
1419
1420 /**
1421  * @brief Recursively sorts a tree-like item array
1422  *
1423  * @param array $items
1424  * @return array
1425  */
1426 function sort_item_children(array $items)
1427 {
1428         $result = $items;
1429         usort($result, 'sort_thr_created_rev');
1430         foreach ($result as $k => $i) {
1431                 if (isset($result[$k]['children'])) {
1432                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1433                 }
1434         }
1435         return $result;
1436 }
1437
1438 /**
1439  * @brief Recursively add all children items at the top level of a list
1440  *
1441  * @param array $children List of items to append
1442  * @param array $item_list
1443  */
1444 function add_children_to_list(array $children, array &$item_list)
1445 {
1446         foreach ($children as $child) {
1447                 $item_list[] = $child;
1448                 if (isset($child['children'])) {
1449                         add_children_to_list($child['children'], $item_list);
1450                 }
1451         }
1452 }
1453
1454 /**
1455  * This recursive function takes the item tree structure created by conv_sort() and
1456  * flatten the extraneous depth levels when people reply sequentially, removing the
1457  * stairs effect in threaded conversations limiting the available content width.
1458  *
1459  * The basic principle is the following: if a post item has only one reply and is
1460  * the last reply of its parent, then the reply is moved to the parent.
1461  *
1462  * This process is rendered somewhat more complicated because items can be either
1463  * replies or likes, and these don't factor at all in the reply count/last reply.
1464  *
1465  * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1466  *
1467  * @param array $parent A tree-like array of items
1468  * @return array
1469  */
1470 function smart_flatten_conversation(array $parent)
1471 {
1472         if (! isset($parent['children']) || count($parent['children']) == 0) {
1473                 return $parent;
1474         }
1475
1476         // We use a for loop to ensure we process the newly-moved items
1477         for ($i = 0; $i < count($parent['children']); $i++) {
1478                 $child = $parent['children'][$i];
1479
1480                 if (isset($child['children']) && count($child['children'])) {
1481                         // This helps counting only the regular posts
1482                         $count_post_closure = function($var) {
1483                                 return $var['verb'] === ACTIVITY_POST;
1484                         };
1485
1486                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1487
1488                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1489
1490                         // If there's only one child's children post and this is the last child post
1491                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1492
1493                                 // Searches the post item in the children
1494                                 $j = 0;
1495                                 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1496                                         $j ++;
1497                                 }
1498
1499                                 $moved_item = $child['children'][$j];
1500                                 unset($parent['children'][$i]['children'][$j]);
1501                                 $parent['children'][] = $moved_item;
1502                         } else {
1503                                 $parent['children'][$i] = smart_flatten_conversation($child);
1504                         }
1505                 }
1506         }
1507
1508         return $parent;
1509 }
1510
1511
1512 /**
1513  * Expands a flat list of items into corresponding tree-like conversation structures,
1514  * sort the top-level posts either on "created" or "commented", and finally
1515  * append all the items at the top level (???)
1516  *
1517  * @brief Expands a flat item list into a conversation array for display
1518  *
1519  * @param array  $item_list A list of items belonging to one or more conversations
1520  * @param string $order     Either on "created" or "commented"
1521  * @return array
1522  */
1523 function conv_sort(array $item_list, $order)
1524 {
1525         $parents = [];
1526
1527         if (!(is_array($item_list) && count($item_list))) {
1528                 return $parents;
1529         }
1530
1531         $item_array = [];
1532
1533         // Dedupes the item list on the uri to prevent infinite loops
1534         foreach ($item_list as $item) {
1535                 $item_array[$item['uri']] = $item;
1536         }
1537
1538         // Extract the top level items
1539         foreach ($item_array as $item) {
1540                 if ($item['id'] == $item['parent']) {
1541                         $parents[] = $item;
1542                 }
1543         }
1544
1545         if (stristr($order, 'created')) {
1546                 usort($parents, 'sort_thr_created');
1547         } elseif (stristr($order, 'commented')) {
1548                 usort($parents, 'sort_thr_commented');
1549         }
1550
1551         /*
1552          * Plucks children from the item_array, second pass collects eventual orphan
1553          * items and add them as children of their top-level post.
1554          */
1555         foreach ($parents as $i => $parent) {
1556                 $parents[$i]['children'] =
1557                         array_merge(get_item_children($item_array, $parent, true),
1558                                 get_item_children($item_array, $parent, false));
1559         }
1560
1561         foreach ($parents as $i => $parent) {
1562                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1563         }
1564
1565         if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1566                 foreach ($parents as $i => $parent) {
1567                         $parents[$i] = smart_flatten_conversation($parent);
1568                 }
1569         }
1570
1571         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1572         /// However, this apparently ensures responses (likes, attendance) display (?!)
1573         foreach ($parents as $parent) {
1574                 if (count($parent['children'])) {
1575                         add_children_to_list($parent['children'], $parents);
1576                 }
1577         }
1578
1579         return $parents;
1580 }
1581
1582 /**
1583  * @brief usort() callback to sort item arrays by the created key
1584  *
1585  * @param array $a
1586  * @param array $b
1587  * @return int
1588  */
1589 function sort_thr_created(array $a, array $b)
1590 {
1591         return strcmp($b['created'], $a['created']);
1592 }
1593
1594 /**
1595  * @brief usort() callback to reverse sort item arrays by the created key
1596  *
1597  * @param array $a
1598  * @param array $b
1599  * @return int
1600  */
1601 function sort_thr_created_rev(array $a, array $b)
1602 {
1603         return strcmp($a['created'], $b['created']);
1604 }
1605
1606 /**
1607  * @brief usort() callback to sort item arrays by the commented key
1608  *
1609  * @param array $a
1610  * @param array $b
1611  * @return type
1612  */
1613 function sort_thr_commented(array $a, array $b)
1614 {
1615         return strcmp($b['commented'], $a['commented']);
1616 }
1617
1618 /// @TODO Add type-hint
1619 function render_location_dummy($item) {
1620         if ($item['location'] != "") {
1621                 return $item['location'];
1622         }
1623
1624         if ($item['coord'] != "") {
1625                 return $item['coord'];
1626         }
1627 }
1628
1629 /// @TODO Add type-hint
1630 function get_responses($conv_responses, $response_verbs, $ob, $item) {
1631         $ret = array();
1632         foreach ($response_verbs as $v) {
1633                 $ret[$v] = array();
1634                 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1635                 $ret[$v]['list']  = defaults($conv_responses[$v], $item['uri'] . '-l', '');
1636                 $ret[$v]['self']  = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1637                 if (count($ret[$v]['list']) > MAX_LIKERS) {
1638                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1639                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1640                                 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . t('View all') . '</b></a>');
1641                 } else {
1642                         $ret[$v]['list_part'] = '';
1643                 }
1644                 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1645                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1646         }
1647
1648         $count = 0;
1649         foreach ($ret as $key) {
1650                 if ($key['count'] == true) {
1651                         $count++;
1652                 }
1653         }
1654         $ret['count'] = $count;
1655
1656         return $ret;
1657 }
1658
1659 function get_response_button_text($v, $count) {
1660         switch ($v) {
1661                 case 'like':
1662                         return tt('Like', 'Likes', $count, 'noun');
1663                         break;
1664                 case 'dislike':
1665                         return tt('Dislike', 'Dislikes', $count, 'noun');
1666                         break;
1667                 case 'attendyes':
1668                         return tt('Attending', 'Attending', $count, 'noun');
1669                         break;
1670                 case 'attendno':
1671                         return tt('Not Attending', 'Not Attending', $count, 'noun');
1672                         break;
1673                 case 'attendmaybe':
1674                         return tt('Undecided', 'Undecided', $count, 'noun');
1675                         break;
1676         }
1677 }