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