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