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