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