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