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