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