]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge remote branch 'upstream/master'
[friendica.git] / include / conversation.php
1 <?php
2
3 require_once("include/bbcode.php");
4
5
6 // Note: the code in 'item_extract_images' and 'item_redir_and_replace_images'
7 // is identical to the code in mod/message.php for 'item_extract_images' and
8 // 'item_redir_and_replace_images'
9 if(! function_exists('item_extract_images')) {
10 function item_extract_images($body) {
11
12         $saved_image = array();
13         $orig_body = $body;
14         $new_body = '';
15
16         $cnt = 0;
17         $img_start = strpos($orig_body, '[img');
18         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
19         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
20         while(($img_st_close !== false) && ($img_end !== false)) {
21
22                 $img_st_close++; // make it point to AFTER the closing bracket
23                 $img_end += $img_start;
24
25                 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
26                         // This is an embedded image
27
28                         $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
29                         $new_body = $new_body . substr($orig_body, 0, $img_start) . '[!#saved_image' . $cnt . '#!]';
30
31                         $cnt++;
32                 }
33                 else
34                         $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
35
36                 $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
37
38                 if($orig_body === false) // in case the body ends on a closing image tag
39                         $orig_body = '';
40
41                 $img_start = strpos($orig_body, '[img');
42                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
43                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
44         }
45
46         $new_body = $new_body . $orig_body;
47
48         return array('body' => $new_body, 'images' => $saved_image);
49 }}
50
51 if(! function_exists('item_redir_and_replace_images')) {
52 function item_redir_and_replace_images($body, $images, $cid) {
53
54         $origbody = $body;
55         $newbody = '';
56
57         $cnt = 1;
58         $pos = get_bb_tag_pos($origbody, 'url', 1);
59         while($pos !== false && $cnt < 1000) {
60
61                 $search = '/\[url\=(.*?)\]\[!#saved_image([0-9]*)#!\]\[\/url\]' . '/is';
62                 $replace = '[url=' . z_path() . '/redir/' . $cid
63                                    . '?f=1&url=' . '$1' . '][!#saved_image' . '$2' .'#!][/url]';
64
65                 $newbody .= substr($origbody, 0, $pos['start']['open']);
66                 $subject = substr($origbody, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
67                 $origbody = substr($origbody, $pos['end']['close']);
68                 if($origbody === false)
69                         $origbody = '';
70
71                 $subject = preg_replace($search, $replace, $subject);
72                 $newbody .= $subject;
73
74                 $cnt++;
75                 $pos = get_bb_tag_pos($origbody, 'url', 1);
76         }
77         $newbody .= $origbody;
78
79         $cnt = 0;
80         foreach($images as $image) {
81                 // We're depending on the property of 'foreach' (specified on the PHP website) that
82                 // it loops over the array starting from the first element and going sequentially
83                 // to the last element
84                 $newbody = str_replace('[!#saved_image' . $cnt . '#!]', '[img]' . $image . '[/img]', $newbody);
85                 $cnt++;
86         }
87         return $newbody;
88 }}
89
90
91
92 /**
93  * Render actions localized
94  */
95 function localize_item(&$item){
96
97         $extracted = item_extract_images($item['body']);
98         if($extracted['images'])
99                 $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
100
101         $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
102         if (activity_match($item['verb'],ACTIVITY_LIKE) || activity_match($item['verb'],ACTIVITY_DISLIKE)){
103
104                 $r = q("SELECT * from `item`,`contact` WHERE
105                                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
106                                  dbesc($item['parent-uri']));
107                 if(count($r)==0) return;
108                 $obj=$r[0];
109
110                 $author  = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
111                 $objauthor =  '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]';
112
113                 switch($obj['verb']){
114                         case ACTIVITY_POST:
115                                 switch ($obj['object-type']){
116                                         case ACTIVITY_OBJ_EVENT:
117                                                 $post_type = t('event');
118                                                 break;
119                                         default:
120                                                 $post_type = t('status');
121                                 }
122                                 break;
123                         default:
124                                 if($obj['resource-id']){
125                                         $post_type = t('photo');
126                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
127                                         $rr['plink'] = $m[1];
128                                 } else {
129                                         $post_type = t('status');
130                                 }
131                 }
132
133                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
134
135                 if(activity_match($item['verb'],ACTIVITY_LIKE)) {
136                         $bodyverb = t('%1$s likes %2$s\'s %3$s');
137                 }
138                 elseif(activity_match($item['verb'],ACTIVITY_DISLIKE)) {
139                         $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
140                 }
141                 $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
142
143         }
144         if (activity_match($item['verb'],ACTIVITY_FRIEND)) {
145
146                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
147
148                 $Aname = $item['author-name'];
149                 $Alink = $item['author-link'];
150
151                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
152
153                 $obj = parse_xml_string($xmlhead.$item['object']);
154                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
155
156                 $Bname = $obj->title;
157                 $Blink = ""; $Bphoto = "";
158                 foreach ($links->link as $l){
159                         $atts = $l->attributes();
160                         switch($atts['rel']){
161                                 case "alternate": $Blink = $atts['href'];
162                                 case "photo": $Bphoto = $atts['href'];
163                         }
164
165                 }
166
167                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
168                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
169                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img]' . $Bphoto . '[/img][/url]';
170
171                 $item['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
172
173         }
174         if (stristr($item['verb'],ACTIVITY_POKE)) {
175                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
176                 if(! $verb)
177                         return;
178                 if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
179
180                 $Aname = $item['author-name'];
181                 $Alink = $item['author-link'];
182
183                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
184
185                 $obj = parse_xml_string($xmlhead.$item['object']);
186                 $links = parse_xml_string($xmlhead."<links>".unxmlify($obj->link)."</links>");
187
188                 $Bname = $obj->title;
189                 $Blink = ""; $Bphoto = "";
190                 foreach ($links->link as $l){
191                         $atts = $l->attributes();
192                         switch($atts['rel']){
193                                 case "alternate": $Blink = $atts['href'];
194                                 case "photo": $Bphoto = $atts['href'];
195                         }
196
197                 }
198
199                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
200                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
201                 if ($Bphoto!="") $Bphoto = '[url=' . zrl($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
202
203                 // we can't have a translation string with three positions but no distinguishable text
204                 // So here is the translate string.
205
206                 $txt = t('%1$s poked %2$s');
207
208                 // now translate the verb
209
210                 $txt = str_replace( t('poked'), t($verb), $txt);
211
212                 // then do the sprintf on the translation string
213
214                 $item['body'] = sprintf($txt, $A, $B). "\n\n\n" . $Bphoto;
215
216         }
217         if (stristr($item['verb'],ACTIVITY_MOOD)) {
218                 $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1));
219                 if(! $verb)
220                         return;
221
222                 $Aname = $item['author-name'];
223                 $Alink = $item['author-link'];
224                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
225
226                 $txt = t('%1$s is currently %2$s');
227
228                 $item['body'] = sprintf($txt, $A, t($verb));
229         }
230
231         if (activity_match($item['verb'],ACTIVITY_TAG)) {
232                 $r = q("SELECT * from `item`,`contact` WHERE
233                 `item`.`contact-id`=`contact`.`id` AND `item`.`uri`='%s';",
234                  dbesc($item['parent-uri']));
235                 if(count($r)==0) return;
236                 $obj=$r[0];
237
238                 $author  = '[url=' . zrl($item['author-link']) . ']' . $item['author-name'] . '[/url]';
239                 $objauthor =  '[url=' . zrl($obj['author-link']) . ']' . $obj['author-name'] . '[/url]';
240
241                 switch($obj['verb']){
242                         case ACTIVITY_POST:
243                                 switch ($obj['object-type']){
244                                         case ACTIVITY_OBJ_EVENT:
245                                                 $post_type = t('event');
246                                                 break;
247                                         default:
248                                                 $post_type = t('status');
249                                 }
250                                 break;
251                         default:
252                                 if($obj['resource-id']){
253                                         $post_type = t('photo');
254                                         $m=array(); preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
255                                         $rr['plink'] = $m[1];
256                                 } else {
257                                         $post_type = t('status');
258                                 }
259                 }
260                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
261
262                 $parsedobj = parse_xml_string($xmlhead.$item['object']);
263
264                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
265                 $item['body'] = sprintf( t('%1$s tagged %2$s\'s %3$s with %4$s'), $author, $objauthor, $plink, $tag );
266
267         }
268         if (activity_match($item['verb'],ACTIVITY_FAVORITE)){
269
270                 if ($item['object-type']== "")
271                         return;
272
273                 $Aname = $item['author-name'];
274                 $Alink = $item['author-link'];
275
276                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
277
278                 $obj = parse_xml_string($xmlhead.$item['object']);
279                 if(strlen($obj->id)) {
280                         $r = q("select * from item where uri = '%s' and uid = %d limit 1",
281                                         dbesc($obj->id),
282                                         intval($item['uid'])
283                         );
284                         if(count($r) && $r[0]['plink']) {
285                                 $target = $r[0];
286                                 $Bname = $target['author-name'];
287                                 $Blink = $target['author-link'];
288                                 $A = '[url=' . zrl($Alink) . ']' . $Aname . '[/url]';
289                                 $B = '[url=' . zrl($Blink) . ']' . $Bname . '[/url]';
290                                 $P = '[url=' . $target['plink'] . ']' . t('post/item') . '[/url]';
291                                 $item['body'] = sprintf( t('%1$s marked %2$s\'s %3$s as favorite'), $A, $B, $P)."\n";
292
293                         }
294                 }
295         }
296         $matches = null;
297         if(preg_match_all('/@\[url=(.*?)\]/is',$item['body'],$matches,PREG_SET_ORDER)) {
298                 foreach($matches as $mtch) {
299                         if(! strpos($mtch[1],'zrl='))
300                                 $item['body'] = str_replace($mtch[0],'@[url=' . zrl($mtch[1]). ']',$item['body']);
301                 }
302         }
303
304         // add zrl's to public images
305         $photo_pattern = "/\[url=(.*?)\/photos\/(.*?)\/image\/(.*?)\]\[img(.*?)\]h(.*?)\[\/img\]\[\/url\]/is";
306         if(preg_match($photo_pattern,$item['body'])) {
307                 $photo_replace = '[url=' . zrl('$1' . '/photos/' . '$2' . '/image/' . '$3' ,true) . '][img' . '$4' . ']h' . '$5'  . '[/img][/url]';
308                 $item['body'] = bb_tag_preg_replace($photo_pattern, $photo_replace, 'url', $item['body']);
309         }
310
311         // add sparkle links to appropriate permalinks
312
313         $x = stristr($item['plink'],'/display/');
314         if($x) {
315                 $sparkle = false;
316                 $y = best_link_url($item,$sparkle,true);
317                 if(strstr($y,'/redir/'))
318                         $item['plink'] = $y . '?f=&url=' . $item['plink'];
319         }
320
321
322
323 }
324
325 /**
326  * Count the total of comments on this item and its desendants
327  */
328 function count_descendants($item) {
329         $total = count($item['children']);
330
331         if($total > 0) {
332                 foreach($item['children'] as $child) {
333                         if(! visible_activity($child))
334                                 $total --;
335                         $total += count_descendants($child);
336                 }
337         }
338
339         return $total;
340 }
341
342 function visible_activity($item) {
343
344         if(activity_match($item['verb'],ACTIVITY_LIKE) || activity_match($item['verb'],ACTIVITY_DISLIKE))
345                 return false;
346
347         if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) {
348                 if(! (($item['self']) && ($item['uid'] == local_user()))) {
349                         return false;
350                 }
351         }
352
353         return true;
354 }
355
356
357 /**
358  * "Render" a conversation or list of items for HTML display.
359  * There are two major forms of display:
360  *      - Sequential or unthreaded ("New Item View" or search results)
361  *      - conversation view
362  * The $mode parameter decides between the various renderings and also
363  * figures out how to determine page owner and other contextual items
364  * that are based on unique features of the calling module.
365  *
366  */
367
368 if(!function_exists('conversation')) {
369 function conversation(&$a, $items, $mode, $update, $preview = false) {
370
371
372         require_once('bbcode.php');
373
374         $ssl_state = ((local_user()) ? true : false);
375
376         $profile_owner = 0;
377         $page_writeable      = false;
378
379         $previewing = (($preview) ? ' preview ' : '');
380
381         if($mode === 'network') {
382                 $profile_owner = local_user();
383                 $page_writeable = true;
384         }
385
386         if($mode === 'profile') {
387                 $profile_owner = $a->profile['profile_uid'];
388                 $page_writeable = can_write_wall($a,$profile_owner);
389         }
390
391         if($mode === 'notes') {
392                 $profile_owner = local_user();
393                 $page_writeable = true;
394         }
395
396         if($mode === 'display') {
397                 $profile_owner = $a->profile['uid'];
398                 $page_writeable = can_write_wall($a,$profile_owner);
399         }
400
401         if($mode === 'community') {
402                 $profile_owner = 0;
403                 $page_writeable = false;
404         }
405
406         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
407
408
409         if($update)
410                 $return_url = $_SESSION['return_url'];
411         else
412                 $return_url = $_SESSION['return_url'] = $a->query_string;
413
414         load_contact_links(local_user());
415
416         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
417         call_hooks('conversation_start',$cb);
418
419         $items = $cb['items'];
420
421         $cmnt_tpl    = get_markup_template('comment_item.tpl');
422         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
423
424         $alike = array();
425         $dlike = array();
426
427
428         // array with html for each thread (parent+comments)
429         $threads = array();
430         $threadsid = -1;
431
432         $page_template = get_markup_template("conversation.tpl");
433
434         if($items && count($items)) {
435
436                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
437
438                         // "New Item View" on network page or search page results
439                         // - just loop through the items and format them minimally for display
440
441 //                      $tpl = get_markup_template('search_item.tpl');
442                         $tpl = 'search_item.tpl';
443
444                         foreach($items as $item) {
445                                 $threadsid++;
446
447                                 $comment     = '';
448                                 $owner_url   = '';
449                                 $owner_photo = '';
450                                 $owner_name  = '';
451                                 $sparkle     = '';
452
453                                 if($mode === 'search' || $mode === 'community') {
454                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
455                                                 && ($item['id'] != $item['parent']))
456                                                 continue;
457                                         $nickname = $item['nickname'];
458                                 }
459                                 else
460                                         $nickname = $a->user['nickname'];
461
462                                 // prevent private email from leaking.
463                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
464                                                 continue;
465
466                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
467                                 if($item['author-link'] && (! $item['author-name']))
468                                         $profile_name = $item['author-link'];
469
470
471
472                                 $tags=array();
473                                 $hashtags = array();
474                                 $mentions = array();
475                                 foreach(explode(',',$item['tag']) as $tag){
476                                         $tag = trim($tag);
477                                         if ($tag!="") {
478                                                 $t = bbcode($tag);
479                                                 $tags[] = $t;
480                                                 if($t[0] == '#')
481                                                         $hashtags[] = $t;
482                                                 elseif($t[0] == '@')
483                                                         $mentions[] = $t;
484                                         }
485                                 }
486
487                                 $sp = false;
488                                 $profile_link = best_link_url($item,$sp);
489                                 if($profile_link === 'mailbox')
490                                         $profile_link = '';
491                                 if($sp)
492                                         $sparkle = ' sparkle';
493                                 else
494                                         $profile_link = zrl($profile_link);
495
496                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
497                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
498                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
499                                 else
500                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
501
502                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
503                                 call_hooks('render_location',$locate);
504
505                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
506
507                                 localize_item($item);
508                                 if($mode === 'network-new')
509                                         $dropping = true;
510                                 else
511                                         $dropping = false;
512
513
514                                 $drop = array(
515                                         'dropping' => $dropping,
516                                         'pagedrop' => $page_dropping,
517                                         'select' => t('Select'),
518                                         'delete' => t('Delete'),
519                                 );
520
521                                 $star = false;
522                                 $isstarred = "unstarred";
523
524                                 $lock = false;
525                                 $likebuttons = false;
526                                 $shareable = false;
527
528                                 $body = prepare_body($item,true);
529
530
531                                 list($categories, $folders) = get_cats_and_terms($item);
532
533                                 $tmp_item = array(
534                                         'template' => $tpl,
535                                         'id' => (($preview) ? 'P0' : $item['item_id']),
536                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
537                                         'profile_url' => $profile_link,
538                                         'item_photo_menu' => item_photo_menu($item),
539                                         'name' => template_escape($profile_name),
540                                         'sparkle' => $sparkle,
541                                         'lock' => $lock,
542                                         'thumb' => $profile_avatar,
543                                         'title' => template_escape($item['title']),
544                                         'body' => template_escape($body),
545                                         'tags' => template_escape($tags),
546                                         'hashtags' => template_escape($hashtags),
547                                         'mentions' => template_escape($mentions),
548                                         'txt_cats' => t('Categories:'),
549                                         'txt_folders' => t('Filed under:'),
550                                         'has_cats' => ((count($categories)) ? 'true' : ''),
551                                         'has_folders' => ((count($folders)) ? 'true' : ''),
552                                         'categories' => $categories,
553                                         'folders' => $folders,
554                                         'text' => strip_tags(template_escape($body)),
555                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
556                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
557                                         'location' => template_escape($location),
558                                         'indent' => '',
559                                         'owner_name' => template_escape($owner_name),
560                                         'owner_url' => $owner_url,
561                                         'owner_photo' => $owner_photo,
562                                         'plink' => get_plink($item),
563                                         'edpost' => false,
564                                         'isstarred' => $isstarred,
565                                         'star' => $star,
566                                         'drop' => $drop,
567                                         'vote' => $likebuttons,
568                                         'like' => '',
569                                         'dislike' => '',
570                                         'comment' => '',
571                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
572                                         'previewing' => $previewing,
573                                         'wait' => t('Please wait'),
574                                         'thread_level' => 1,
575                                 );
576
577                                 $arr = array('item' => $item, 'output' => $tmp_item);
578                                 call_hooks('display_item', $arr);
579
580                                 $threads[$threadsid]['id'] = $item['item_id'];
581                                 $threads[$threadsid]['items'] = array($arr['output']);
582
583                         }
584
585                 }
586                 else
587                 {
588                         // Normal View
589                         $page_template = get_markup_template("threaded_conversation.tpl");
590
591                         require_once('object/Conversation.php');
592                         require_once('object/Item.php');
593
594                         $conv = new Conversation($mode, $preview);
595
596                         // get all the topmost parents
597                         // this shouldn't be needed, as we should have only them in our array
598                         // But for now, this array respects the old style, just in case
599
600                         $threads = array();
601                         foreach($items as $item) {
602
603                                 // Can we put this after the visibility check?
604                                 like_puller($a,$item,$alike,'like');
605                                 like_puller($a,$item,$dlike,'dislike');
606
607                                 // Only add what is visible
608                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
609                                         continue;
610                                 }
611                                 if(! visible_activity($item)) {
612                                         continue;
613                                 }
614
615                                 $item['pagedrop'] = $page_dropping;
616
617                                 if($item['id'] == $item['parent']) {
618                                         $item_object = new Item($item);
619                                         $conv->add_thread($item_object);
620                                 }
621                         }
622
623                         $threads = $conv->get_template_data($alike, $dlike);
624                         if(!$threads) {
625                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
626                                 $threads = array();
627                         }
628                 }
629         }
630
631         $o = replace_macros($page_template, array(
632                 '$baseurl' => $a->get_baseurl($ssl_state),
633         '$remove' => t('remove'),
634                 '$mode' => $mode,
635                 '$user' => $a->user,
636                 '$threads' => $threads,
637                 '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
638         ));
639
640         return $o;
641 }}
642
643 function best_link_url($item,&$sparkle,$ssl_state = false) {
644
645         $a = get_app();
646
647         $best_url = '';
648         $sparkle  = false;
649
650         $clean_url = normalise_link($item['author-link']);
651
652         if((local_user()) && (local_user() == $item['uid'])) {
653                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
654                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
655                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
656                                 $sparkle = true;
657                         }
658                         else
659                                 $best_url = $a->contacts[$clean_url]['url'];
660                 }
661         }
662         if(! $best_url) {
663                 if(strlen($item['author-link']))
664                         $best_url = $item['author-link'];
665                 else
666                         $best_url = $item['url'];
667         }
668
669         return $best_url;
670 }
671
672
673 if(! function_exists('item_photo_menu')){
674 function item_photo_menu($item){
675         $a = get_app();
676
677         $ssl_state = false;
678
679         if(local_user()) {
680                 $ssl_state = true;
681                  if(! count($a->contacts))
682                         load_contact_links(local_user());
683         }
684         $sub_link="";
685         $poke_link="";
686         $contact_url="";
687         $pm_url="";
688         $status_link="";
689         $photos_link="";
690         $posts_link="";
691
692         if((local_user()) && local_user() == $item['uid'] && $item['parent'] == $item['id'] && (! $item['self'])) {
693                 $sub_link = 'javascript:dosubthread(' . $item['id'] . '); return false;';
694         }
695
696         $sparkle = false;
697         $profile_link = best_link_url($item,$sparkle,$ssl_state);
698         if($profile_link === 'mailbox')
699                 $profile_link = '';
700
701         if($sparkle) {
702                 $cid = intval(basename($profile_link));
703                 $status_link = $profile_link . "?url=status";
704                 $photos_link = $profile_link . "?url=photos";
705                 $profile_link = $profile_link . "?url=profile";
706                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
707                 $zurl = '';
708         }
709         else {
710                 $profile_link = zrl($profile_link);
711                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
712                         $cid = $item['contact-id'];
713                 }
714                 else {
715                         $cid = 0;
716                 }
717         }
718         if(($cid) && (! $item['self'])) {
719                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
720                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
721                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
722
723                 $clean_url = normalise_link($item['author-link']);
724
725                 if((local_user()) && (local_user() == $item['uid'])) {
726                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
727                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
728                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
729                                 }
730                         }
731                 }
732
733         }
734
735         $menu = Array(
736                 t("Follow Thread") => $sub_link,
737                 t("View Status") => $status_link,
738                 t("View Profile") => $profile_link,
739                 t("View Photos") => $photos_link,
740                 t("Network Posts") => $posts_link,
741                 t("Edit Contact") => $contact_url,
742                 t("Send PM") => $pm_url,
743                 t("Poke") => $poke_link
744         );
745
746
747         $args = array('item' => $item, 'menu' => $menu);
748
749         call_hooks('item_photo_menu', $args);
750
751         $menu = $args['menu'];
752
753         $o = "";
754         foreach($menu as $k=>$v){
755                 if(strpos($v,'javascript:') === 0) {
756                         $v = substr($v,11);
757                         $o .= "<li><a href=\"#\" onclick=\"$v\">$k</a></li>\n";
758                 }
759                 elseif ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
760         }
761         return $o;
762 }}
763
764 if(! function_exists('like_puller')) {
765 function like_puller($a,$item,&$arr,$mode) {
766
767         $url = '';
768         $sparkle = '';
769         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
770
771         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
772                 $url = $item['author-link'];
773                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
774                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
775                         $sparkle = ' class="sparkle" ';
776                 }
777                 else
778                         $url = zrl($url);
779
780                 if(! $item['thr-parent'])
781                         $item['thr-parent'] = $item['parent-uri'];
782
783                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
784                         $arr[$item['thr-parent'] . '-l'] = array();
785                 if(! isset($arr[$item['thr-parent']]))
786                         $arr[$item['thr-parent']] = 1;
787                 else
788                         $arr[$item['thr-parent']] ++;
789                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
790         }
791         return;
792 }}
793
794 // Format the like/dislike text for a profile item
795 // $cnt = number of people who like/dislike the item
796 // $arr = array of pre-linked names of likers/dislikers
797 // $type = one of 'like, 'dislike'
798 // $id  = item id
799 // returns formatted text
800
801 if(! function_exists('format_like')) {
802 function format_like($cnt,$arr,$type,$id) {
803         $o = '';
804         if($cnt == 1)
805                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
806         else {
807                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
808                 $o .= (($type === 'like') ?
809                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
810                                          :
811                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) );
812                 $o .= EOL ;
813                 $total = count($arr);
814                 if($total >= MAX_LIKERS)
815                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
816                 if($total < MAX_LIKERS)
817                         $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
818                 $str = implode(', ', $arr);
819                 if($total >= MAX_LIKERS)
820                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
821                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
822                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
823         }
824         return $o;
825 }}
826
827
828 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
829
830         $o = '';
831
832         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
833
834         $plaintext = false;
835         if(local_user() && intval(get_pconfig(local_user(),'system','plaintext')))
836                 $plaintext = true;
837
838         $tpl = get_markup_template('jot-header.tpl');
839         $a->page['htmlhead'] .= replace_macros($tpl, array(
840                 '$newpost' => 'true',
841                 '$baseurl' => $a->get_baseurl(true),
842                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
843                 '$geotag' => $geotag,
844                 '$nickname' => $x['nickname'],
845                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
846                 '$linkurl' => t('Please enter a link URL:'),
847                 '$vidurl' => t("Please enter a video link/URL:"),
848                 '$audurl' => t("Please enter an audio link/URL:"),
849                 '$term' => t('Tag term:'),
850                 '$fileas' => t('Save to Folder:'),
851                 '$whereareu' => t('Where are you right now?')
852         ));
853
854
855         $tpl = get_markup_template('jot-end.tpl');
856         $a->page['end'] .= replace_macros($tpl, array(
857                 '$newpost' => 'true',
858                 '$baseurl' => $a->get_baseurl(true),
859                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
860                 '$geotag' => $geotag,
861                 '$nickname' => $x['nickname'],
862                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
863                 '$linkurl' => t('Please enter a link URL:'),
864                 '$vidurl' => t("Please enter a video link/URL:"),
865                 '$audurl' => t("Please enter an audio link/URL:"),
866                 '$term' => t('Tag term:'),
867                 '$fileas' => t('Save to Folder:'),
868                 '$whereareu' => t('Where are you right now?')
869         ));
870
871
872         $tpl = get_markup_template("jot.tpl");
873
874         $jotplugins = '';
875         $jotnets = '';
876
877         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
878
879         $mail_enabled = false;
880         $pubmail_enabled = false;
881
882         if(($x['is_owner']) && (! $mail_disabled)) {
883                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
884                         intval(local_user())
885                 );
886                 if(count($r)) {
887                         $mail_enabled = true;
888                         if(intval($r[0]['pubmail']))
889                                 $pubmail_enabled = true;
890                 }
891         }
892
893         if($mail_enabled) {
894                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
895                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
896         }
897
898         call_hooks('jot_tool', $jotplugins);
899         call_hooks('jot_networks', $jotnets);
900
901         if($notes_cid)
902                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
903
904         $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
905
906         $o .= replace_macros($tpl,array(
907                 '$return_path' => $a->query_string,
908                 '$action' =>  $a->get_baseurl(true) . '/item',
909                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
910                 '$upload' => t('Upload photo'),
911                 '$shortupload' => t('upload photo'),
912                 '$attach' => t('Attach file'),
913                 '$shortattach' => t('attach file'),
914                 '$weblink' => t('Insert web link'),
915                 '$shortweblink' => t('web link'),
916                 '$video' => t('Insert video link'),
917                 '$shortvideo' => t('video link'),
918                 '$audio' => t('Insert audio link'),
919                 '$shortaudio' => t('audio link'),
920                 '$setloc' => t('Set your location'),
921                 '$shortsetloc' => t('set location'),
922                 '$noloc' => t('Clear browser location'),
923                 '$shortnoloc' => t('clear location'),
924                 '$title' => "",
925                 '$placeholdertitle' => t('Set title'),
926                 '$category' => "",
927                 '$placeholdercategory' => t('Categories (comma-separated list)'),
928                 '$wait' => t('Please wait'),
929                 '$permset' => t('Permission settings'),
930                 '$shortpermset' => t('permissions'),
931                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
932                 '$content' => '',
933                 '$post_id' => '',
934                 '$baseurl' => $a->get_baseurl(true),
935                 '$defloc' => $x['default_location'],
936                 '$visitor' => $x['visitor'],
937                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
938                 '$emailcc' => t('CC: email addresses'),
939                 '$public' => t('Public post'),
940                 '$jotnets' => $jotnets,
941                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
942                 '$lockstate' => $x['lockstate'],
943                 '$acl' => $x['acl'],
944                 '$bang' => $x['bang'],
945                 '$profile_uid' => $x['profile_uid'],
946                 '$preview' => t('Preview'),
947                 '$sourceapp' => t($a->sourcename),
948                 '$cancel' => t('Cancel')
949         ));
950
951
952         if ($popup==true){
953                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
954
955         }
956
957         return $o;
958 }
959
960
961 function get_item_children($arr, $parent) {
962         $children = array();
963         foreach($arr as $item) {
964                 if($item['id'] != $item['parent']) {
965                         if(get_config('system','thread_allow')) {
966                                 // Fallback to parent-uri if thr-parent is not set
967                                 $thr_parent = $item['thr-parent'];
968                                 if($thr_parent == '')
969                                         $thr_parent = $item['parent-uri'];
970
971                                 if($thr_parent == $parent['uri']) {
972                                         $item['children'] = get_item_children($arr, $item);
973                                         $children[] = $item;
974                                 }
975                         }
976                         else if($item['parent'] == $parent['id']) {
977                                 $children[] = $item;
978                         }
979                 }
980         }
981         return $children;
982 }
983
984 function sort_item_children($items) {
985         $result = $items;
986         usort($result,'sort_thr_created_rev');
987         foreach($result as $k => $i) {
988                 if(count($result[$k]['children'])) {
989                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
990                 }
991         }
992         return $result;
993 }
994
995 function add_children_to_list($children, &$arr) {
996         foreach($children as $y) {
997                 $arr[] = $y;
998                 if(count($y['children']))
999                         add_children_to_list($y['children'], $arr);
1000         }
1001 }
1002
1003 function conv_sort($arr,$order) {
1004
1005         if((!(is_array($arr) && count($arr))))
1006                 return array();
1007
1008         $parents = array();
1009         $children = array();
1010
1011         foreach($arr as $x)
1012                 if($x['id'] == $x['parent'])
1013                                 $parents[] = $x;
1014
1015         if(stristr($order,'created'))
1016                 usort($parents,'sort_thr_created');
1017         elseif(stristr($order,'commented'))
1018                 usort($parents,'sort_thr_commented');
1019
1020         if(count($parents))
1021                 foreach($parents as $i=>$_x)
1022                         $parents[$i]['children'] = get_item_children($arr, $_x);
1023
1024         /*foreach($arr as $x) {
1025                 if($x['id'] != $x['parent']) {
1026                         $p = find_thread_parent_index($parents,$x);
1027                         if($p !== false)
1028                                 $parents[$p]['children'][] = $x;
1029                 }
1030         }*/
1031         if(count($parents)) {
1032                 foreach($parents as $k => $v) {
1033                         if(count($parents[$k]['children'])) {
1034                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1035                                 /*$y = $parents[$k]['children'];
1036                                 usort($y,'sort_thr_created_rev');
1037                                 $parents[$k]['children'] = $y;*/
1038                         }
1039                 }
1040         }
1041
1042         $ret = array();
1043         if(count($parents)) {
1044                 foreach($parents as $x) {
1045                         $ret[] = $x;
1046                         if(count($x['children']))
1047                                 add_children_to_list($x['children'], $ret);
1048                                 /*foreach($x['children'] as $y)
1049                                         $ret[] = $y;*/
1050                 }
1051         }
1052
1053         return $ret;
1054 }
1055
1056
1057 function sort_thr_created($a,$b) {
1058         return strcmp($b['created'],$a['created']);
1059 }
1060
1061 function sort_thr_created_rev($a,$b) {
1062         return strcmp($a['created'],$b['created']);
1063 }
1064
1065 function sort_thr_commented($a,$b) {
1066         return strcmp($b['commented'],$a['commented']);
1067 }
1068
1069 function find_thread_parent_index($arr,$x) {
1070         foreach($arr as $k => $v)
1071                 if($v['id'] == $x['parent'])
1072                         return $k;
1073         return false;
1074 }
1075
1076 function render_location_google($item) {
1077         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1078         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1079         if($coord) {
1080                 if($location)
1081                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1082                 else
1083                         $location = '<span class="smalltext">' . $coord . '</span>';
1084         }
1085         return $location;
1086 }