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