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