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