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