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