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