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