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