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