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