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