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