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