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