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