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