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