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