]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge pull request #4339 from zeroadam/feature/Network
[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                 if (!$community_readonly) {
582                         $items = community_add_items($items);
583                 }
584                 $profile_owner = 0;
585                 if (!$update) {
586                         $live_update_div = '<div id="live-community"></div>' . "\r\n"
587                                 . "<script> var profile_uid = -1; var netargs = '" . substr($a->cmd, 10)
588                                 ."/?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
589                 }
590         } elseif ($mode === 'search') {
591                 $live_update_div = '<div id="live-search"></div>' . "\r\n";
592         }
593
594         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
595
596         if (!$update) {
597                 $_SESSION['return_url'] = $a->query_string;
598         }
599
600         $cb = ['items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview];
601         Addon::callHooks('conversation_start',$cb);
602
603         $items = $cb['items'];
604
605         $conv_responses = [
606                 'like' => ['title' => L10n::t('Likes','title')], 'dislike' => ['title' => L10n::t('Dislikes','title')],
607                 'attendyes' => ['title' => L10n::t('Attending','title')], 'attendno' => ['title' => L10n::t('Not attending','title')], 'attendmaybe' => ['title' => L10n::t('Might attend','title')]
608         ];
609
610         // array with html for each thread (parent+comments)
611         $threads = [];
612         $threadsid = -1;
613
614         $page_template = get_markup_template("conversation.tpl");
615
616         if ($items && count($items)) {
617                 $community_readonly = ($mode === 'community');
618
619                 // Currently behind a config value. This allows the commenting and sharing of every public item.
620                 if (Config::get('system', 'comment_public')) {
621                         if ($mode === 'community') {
622                                 $community_readonly = false;
623                                 $writable = true;
624                         } else {
625                                 $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
626                         }
627                 } else {
628                         $writable = false;
629                 }
630
631                 if (!local_user()) {
632                         $writable = false;
633                 }
634
635                 if (in_array($mode, ['network-new', 'search', 'contact-posts']) || $community_readonly) {
636
637                         /*
638                          * "New Item View" on network page or search page results
639                          * - just loop through the items and format them minimally for display
640                          */
641
642                         /// @TODO old lost code?
643                         // $tpl = get_markup_template('search_item.tpl');
644                         $tpl = 'search_item.tpl';
645
646                         foreach ($items as $item) {
647
648                                 if ($arr_blocked) {
649                                         $blocked = false;
650                                         foreach ($arr_blocked as $b) {
651                                                 if ($b && link_compare($item['author-link'], $b)) {
652                                                         $blocked = true;
653                                                         break;
654                                                 }
655                                         }
656                                         if ($blocked) {
657                                                 continue;
658                                         }
659                                 }
660
661
662                                 $threadsid++;
663
664                                 $owner_url   = '';
665                                 $owner_name  = '';
666                                 $sparkle     = '';
667
668                                 // prevent private email from leaking.
669                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
670                                         continue;
671                                 }
672
673                                 $profile_name = ((strlen($item['author-name'])) ? $item['author-name'] : $item['name']);
674                                 if ($item['author-link'] && (! $item['author-name'])) {
675                                         $profile_name = $item['author-link'];
676                                 }
677
678                                 $tags = [];
679                                 $hashtags = [];
680                                 $mentions = [];
681
682                                 $searchpath = System::baseUrl()."/search?tag=";
683
684                                 $taglist = dba::select('term', ['type', 'term', 'url'],
685                                                         ["`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION],
686                                                         ['order' => ['tid']]);
687
688                                 while ($tag = dba::fetch($taglist)) {
689                                         if ($tag["url"] == "") {
690                                                 $tag["url"] = $searchpath . strtolower($tag["term"]);
691                                         }
692
693                                         $tag["url"] = best_link_url($item, $sp, $tag["url"]);
694
695                                         if ($tag["type"] == TERM_HASHTAG) {
696                                                 $hashtags[] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
697                                                 $prefix = "#";
698                                         } elseif ($tag["type"] == TERM_MENTION) {
699                                                 $mentions[] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
700                                                 $prefix = "@";
701                                         }
702                                         $tags[] = $prefix."<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
703                                 }
704                                 dba::close($taglist);
705
706                                 $sp = false;
707                                 $profile_link = best_link_url($item, $sp);
708                                 if ($profile_link === 'mailbox') {
709                                         $profile_link = '';
710                                 }
711
712                                 if ($sp) {
713                                         $sparkle = ' sparkle';
714                                 } else {
715                                         $profile_link = Profile::zrl($profile_link);
716                                 }
717
718                                 if (!x($item, 'author-thumb') || ($item['author-thumb'] == "")) {
719                                         $author_contact = Contact::getDetailsByURL($item['author-link'], $profile_owner);
720                                         if ($author_contact["thumb"]) {
721                                                 $item['author-thumb'] = $author_contact["thumb"];
722                                         } else {
723                                                 $item['author-thumb'] = $item['author-avatar'];
724                                         }
725                                 }
726
727                                 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
728                                         $owner_contact = Contact::getDetailsByURL($item['owner-link'], $profile_owner);
729                                         if ($owner_contact["thumb"]) {
730                                                 $item['owner-thumb'] = $owner_contact["thumb"];
731                                         } else {
732                                                 $item['owner-thumb'] = $item['owner-avatar'];
733                                         }
734                                 }
735
736                                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
737                                 Addon::callHooks('render_location',$locate);
738
739                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
740
741                                 localize_item($item);
742                                 if ($mode === 'network-new') {
743                                         $dropping = true;
744                                 } else {
745                                         $dropping = false;
746                                 }
747
748                                 $drop = [
749                                         'dropping' => $dropping,
750                                         'pagedrop' => $page_dropping,
751                                         'select' => L10n::t('Select'),
752                                         'delete' => L10n::t('Delete'),
753                                 ];
754
755                                 $star = false;
756                                 $isstarred = "unstarred";
757
758                                 $lock = false;
759                                 $likebuttons = false;
760
761                                 $body = prepare_body($item, true, $preview);
762
763                                 list($categories, $folders) = get_cats_and_terms($item);
764
765                                 $profile_name_e = $profile_name;
766                                 $item['title_e'] = $item['title'];
767                                 $body_e = $body;
768                                 $tags_e = $tags;
769                                 $hashtags_e = $hashtags;
770                                 $mentions_e = $mentions;
771                                 $location_e = $location;
772                                 $owner_name_e = $owner_name;
773
774                                 if ($item['item_network'] == "") {
775                                         $item['item_network'] = $item['network'];
776                                 }
777
778                                 $tmp_item = [
779                                         'template' => $tpl,
780                                         'id' => (($preview) ? 'P0' : $item['item_id']),
781                                         'guid' => (($preview) ? 'Q0' : $item['guid']),
782                                         'network' => $item['item_network'],
783                                         'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
784                                         'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
785                                         'profile_url' => $profile_link,
786                                         'item_photo_menu' => item_photo_menu($item),
787                                         'name' => $profile_name_e,
788                                         'sparkle' => $sparkle,
789                                         'lock' => $lock,
790                                         'thumb' => System::removedBaseUrl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
791                                         'title' => $item['title_e'],
792                                         'body' => $body_e,
793                                         'tags' => $tags_e,
794                                         'hashtags' => $hashtags_e,
795                                         'mentions' => $mentions_e,
796                                         'txt_cats' => L10n::t('Categories:'),
797                                         'txt_folders' => L10n::t('Filed under:'),
798                                         'has_cats' => ((count($categories)) ? 'true' : ''),
799                                         'has_folders' => ((count($folders)) ? 'true' : ''),
800                                         'categories' => $categories,
801                                         'folders' => $folders,
802                                         'text' => strip_tags($body_e),
803                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
804                                         'ago' => (($item['app']) ? L10n::t('%s from %s', relative_date($item['created']),$item['app']) : relative_date($item['created'])),
805                                         'location' => $location_e,
806                                         'indent' => '',
807                                         'owner_name' => $owner_name_e,
808                                         'owner_url' => $owner_url,
809                                         'owner_photo' => System::removedBaseUrl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
810                                         'plink' => get_plink($item),
811                                         'edpost' => false,
812                                         'isstarred' => $isstarred,
813                                         'star' => $star,
814                                         'drop' => $drop,
815                                         'vote' => $likebuttons,
816                                         'like' => '',
817                                         'dislike' => '',
818                                         'comment' => '',
819                                         'conv' => (($preview) ? '' : ['href'=> 'display/'.$item['guid'], 'title'=> L10n::t('View in context')]),
820                                         'previewing' => $previewing,
821                                         'wait' => L10n::t('Please wait'),
822                                         'thread_level' => 1,
823                                 ];
824
825                                 $arr = ['item' => $item, 'output' => $tmp_item];
826                                 Addon::callHooks('display_item', $arr);
827
828                                 $threads[$threadsid]['id'] = $item['item_id'];
829                                 $threads[$threadsid]['network'] = $item['item_network'];
830                                 $threads[$threadsid]['items'] = [$arr['output']];
831
832                         }
833                 } else {
834                         // Normal View
835                         $page_template = get_markup_template("threaded_conversation.tpl");
836
837                         $conv = new Thread($mode, $preview, $writable);
838
839                         /*
840                          * get all the topmost parents
841                          * this shouldn't be needed, as we should have only them in our array
842                          * But for now, this array respects the old style, just in case
843                          */
844                         foreach ($items as $item) {
845                                 if ($arr_blocked) {
846                                         $blocked = false;
847                                         foreach ($arr_blocked as $b) {
848                                                 if ($b && link_compare($item['author-link'], $b)) {
849                                                         $blocked = true;
850                                                         break;
851                                                 }
852                                         }
853                                         if ($blocked) {
854                                                 continue;
855                                         }
856                                 }
857
858                                 // Can we put this after the visibility check?
859                                 builtin_activity_puller($item, $conv_responses);
860
861                                 // Only add what is visible
862                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
863                                         continue;
864                                 }
865
866                                 if (! visible_activity($item)) {
867                                         continue;
868                                 }
869
870                                 Addon::callHooks('display_item', $arr);
871
872                                 $item['pagedrop'] = $page_dropping;
873
874                                 if ($item['id'] == $item['parent']) {
875                                         $item_object = new Post($item);
876                                         $conv->addParent($item_object);
877                                 }
878                         }
879
880                         $threads = $conv->getTemplateData($conv_responses);
881                         if (!$threads) {
882                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
883                                 $threads = [];
884                         }
885                 }
886         }
887
888         $o = replace_macros($page_template, [
889                 '$baseurl' => System::baseUrl($ssl_state),
890                 '$return_path' => $a->query_string,
891                 '$live_update' => $live_update_div,
892                 '$remove' => L10n::t('remove'),
893                 '$mode' => $mode,
894                 '$user' => $a->user,
895                 '$threads' => $threads,
896                 '$dropping' => ($page_dropping && Feature::isEnabled(local_user(), 'multi_delete') ? L10n::t('Delete Selected Items') : False),
897         ]);
898
899         return $o;
900 }
901
902 /**
903  * @brief Add comments to top level entries that had been fetched before
904  *
905  * The system will fetch the comments for the local user whenever possible.
906  * This behaviour is currently needed to allow commenting on Friendica posts.
907  *
908  * @param array $parents Parent items
909  *
910  * @return array items with parents and comments
911  */
912 function community_add_items($parents) {
913         $max_comments = Config::get("system", "max_comments", 100);
914
915         $items = [];
916
917         foreach ($parents AS $parent) {
918                 $thread_items = dba::p(item_query()." AND `item`.`uid` = ?
919                         AND `item`.`parent-uri` = ?
920                         ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
921                         local_user(),
922                         $parent['uri']
923                 );
924                 $comments = dba::inArray($thread_items);
925
926                 // Check if the original item is in the result.
927                 // When commenting from the community page there can be incomplete threads
928                 if (count($comments) > 0) {
929                         $parent_found = false;
930                         foreach ($comments as $comment) {
931                                 if ($comment['uri'] == $comment['parent-uri']) {
932                                         $parent_found = true;
933                                         break;
934                                 }
935                         }
936                         if (!$parent_found) {
937                                 $comments = [];
938                         }
939                 }
940
941                 if (count($comments) == 0) {
942                         $thread_items = dba::p(item_query()." AND `item`.`uid` = 0
943                                 AND `item`.`parent-uri` = ?
944                                 ORDER BY `item`.`commented` DESC LIMIT ".intval($max_comments + 1),
945                                 $parent['uri']
946                         );
947                         $comments = dba::inArray($thread_items);
948                 }
949
950                 if (count($comments) != 0) {
951                         $items = array_merge($items, $comments);
952                 }
953         }
954
955         foreach ($items as $index => $item) {
956                 if ($item['uid'] == 0) {
957                         $items[$index]['writable'] = in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
958                 }
959         }
960
961         $items = conv_sort($items, "`commented`");
962
963         return $items;
964 }
965
966 function best_link_url($item, &$sparkle, $url = '') {
967
968         $best_url = '';
969         $sparkle  = false;
970
971         $clean_url = normalise_link($item['author-link']);
972
973         if (local_user()) {
974                 $condition = [
975                         'network' => NETWORK_DFRN,
976                         'uid' => local_user(),
977                         'nurl' => normalise_link($clean_url),
978                         'pending' => false
979                 ];
980                 $contact = dba::selectFirst('contact', ['id'], $condition);
981                 if (DBM::is_result($contact)) {
982                         $best_url = 'redir/' . $contact['id'];
983                         $sparkle = true;
984                         if ($url != '') {
985                                 $hostname = get_app()->get_hostname();
986                                 if (!strstr($url, $hostname)) {
987                                         $best_url .= "?url=".$url;
988                                 } else {
989                                         $best_url = $url;
990                                 }
991                         }
992                 }
993         }
994         if (! $best_url) {
995                 if ($url != '') {
996                         $best_url = $url;
997                 } elseif (strlen($item['author-link'])) {
998                         $best_url = $item['author-link'];
999                 } else {
1000                         $best_url = $item['url'];
1001                 }
1002         }
1003
1004         return $best_url;
1005 }
1006
1007
1008 function item_photo_menu($item) {
1009         $sub_link = '';
1010         $poke_link = '';
1011         $contact_url = '';
1012         $pm_url = '';
1013         $status_link = '';
1014         $photos_link = '';
1015         $posts_link = '';
1016
1017         if ((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
1018                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
1019         }
1020
1021         $sparkle = false;
1022         $profile_link = best_link_url($item, $sparkle);
1023         if ($profile_link === 'mailbox') {
1024                 $profile_link = '';
1025         }
1026
1027         $cid = 0;
1028         $network = '';
1029         $rel = 0;
1030         $condition = ['uid' => local_user(), 'nurl' => normalise_link($item['author-link'])];
1031         $contact = dba::selectFirst('contact', ['id', 'network', 'rel'], $condition);
1032         if (DBM::is_result($contact)) {
1033                 $cid = $contact['id'];
1034                 $network = $contact['network'];
1035                 $rel = $contact['rel'];
1036         }
1037
1038         if ($sparkle) {
1039                 $status_link = $profile_link . '?url=status';
1040                 $photos_link = $profile_link . '?url=photos';
1041                 $profile_link = $profile_link . '?url=profile';
1042         } else {
1043                 $profile_link = Profile::zrl($profile_link);
1044         }
1045
1046         if ($cid && !$item['self']) {
1047                 $poke_link = 'poke/?f=&c=' . $cid;
1048                 $contact_url = 'contacts/' . $cid;
1049                 $posts_link = 'contacts/' . $cid . '/posts';
1050
1051                 if (in_array($network, [NETWORK_DFRN, NETWORK_DIASPORA])) {
1052                         $pm_url = 'message/new/' . $cid;
1053                 }
1054         }
1055
1056         if (local_user()) {
1057                 $menu = [
1058                         L10n::t('Follow Thread') => $sub_link,
1059                         L10n::t('View Status') => $status_link,
1060                         L10n::t('View Profile') => $profile_link,
1061                         L10n::t('View Photos') => $photos_link,
1062                         L10n::t('Network Posts') => $posts_link,
1063                         L10n::t('View Contact') => $contact_url,
1064                         L10n::t('Send PM') => $pm_url
1065                 ];
1066
1067                 if ($network == NETWORK_DFRN) {
1068                         $menu[L10n::t("Poke")] = $poke_link;
1069                 }
1070
1071                 if ((($cid == 0) || ($rel == CONTACT_IS_FOLLOWER)) &&
1072                         in_array($item['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
1073                         $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
1074                 }
1075         } else {
1076                 $menu = [L10n::t('View Profile') => $item['author-link']];
1077         }
1078
1079         $args = ['item' => $item, 'menu' => $menu];
1080
1081         Addon::callHooks('item_photo_menu', $args);
1082
1083         $menu = $args['menu'];
1084
1085         $o = '';
1086         foreach ($menu as $k => $v) {
1087                 if (strpos($v, 'javascript:') === 0) {
1088                         $v = substr($v, 11);
1089                         $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1090                 } elseif ($v!='') {
1091                         $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
1092                 }
1093         }
1094         return $o;
1095 }
1096
1097 /**
1098  * @brief Checks item to see if it is one of the builtin activities (like/dislike, event attendance, consensus items, etc.)
1099  * Increments the count of each matching activity and adds a link to the author as needed.
1100  *
1101  * @param array $item
1102  * @param array &$conv_responses (already created with builtin activity structure)
1103  * @return void
1104  */
1105 function builtin_activity_puller($item, &$conv_responses) {
1106         foreach ($conv_responses as $mode => $v) {
1107                 $url = '';
1108                 $sparkle = '';
1109
1110                 switch ($mode) {
1111                         case 'like':
1112                                 $verb = ACTIVITY_LIKE;
1113                                 break;
1114                         case 'dislike':
1115                                 $verb = ACTIVITY_DISLIKE;
1116                                 break;
1117                         case 'attendyes':
1118                                 $verb = ACTIVITY_ATTEND;
1119                                 break;
1120                         case 'attendno':
1121                                 $verb = ACTIVITY_ATTENDNO;
1122                                 break;
1123                         case 'attendmaybe':
1124                                 $verb = ACTIVITY_ATTENDMAYBE;
1125                                 break;
1126                         default:
1127                                 return;
1128                 }
1129
1130                 if ((activity_match($item['verb'], $verb)) && ($item['id'] != $item['parent'])) {
1131                         $url = $item['author-link'];
1132                         if ((local_user()) && (local_user() == $item['uid']) && ($item['network'] === NETWORK_DFRN) && (! $item['self']) && (link_compare($item['author-link'], $item['url']))) {
1133                                 $url = 'redir/' . $item['contact-id'];
1134                                 $sparkle = ' class="sparkle" ';
1135                         } else {
1136                                 $url = Profile::zrl($url);
1137                         }
1138
1139                         $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
1140
1141                         if (! $item['thr-parent']) {
1142                                 $item['thr-parent'] = $item['parent-uri'];
1143                         }
1144
1145                         if (! ((isset($conv_responses[$mode][$item['thr-parent'] . '-l']))
1146                                 && (is_array($conv_responses[$mode][$item['thr-parent'] . '-l'])))) {
1147                                 $conv_responses[$mode][$item['thr-parent'] . '-l'] = [];
1148                         }
1149
1150                         // only list each unique author once
1151                         if (in_array($url,$conv_responses[$mode][$item['thr-parent'] . '-l'])) {
1152                                 continue;
1153                         }
1154
1155                         if (! isset($conv_responses[$mode][$item['thr-parent']])) {
1156                                 $conv_responses[$mode][$item['thr-parent']] = 1;
1157                         } else {
1158                                 $conv_responses[$mode][$item['thr-parent']] ++;
1159                         }
1160
1161                         if (public_contact() == $item['author-id']) {
1162                                 $conv_responses[$mode][$item['thr-parent'] . '-self'] = 1;
1163                         }
1164
1165                         $conv_responses[$mode][$item['thr-parent'] . '-l'][] = $url;
1166
1167                         // there can only be one activity verb per item so if we found anything, we can stop looking
1168                         return;
1169                 }
1170         }
1171 }
1172
1173 /**
1174  * Format the vote text for a profile item
1175  * @param int $cnt = number of people who vote the item
1176  * @param array $arr = array of pre-linked names of likers/dislikers
1177  * @param string $type = one of 'like, 'dislike', 'attendyes', 'attendno', 'attendmaybe'
1178  * @param int $id  = item id
1179  * @return formatted text
1180  */
1181 function format_like($cnt, array $arr, $type, $id) {
1182         $o = '';
1183         $expanded = '';
1184
1185         if ($cnt == 1) {
1186                 $likers = $arr[0];
1187
1188                 // Phrase if there is only one liker. In other cases it will be uses for the expanded
1189                 // list which show all likers
1190                 switch ($type) {
1191                         case 'like' :
1192                                 $phrase = L10n::t('%s likes this.', $likers);
1193                                 break;
1194                         case 'dislike' :
1195                                 $phrase = L10n::t('%s doesn\'t like this.', $likers);
1196                                 break;
1197                         case 'attendyes' :
1198                                 $phrase = L10n::t('%s attends.', $likers);
1199                                 break;
1200                         case 'attendno' :
1201                                 $phrase = L10n::t('%s doesn\'t attend.', $likers);
1202                                 break;
1203                         case 'attendmaybe' :
1204                                 $phrase = L10n::t('%s attends maybe.', $likers);
1205                                 break;
1206                 }
1207         }
1208
1209         if ($cnt > 1) {
1210                 $total = count($arr);
1211                 if ($total >= MAX_LIKERS) {
1212                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1213                 }
1214                 if ($total < MAX_LIKERS) {
1215                         $last = L10n::t('and') . ' ' . $arr[count($arr)-1];
1216                         $arr2 = array_slice($arr, 0, -1);
1217                         $str = implode(', ', $arr2) . ' ' . $last;
1218                 }
1219                 if ($total >= MAX_LIKERS) {
1220                         $str = implode(', ', $arr);
1221                         $str .= L10n::t('and %d other people', $total - MAX_LIKERS );
1222                 }
1223
1224                 $likers = $str;
1225
1226                 $spanatts = "class=\"fakelink\" onclick=\"openClose('{$type}list-$id');\"";
1227
1228                 switch ($type) {
1229                         case 'like':
1230                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> like this', $spanatts, $cnt);
1231                                 $explikers = L10n::t('%s like this.', $likers);
1232                                 break;
1233                         case 'dislike':
1234                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> don\'t like this', $spanatts, $cnt);
1235                                 $explikers = L10n::t('%s don\'t like this.', $likers);
1236                                 break;
1237                         case 'attendyes':
1238                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> attend', $spanatts, $cnt);
1239                                 $explikers = L10n::t('%s attend.', $likers);
1240                                 break;
1241                         case 'attendno':
1242                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> don\'t attend', $spanatts, $cnt);
1243                                 $explikers = L10n::t('%s don\'t attend.', $likers);
1244                                 break;
1245                         case 'attendmaybe':
1246                                 $phrase = L10n::t('<span  %1$s>%2$d people</span> attend maybe', $spanatts, $cnt);
1247                                 $explikers = L10n::t('%s anttend maybe.', $likers);
1248                                 break;
1249                 }
1250
1251                 $expanded .= "\t" . '<div class="wall-item-' . $type . '-expanded" id="' . $type . 'list-' . $id . '" style="display: none;" >' . $explikers . EOL . '</div>';
1252         }
1253
1254         $phrase .= EOL ;
1255         $o .= replace_macros(get_markup_template('voting_fakelink.tpl'), [
1256                 '$phrase' => $phrase,
1257                 '$type' => $type,
1258                 '$id' => $id
1259         ]);
1260         $o .= $expanded;
1261
1262         return $o;
1263 }
1264
1265 function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
1266 {
1267         $o = '';
1268
1269         $geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), []) : '';
1270
1271         $tpl = get_markup_template('jot-header.tpl');
1272         $a->page['htmlhead'] .= replace_macros($tpl, [
1273                 '$newpost'   => 'true',
1274                 '$baseurl'   => System::baseUrl(true),
1275                 '$geotag'    => $geotag,
1276                 '$nickname'  => $x['nickname'],
1277                 '$ispublic'  => L10n::t('Visible to <strong>everybody</strong>'),
1278                 '$linkurl'   => L10n::t('Please enter a link URL:'),
1279                 '$vidurl'    => L10n::t("Please enter a video link/URL:"),
1280                 '$audurl'    => L10n::t("Please enter an audio link/URL:"),
1281                 '$term'      => L10n::t('Tag term:'),
1282                 '$fileas'    => L10n::t('Save to Folder:'),
1283                 '$whereareu' => L10n::t('Where are you right now?'),
1284                 '$delitems'  => L10n::t("Delete item\x28s\x29?")
1285         ]);
1286
1287         $tpl = get_markup_template('jot-end.tpl');
1288         $a->page['end'] .= replace_macros($tpl, [
1289                 '$newpost'   => 'true',
1290                 '$baseurl'   => System::baseUrl(true),
1291                 '$geotag'    => $geotag,
1292                 '$nickname'  => $x['nickname'],
1293                 '$ispublic'  => L10n::t('Visible to <strong>everybody</strong>'),
1294                 '$linkurl'   => L10n::t('Please enter a link URL:'),
1295                 '$vidurl'    => L10n::t("Please enter a video link/URL:"),
1296                 '$audurl'    => L10n::t("Please enter an audio link/URL:"),
1297                 '$term'      => L10n::t('Tag term:'),
1298                 '$fileas'    => L10n::t('Save to Folder:'),
1299                 '$whereareu' => L10n::t('Where are you right now?')
1300         ]);
1301
1302         $jotplugins = '';
1303         Addon::callHooks('jot_tool', $jotplugins);
1304
1305         // Private/public post links for the non-JS ACL form
1306         $private_post = 1;
1307         if (x($_REQUEST, 'public')) {
1308                 $private_post = 0;
1309         }
1310
1311         $query_str = $a->query_string;
1312         if (strpos($query_str, 'public=1') !== false) {
1313                 $query_str = str_replace(['?public=1', '&public=1'], ['', ''], $query_str);
1314         }
1315
1316         /*
1317          * I think $a->query_string may never have ? in it, but I could be wrong
1318          * It looks like it's from the index.php?q=[etc] rewrite that the web
1319          * server does, which converts any ? to &, e.g. suggest&ignore=61 for suggest?ignore=61
1320          */
1321         if (strpos($query_str, '?') === false) {
1322                 $public_post_link = '?public=1';
1323         } else {
1324                 $public_post_link = '&public=1';
1325         }
1326
1327         // $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
1328         $tpl = get_markup_template("jot.tpl");
1329
1330         $o .= replace_macros($tpl,[
1331                 '$return_path'  => $query_str,
1332                 '$action'       => 'item',
1333                 '$share'        => defaults($x, 'button', L10n::t('Share')),
1334                 '$upload'       => L10n::t('Upload photo'),
1335                 '$shortupload'  => L10n::t('upload photo'),
1336                 '$attach'       => L10n::t('Attach file'),
1337                 '$shortattach'  => L10n::t('attach file'),
1338                 '$weblink'      => L10n::t('Insert web link'),
1339                 '$shortweblink' => L10n::t('web link'),
1340                 '$video'        => L10n::t('Insert video link'),
1341                 '$shortvideo'   => L10n::t('video link'),
1342                 '$audio'        => L10n::t('Insert audio link'),
1343                 '$shortaudio'   => L10n::t('audio link'),
1344                 '$setloc'       => L10n::t('Set your location'),
1345                 '$shortsetloc'  => L10n::t('set location'),
1346                 '$noloc'        => L10n::t('Clear browser location'),
1347                 '$shortnoloc'   => L10n::t('clear location'),
1348                 '$title'        => defaults($x, 'title', ''),
1349                 '$placeholdertitle' => L10n::t('Set title'),
1350                 '$category'     => defaults($x, 'category', ''),
1351                 '$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? L10n::t("Categories \x28comma-separated list\x29") : '',
1352                 '$wait'         => L10n::t('Please wait'),
1353                 '$permset'      => L10n::t('Permission settings'),
1354                 '$shortpermset' => L10n::t('permissions'),
1355                 '$ptyp'         => $notes_cid ? 'note' : 'wall',
1356                 '$content'      => defaults($x, 'content', ''),
1357                 '$post_id'      => defaults($x, 'post_id', ''),
1358                 '$baseurl'      => System::baseUrl(true),
1359                 '$defloc'       => $x['default_location'],
1360                 '$visitor'      => $x['visitor'],
1361                 '$pvisit'       => $notes_cid ? 'none' : $x['visitor'],
1362                 '$public'       => L10n::t('Public post'),
1363                 '$lockstate'    => $x['lockstate'],
1364                 '$bang'         => $x['bang'],
1365                 '$profile_uid'  => $x['profile_uid'],
1366                 '$preview'      => Feature::isEnabled($x['profile_uid'], 'preview') ? L10n::t('Preview') : '',
1367                 '$jotplugins'   => $jotplugins,
1368                 '$notes_cid'    => $notes_cid,
1369                 '$sourceapp'    => L10n::t($a->sourcename),
1370                 '$cancel'       => L10n::t('Cancel'),
1371                 '$rand_num'     => random_digits(12),
1372
1373                 // ACL permissions box
1374                 '$acl'           => $x['acl'],
1375                 '$group_perms'   => L10n::t('Post to Groups'),
1376                 '$contact_perms' => L10n::t('Post to Contacts'),
1377                 '$private'       => L10n::t('Private post'),
1378                 '$is_private'    => $private_post,
1379                 '$public_link'   => $public_post_link,
1380
1381                 //jot nav tab (used in some themes)
1382                 '$message' => L10n::t('Message'),
1383                 '$browser' => L10n::t('Browser'),
1384         ]);
1385
1386
1387         if ($popup == true) {
1388                 $o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
1389         }
1390
1391         return $o;
1392 }
1393
1394 /**
1395  * Plucks the children of the given parent from a given item list.
1396  *
1397  * @brief Plucks all the children in the given item list of the given parent
1398  *
1399  * @param array $item_list
1400  * @param array $parent
1401  * @param bool $recursive
1402  * @return type
1403  */
1404 function get_item_children(array &$item_list, array $parent, $recursive = true)
1405 {
1406         $children = [];
1407         foreach ($item_list as $i => $item) {
1408                 if ($item['id'] != $item['parent']) {
1409                         if ($recursive) {
1410                                 // Fallback to parent-uri if thr-parent is not set
1411                                 $thr_parent = $item['thr-parent'];
1412                                 if ($thr_parent == '') {
1413                                         $thr_parent = $item['parent-uri'];
1414                                 }
1415
1416                                 if ($thr_parent == $parent['uri']) {
1417                                         $item['children'] = get_item_children($item_list, $item);
1418                                         $children[] = $item;
1419                                         unset($item_list[$i]);
1420                                 }
1421                         } elseif ($item['parent'] == $parent['id']) {
1422                                 $children[] = $item;
1423                                 unset($item_list[$i]);
1424                         }
1425                 }
1426         }
1427         return $children;
1428 }
1429
1430 /**
1431  * @brief Recursively sorts a tree-like item array
1432  *
1433  * @param array $items
1434  * @return array
1435  */
1436 function sort_item_children(array $items)
1437 {
1438         $result = $items;
1439         usort($result, 'sort_thr_created_rev');
1440         foreach ($result as $k => $i) {
1441                 if (isset($result[$k]['children'])) {
1442                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
1443                 }
1444         }
1445         return $result;
1446 }
1447
1448 /**
1449  * @brief Recursively add all children items at the top level of a list
1450  *
1451  * @param array $children List of items to append
1452  * @param array $item_list
1453  */
1454 function add_children_to_list(array $children, array &$item_list)
1455 {
1456         foreach ($children as $child) {
1457                 $item_list[] = $child;
1458                 if (isset($child['children'])) {
1459                         add_children_to_list($child['children'], $item_list);
1460                 }
1461         }
1462 }
1463
1464 /**
1465  * This recursive function takes the item tree structure created by conv_sort() and
1466  * flatten the extraneous depth levels when people reply sequentially, removing the
1467  * stairs effect in threaded conversations limiting the available content width.
1468  *
1469  * The basic principle is the following: if a post item has only one reply and is
1470  * the last reply of its parent, then the reply is moved to the parent.
1471  *
1472  * This process is rendered somewhat more complicated because items can be either
1473  * replies or likes, and these don't factor at all in the reply count/last reply.
1474  *
1475  * @brief Selectively flattens a tree-like item structure to prevent threading stairs
1476  *
1477  * @param array $parent A tree-like array of items
1478  * @return array
1479  */
1480 function smart_flatten_conversation(array $parent)
1481 {
1482         if (! isset($parent['children']) || count($parent['children']) == 0) {
1483                 return $parent;
1484         }
1485
1486         // We use a for loop to ensure we process the newly-moved items
1487         for ($i = 0; $i < count($parent['children']); $i++) {
1488                 $child = $parent['children'][$i];
1489
1490                 if (isset($child['children']) && count($child['children'])) {
1491                         // This helps counting only the regular posts
1492                         $count_post_closure = function($var) {
1493                                 return $var['verb'] === ACTIVITY_POST;
1494                         };
1495
1496                         $child_post_count = count(array_filter($child['children'], $count_post_closure));
1497
1498                         $remaining_post_count = count(array_filter(array_slice($parent['children'], $i), $count_post_closure));
1499
1500                         // If there's only one child's children post and this is the last child post
1501                         if ($child_post_count == 1 && $remaining_post_count == 1) {
1502
1503                                 // Searches the post item in the children
1504                                 $j = 0;
1505                                 while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) {
1506                                         $j ++;
1507                                 }
1508
1509                                 $moved_item = $child['children'][$j];
1510                                 unset($parent['children'][$i]['children'][$j]);
1511                                 $parent['children'][] = $moved_item;
1512                         } else {
1513                                 $parent['children'][$i] = smart_flatten_conversation($child);
1514                         }
1515                 }
1516         }
1517
1518         return $parent;
1519 }
1520
1521
1522 /**
1523  * Expands a flat list of items into corresponding tree-like conversation structures,
1524  * sort the top-level posts either on "created" or "commented", and finally
1525  * append all the items at the top level (???)
1526  *
1527  * @brief Expands a flat item list into a conversation array for display
1528  *
1529  * @param array  $item_list A list of items belonging to one or more conversations
1530  * @param string $order     Either on "created" or "commented"
1531  * @return array
1532  */
1533 function conv_sort(array $item_list, $order)
1534 {
1535         $parents = [];
1536
1537         if (!(is_array($item_list) && count($item_list))) {
1538                 return $parents;
1539         }
1540
1541         $item_array = [];
1542
1543         // Dedupes the item list on the uri to prevent infinite loops
1544         foreach ($item_list as $item) {
1545                 $item_array[$item['uri']] = $item;
1546         }
1547
1548         // Extract the top level items
1549         foreach ($item_array as $item) {
1550                 if ($item['id'] == $item['parent']) {
1551                         $parents[] = $item;
1552                 }
1553         }
1554
1555         if (stristr($order, 'created')) {
1556                 usort($parents, 'sort_thr_created');
1557         } elseif (stristr($order, 'commented')) {
1558                 usort($parents, 'sort_thr_commented');
1559         }
1560
1561         /*
1562          * Plucks children from the item_array, second pass collects eventual orphan
1563          * items and add them as children of their top-level post.
1564          */
1565         foreach ($parents as $i => $parent) {
1566                 $parents[$i]['children'] =
1567                         array_merge(get_item_children($item_array, $parent, true),
1568                                 get_item_children($item_array, $parent, false));
1569         }
1570
1571         foreach ($parents as $i => $parent) {
1572                 $parents[$i]['children'] = sort_item_children($parents[$i]['children']);
1573         }
1574
1575         if (PConfig::get(local_user(), 'system', 'smart_threading', 0)) {
1576                 foreach ($parents as $i => $parent) {
1577                         $parents[$i] = smart_flatten_conversation($parent);
1578                 }
1579         }
1580
1581         /// @TODO: Stop recusrsively adding all children back to the top level (!!!)
1582         /// However, this apparently ensures responses (likes, attendance) display (?!)
1583         foreach ($parents as $parent) {
1584                 if (count($parent['children'])) {
1585                         add_children_to_list($parent['children'], $parents);
1586                 }
1587         }
1588
1589         return $parents;
1590 }
1591
1592 /**
1593  * @brief usort() callback to 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(array $a, array $b)
1600 {
1601         return strcmp($b['created'], $a['created']);
1602 }
1603
1604 /**
1605  * @brief usort() callback to reverse sort item arrays by the created key
1606  *
1607  * @param array $a
1608  * @param array $b
1609  * @return int
1610  */
1611 function sort_thr_created_rev(array $a, array $b)
1612 {
1613         return strcmp($a['created'], $b['created']);
1614 }
1615
1616 /**
1617  * @brief usort() callback to sort item arrays by the commented key
1618  *
1619  * @param array $a
1620  * @param array $b
1621  * @return type
1622  */
1623 function sort_thr_commented(array $a, array $b)
1624 {
1625         return strcmp($b['commented'], $a['commented']);
1626 }
1627
1628 /// @TODO Add type-hint
1629 function render_location_dummy($item) {
1630         if ($item['location'] != "") {
1631                 return $item['location'];
1632         }
1633
1634         if ($item['coord'] != "") {
1635                 return $item['coord'];
1636         }
1637 }
1638
1639 /// @TODO Add type-hint
1640 function get_responses($conv_responses, $response_verbs, $ob, $item) {
1641         $ret = [];
1642         foreach ($response_verbs as $v) {
1643                 $ret[$v] = [];
1644                 $ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
1645                 $ret[$v]['list']  = defaults($conv_responses[$v], $item['uri'] . '-l', '');
1646                 $ret[$v]['self']  = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
1647                 if (count($ret[$v]['list']) > MAX_LIKERS) {
1648                         $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
1649                         array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'
1650                                 . (($ob) ? $ob->getId() : $item['id']) . '"><b>' . L10n::t('View all') . '</b></a>');
1651                 } else {
1652                         $ret[$v]['list_part'] = '';
1653                 }
1654                 $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']);
1655                 $ret[$v]['title'] = $conv_responses[$v]['title'];
1656         }
1657
1658         $count = 0;
1659         foreach ($ret as $key) {
1660                 if ($key['count'] == true) {
1661                         $count++;
1662                 }
1663         }
1664         $ret['count'] = $count;
1665
1666         return $ret;
1667 }
1668
1669 function get_response_button_text($v, $count)
1670 {
1671         switch ($v) {
1672                 case 'like':
1673                         $return = L10n::tt('Like', 'Likes', $count);
1674                         break;
1675                 case 'dislike':
1676                         $return = L10n::tt('Dislike', 'Dislikes', $count);
1677                         break;
1678                 case 'attendyes':
1679                         $return = L10n::tt('Attending', 'Attending', $count);
1680                         break;
1681                 case 'attendno':
1682                         $return = L10n::tt('Not Attending', 'Not Attending', $count);
1683                         break;
1684                 case 'attendmaybe':
1685                         $return = L10n::tt('Undecided', 'Undecided', $count);
1686                         break;
1687         }
1688
1689         return $return;
1690 }