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