]> git.mxchange.org Git - friendica.git/blob - include/conversation.php
Merge https://github.com/friendica/friendica into pull
[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($child['verb'],ACTIVITY_LIKE) || activity_match($child['verb'],ACTIVITY_DISLIKE))
345                 return false;
346
347         if(activity_match($item['verb'],ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && $item['uid'] != local_user())
348                 return false;
349
350         return true;
351 }
352
353
354 /**
355  * "Render" a conversation or list of items for HTML display.
356  * There are two major forms of display:
357  *      - Sequential or unthreaded ("New Item View" or search results)
358  *      - conversation view
359  * The $mode parameter decides between the various renderings and also
360  * figures out how to determine page owner and other contextual items
361  * that are based on unique features of the calling module.
362  *
363  */
364
365 if(!function_exists('conversation')) {
366 function conversation(&$a, $items, $mode, $update, $preview = false) {
367
368
369         require_once('bbcode.php');
370
371         $ssl_state = ((local_user()) ? true : false);
372
373         $profile_owner = 0;
374         $page_writeable      = false;
375
376         $previewing = (($preview) ? ' preview ' : '');
377
378         if($mode === 'network') {
379                 $profile_owner = local_user();
380                 $page_writeable = true;
381         }
382
383         if($mode === 'profile') {
384                 $profile_owner = $a->profile['profile_uid'];
385                 $page_writeable = can_write_wall($a,$profile_owner);
386         }
387
388         if($mode === 'notes') {
389                 $profile_owner = local_user();
390                 $page_writeable = true;
391         }
392
393         if($mode === 'display') {
394                 $profile_owner = $a->profile['uid'];
395                 $page_writeable = can_write_wall($a,$profile_owner);
396         }
397
398         if($mode === 'community') {
399                 $profile_owner = 0;
400                 $page_writeable = false;
401         }
402
403         $page_dropping = ((local_user() && local_user() == $profile_owner) ? true : false);
404
405
406         if($update)
407                 $return_url = $_SESSION['return_url'];
408         else
409                 $return_url = $_SESSION['return_url'] = $a->query_string;
410
411         load_contact_links(local_user());
412
413         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
414         call_hooks('conversation_start',$cb);
415
416         $items = $cb['items'];
417
418         $cmnt_tpl    = get_markup_template('comment_item.tpl');
419         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
420
421         $alike = array();
422         $dlike = array();
423
424
425         // array with html for each thread (parent+comments)
426         $threads = array();
427         $threadsid = -1;
428
429         $page_template = get_markup_template("conversation.tpl");
430
431         if($items && count($items)) {
432
433                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
434
435                         // "New Item View" on network page or search page results
436                         // - just loop through the items and format them minimally for display
437
438 //                      $tpl = get_markup_template('search_item.tpl');
439                         $tpl = 'search_item.tpl';
440
441                         foreach($items as $item) {
442                                 $threadsid++;
443
444                                 $comment     = '';
445                                 $owner_url   = '';
446                                 $owner_photo = '';
447                                 $owner_name  = '';
448                                 $sparkle     = '';
449
450                                 if($mode === 'search' || $mode === 'community') {
451                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE)))
452                                                 && ($item['id'] != $item['parent']))
453                                                 continue;
454                                         $nickname = $item['nickname'];
455                                 }
456                                 else
457                                         $nickname = $a->user['nickname'];
458
459                                 // prevent private email from leaking.
460                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
461                                                 continue;
462
463                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
464                                 if($item['author-link'] && (! $item['author-name']))
465                                         $profile_name = $item['author-link'];
466
467
468
469                                 $tags=array();
470                                 $hashtags = array();
471                                 $mentions = array();
472                                 foreach(explode(',',$item['tag']) as $tag){
473                                         $tag = trim($tag);
474                                         if ($tag!="") {
475                                                 $t = bbcode($tag);
476                                                 $tags[] = $t;
477                                                 if($t[0] == '#')
478                                                         $hashtags[] = $t;
479                                                 elseif($t[0] == '@')
480                                                         $mentions[] = $t;
481                                         }
482                                 }
483
484                                 $sp = false;
485                                 $profile_link = best_link_url($item,$sp);
486                                 if($profile_link === 'mailbox')
487                                         $profile_link = '';
488                                 if($sp)
489                                         $sparkle = ' sparkle';
490                                 else
491                                         $profile_link = zrl($profile_link);
492
493                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
494                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
495                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
496                                 else
497                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
498
499                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
500                                 call_hooks('render_location',$locate);
501
502                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
503
504                                 localize_item($item);
505                                 if($mode === 'network-new')
506                                         $dropping = true;
507                                 else
508                                         $dropping = false;
509
510
511                                 $drop = array(
512                                         'dropping' => $dropping,
513                                         'pagedrop' => $page_dropping,
514                                         'select' => t('Select'),
515                                         'delete' => t('Delete'),
516                                 );
517
518                                 $star = false;
519                                 $isstarred = "unstarred";
520
521                                 $lock = false;
522                                 $likebuttons = false;
523                                 $shareable = false;
524
525                                 $body = prepare_body($item,true);
526
527
528                                 list($categories, $folders) = get_cats_and_terms($item);
529
530                                 $tmp_item = array(
531                                         'template' => $tpl,
532                                         'id' => (($preview) ? 'P0' : $item['item_id']),
533                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
534                                         'profile_url' => $profile_link,
535                                         'item_photo_menu' => item_photo_menu($item),
536                                         'name' => template_escape($profile_name),
537                                         'sparkle' => $sparkle,
538                                         'lock' => $lock,
539                                         'thumb' => $profile_avatar,
540                                         'title' => template_escape($item['title']),
541                                         'body' => template_escape($body),
542                                         'tags' => template_escape($tags),
543                                         'hashtags' => template_escape($hashtags),
544                                         'mentions' => template_escape($mentions),
545                                         'txt_cats' => t('Categories:'),
546                                         'txt_folders' => t('Filed under:'),
547                                         'has_cats' => ((count($categories)) ? 'true' : ''),
548                                         'has_folders' => ((count($folders)) ? 'true' : ''),
549                                         'categories' => $categories,
550                                         'folders' => $folders,
551                                         'text' => strip_tags(template_escape($body)),
552                                         'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
553                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
554                                         'location' => template_escape($location),
555                                         'indent' => '',
556                                         'owner_name' => template_escape($owner_name),
557                                         'owner_url' => $owner_url,
558                                         'owner_photo' => $owner_photo,
559                                         'plink' => get_plink($item),
560                                         'edpost' => false,
561                                         'isstarred' => $isstarred,
562                                         'star' => $star,
563                                         'drop' => $drop,
564                                         'vote' => $likebuttons,
565                                         'like' => '',
566                                         'dislike' => '',
567                                         'comment' => '',
568                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
569                                         'previewing' => $previewing,
570                                         'wait' => t('Please wait'),
571                                         'thread_level' => 1,
572                                 );
573
574                                 $arr = array('item' => $item, 'output' => $tmp_item);
575                                 call_hooks('display_item', $arr);
576
577                                 $threads[$threadsid]['id'] = $item['item_id'];
578                                 $threads[$threadsid]['items'] = array($arr['output']);
579
580                         }
581
582                 }
583                 else
584                 {
585                         // Normal View
586                         $page_template = get_markup_template("threaded_conversation.tpl");
587
588                         require_once('object/Conversation.php');
589                         require_once('object/Item.php');
590
591                         $conv = new Conversation($mode, $preview);
592
593                         // get all the topmost parents
594                         // this shouldn't be needed, as we should have only them in our array
595                         // But for now, this array respects the old style, just in case
596
597                         $threads = array();
598                         foreach($items as $item) {
599
600                                 // Can we put this after the visibility check?
601                                 like_puller($a,$item,$alike,'like');
602                                 like_puller($a,$item,$dlike,'dislike');
603
604                                 // Only add what is visible
605                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
606                                         continue;
607                                 }
608                                 if(! visible_activity($item)) {
609                                         continue;
610                                 }
611
612                                 $item['pagedrop'] = $page_dropping;
613
614                                 if($item['id'] == $item['parent']) {
615                                         $item_object = new Item($item);
616                                         $conv->add_thread($item_object);
617                                 }
618                         }
619
620                         $threads = $conv->get_template_data($alike, $dlike);
621                         if(!$threads) {
622                                 logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG);
623                                 $threads = array();
624                         }
625                 }
626         }
627
628         $o = replace_macros($page_template, array(
629                 '$baseurl' => $a->get_baseurl($ssl_state),
630         '$remove' => t('remove'),
631                 '$mode' => $mode,
632                 '$user' => $a->user,
633                 '$threads' => $threads,
634                 '$dropping' => ($page_dropping?t('Delete Selected Items'):False),
635         ));
636
637         return $o;
638 }}
639
640 function best_link_url($item,&$sparkle,$ssl_state = false) {
641
642         $a = get_app();
643
644         $best_url = '';
645         $sparkle  = false;
646
647         $clean_url = normalise_link($item['author-link']);
648
649         if((local_user()) && (local_user() == $item['uid'])) {
650                 if(isset($a->contacts) && x($a->contacts,$clean_url)) {
651                         if($a->contacts[$clean_url]['network'] === NETWORK_DFRN) {
652                                 $best_url = $a->get_baseurl($ssl_state) . '/redir/' . $a->contacts[$clean_url]['id'];
653                                 $sparkle = true;
654                         }
655                         else
656                                 $best_url = $a->contacts[$clean_url]['url'];
657                 }
658         }
659         if(! $best_url) {
660                 if(strlen($item['author-link']))
661                         $best_url = $item['author-link'];
662                 else
663                         $best_url = $item['url'];
664         }
665
666         return $best_url;
667 }
668
669
670 if(! function_exists('item_photo_menu')){
671 function item_photo_menu($item){
672         $a = get_app();
673
674         $ssl_state = false;
675
676         if(local_user()) {
677                 $ssl_state = true;
678                  if(! count($a->contacts))
679                         load_contact_links(local_user());
680         }
681         $poke_link="";
682         $contact_url="";
683         $pm_url="";
684         $status_link="";
685         $photos_link="";
686         $posts_link="";
687
688         $sparkle = false;
689         $profile_link = best_link_url($item,$sparkle,$ssl_state);
690         if($profile_link === 'mailbox')
691                 $profile_link = '';
692
693         if($sparkle) {
694                 $cid = intval(basename($profile_link));
695                 $status_link = $profile_link . "?url=status";
696                 $photos_link = $profile_link . "?url=photos";
697                 $profile_link = $profile_link . "?url=profile";
698                 $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
699                 $zurl = '';
700         }
701         else {
702                 $profile_link = zrl($profile_link);
703                 if(local_user() && local_user() == $item['uid'] && link_compare($item['url'],$item['author-link'])) {
704                         $cid = $item['contact-id'];
705                 }
706                 else {
707                         $cid = 0;
708                 }
709         }
710         if(($cid) && (! $item['self'])) {
711                 $poke_link = $a->get_baseurl($ssl_state) . '/poke/?f=&c=' . $cid;
712                 $contact_url = $a->get_baseurl($ssl_state) . '/contacts/' . $cid;
713                 $posts_link = $a->get_baseurl($ssl_state) . '/network/?cid=' . $cid;
714
715                 $clean_url = normalise_link($item['author-link']);
716
717                 if((local_user()) && (local_user() == $item['uid'])) {
718                         if(isset($a->contacts) && x($a->contacts,$clean_url)) {
719                                 if($a->contacts[$clean_url]['network'] === NETWORK_DIASPORA) {
720                                         $pm_url = $a->get_baseurl($ssl_state) . '/message/new/' . $cid;
721                                 }
722                         }
723                 }
724
725         }
726
727         $menu = Array(
728                 t("View Status") => $status_link,
729                 t("View Profile") => $profile_link,
730                 t("View Photos") => $photos_link,
731                 t("Network Posts") => $posts_link,
732                 t("Edit Contact") => $contact_url,
733                 t("Send PM") => $pm_url,
734                 t("Poke") => $poke_link
735         );
736
737
738         $args = array('item' => $item, 'menu' => $menu);
739
740         call_hooks('item_photo_menu', $args);
741
742         $menu = $args['menu'];
743
744         $o = "";
745         foreach($menu as $k=>$v){
746                 if ($v!="") $o .= "<li><a href=\"$v\">$k</a></li>\n";
747         }
748         return $o;
749 }}
750
751 if(! function_exists('like_puller')) {
752 function like_puller($a,$item,&$arr,$mode) {
753
754         $url = '';
755         $sparkle = '';
756         $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
757
758         if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
759                 $url = $item['author-link'];
760                 if((local_user()) && (local_user() == $item['uid']) && ($item['network'] === 'dfrn') && (! $item['self']) && (link_compare($item['author-link'],$item['url']))) {
761                         $url = $a->get_baseurl(true) . '/redir/' . $item['contact-id'];
762                         $sparkle = ' class="sparkle" ';
763                 }
764                 else
765                         $url = zrl($url);
766
767                 if(! $item['thr-parent'])
768                         $item['thr-parent'] = $item['parent-uri'];
769
770                 if(! ((isset($arr[$item['thr-parent'] . '-l'])) && (is_array($arr[$item['thr-parent'] . '-l']))))
771                         $arr[$item['thr-parent'] . '-l'] = array();
772                 if(! isset($arr[$item['thr-parent']]))
773                         $arr[$item['thr-parent']] = 1;
774                 else
775                         $arr[$item['thr-parent']] ++;
776                 $arr[$item['thr-parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
777         }
778         return;
779 }}
780
781 // Format the like/dislike text for a profile item
782 // $cnt = number of people who like/dislike the item
783 // $arr = array of pre-linked names of likers/dislikers
784 // $type = one of 'like, 'dislike'
785 // $id  = item id
786 // returns formatted text
787
788 if(! function_exists('format_like')) {
789 function format_like($cnt,$arr,$type,$id) {
790         $o = '';
791         if($cnt == 1)
792                 $o .= (($type === 'like') ? sprintf( t('%s likes this.'), $arr[0]) : sprintf( t('%s doesn\'t like this.'), $arr[0])) . EOL ;
793         else {
794                 $spanatts = 'class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');"';
795                 $o .= (($type === 'like') ?
796                                         sprintf( t('<span  %1$s>%2$d people</span> like this.'), $spanatts, $cnt)
797                                          :
798                                         sprintf( t('<span  %1$s>%2$d people</span> don\'t like this.'), $spanatts, $cnt) );
799                 $o .= EOL ;
800                 $total = count($arr);
801                 if($total >= MAX_LIKERS)
802                         $arr = array_slice($arr, 0, MAX_LIKERS - 1);
803                 if($total < MAX_LIKERS)
804                         $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
805                 $str = implode(', ', $arr);
806                 if($total >= MAX_LIKERS)
807                         $str .= sprintf( t(', and %d other people'), $total - MAX_LIKERS );
808                 $str = (($type === 'like') ? sprintf( t('%s like this.'), $str) : sprintf( t('%s don\'t like this.'), $str));
809                 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
810         }
811         return $o;
812 }}
813
814
815 function status_editor($a,$x, $notes_cid = 0, $popup=false) {
816
817         $o = '';
818
819         $geotag = (($x['allow_location']) ? get_markup_template('jot_geotag.tpl') : '');
820
821         $plaintext = false;
822         if(local_user() && intval(get_pconfig(local_user(),'system','plaintext')))
823                 $plaintext = true;
824
825         $tpl = get_markup_template('jot-header.tpl');
826         $a->page['htmlhead'] .= replace_macros($tpl, array(
827                 '$newpost' => 'true',
828                 '$baseurl' => $a->get_baseurl(true),
829                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
830                 '$geotag' => $geotag,
831                 '$nickname' => $x['nickname'],
832                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
833                 '$linkurl' => t('Please enter a link URL:'),
834                 '$vidurl' => t("Please enter a video link/URL:"),
835                 '$audurl' => t("Please enter an audio link/URL:"),
836                 '$term' => t('Tag term:'),
837                 '$fileas' => t('Save to Folder:'),
838                 '$whereareu' => t('Where are you right now?')
839         ));
840
841
842         $tpl = get_markup_template('jot-end.tpl');
843         $a->page['end'] .= replace_macros($tpl, array(
844                 '$newpost' => 'true',
845                 '$baseurl' => $a->get_baseurl(true),
846                 '$editselect' => (($plaintext) ? 'none' : '/(profile-jot-text|prvmail-text)/'),
847                 '$geotag' => $geotag,
848                 '$nickname' => $x['nickname'],
849                 '$ispublic' => t('Visible to <strong>everybody</strong>'),
850                 '$linkurl' => t('Please enter a link URL:'),
851                 '$vidurl' => t("Please enter a video link/URL:"),
852                 '$audurl' => t("Please enter an audio link/URL:"),
853                 '$term' => t('Tag term:'),
854                 '$fileas' => t('Save to Folder:'),
855                 '$whereareu' => t('Where are you right now?')
856         ));
857
858
859         $tpl = get_markup_template("jot.tpl");
860
861         $jotplugins = '';
862         $jotnets = '';
863
864         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
865
866         $mail_enabled = false;
867         $pubmail_enabled = false;
868
869         if(($x['is_owner']) && (! $mail_disabled)) {
870                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
871                         intval(local_user())
872                 );
873                 if(count($r)) {
874                         $mail_enabled = true;
875                         if(intval($r[0]['pubmail']))
876                                 $pubmail_enabled = true;
877                 }
878         }
879
880         if($mail_enabled) {
881                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
882                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
883         }
884
885         call_hooks('jot_tool', $jotplugins);
886         call_hooks('jot_networks', $jotnets);
887
888         if($notes_cid)
889                 $jotnets .= '<input type="hidden" name="contact_allow[]" value="' . $notes_cid .'" />';
890
891         $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins));
892
893         $o .= replace_macros($tpl,array(
894                 '$return_path' => $a->query_string,
895                 '$action' =>  $a->get_baseurl(true) . '/item',
896                 '$share' => (x($x,'button') ? $x['button'] : t('Share')),
897                 '$upload' => t('Upload photo'),
898                 '$shortupload' => t('upload photo'),
899                 '$attach' => t('Attach file'),
900                 '$shortattach' => t('attach file'),
901                 '$weblink' => t('Insert web link'),
902                 '$shortweblink' => t('web link'),
903                 '$video' => t('Insert video link'),
904                 '$shortvideo' => t('video link'),
905                 '$audio' => t('Insert audio link'),
906                 '$shortaudio' => t('audio link'),
907                 '$setloc' => t('Set your location'),
908                 '$shortsetloc' => t('set location'),
909                 '$noloc' => t('Clear browser location'),
910                 '$shortnoloc' => t('clear location'),
911                 '$title' => "",
912                 '$placeholdertitle' => t('Set title'),
913                 '$category' => "",
914                 '$placeholdercategory' => t('Categories (comma-separated list)'),
915                 '$wait' => t('Please wait'),
916                 '$permset' => t('Permission settings'),
917                 '$shortpermset' => t('permissions'),
918                 '$ptyp' => (($notes_cid) ? 'note' : 'wall'),
919                 '$content' => '',
920                 '$post_id' => '',
921                 '$baseurl' => $a->get_baseurl(true),
922                 '$defloc' => $x['default_location'],
923                 '$visitor' => $x['visitor'],
924                 '$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
925                 '$emailcc' => t('CC: email addresses'),
926                 '$public' => t('Public post'),
927                 '$jotnets' => $jotnets,
928                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
929                 '$lockstate' => $x['lockstate'],
930                 '$acl' => $x['acl'],
931                 '$bang' => $x['bang'],
932                 '$profile_uid' => $x['profile_uid'],
933                 '$preview' => t('Preview'),
934                 '$sourceapp' => t($a->sourcename),
935                 '$cancel' => t('Cancel')
936         ));
937
938
939         if ($popup==true){
940                 $o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
941
942         }
943
944         return $o;
945 }
946
947
948 function get_item_children($arr, $parent) {
949         $children = array();
950         foreach($arr as $item) {
951                 if($item['id'] != $item['parent']) {
952                         if(get_config('system','thread_allow')) {
953                                 // Fallback to parent-uri if thr-parent is not set
954                                 $thr_parent = $item['thr-parent'];
955                                 if($thr_parent == '')
956                                         $thr_parent = $item['parent-uri'];
957
958                                 if($thr_parent == $parent['uri']) {
959                                         $item['children'] = get_item_children($arr, $item);
960                                         $children[] = $item;
961                                 }
962                         }
963                         else if($item['parent'] == $parent['id']) {
964                                 $children[] = $item;
965                         }
966                 }
967         }
968         return $children;
969 }
970
971 function sort_item_children($items) {
972         $result = $items;
973         usort($result,'sort_thr_created_rev');
974         foreach($result as $k => $i) {
975                 if(count($result[$k]['children'])) {
976                         $result[$k]['children'] = sort_item_children($result[$k]['children']);
977                 }
978         }
979         return $result;
980 }
981
982 function add_children_to_list($children, &$arr) {
983         foreach($children as $y) {
984                 $arr[] = $y;
985                 if(count($y['children']))
986                         add_children_to_list($y['children'], $arr);
987         }
988 }
989
990 function conv_sort($arr,$order) {
991
992         if((!(is_array($arr) && count($arr))))
993                 return array();
994
995         $parents = array();
996         $children = array();
997
998         foreach($arr as $x)
999                 if($x['id'] == $x['parent'])
1000                                 $parents[] = $x;
1001
1002         if(stristr($order,'created'))
1003                 usort($parents,'sort_thr_created');
1004         elseif(stristr($order,'commented'))
1005                 usort($parents,'sort_thr_commented');
1006
1007         if(count($parents))
1008                 foreach($parents as $i=>$_x)
1009                         $parents[$i]['children'] = get_item_children($arr, $_x);
1010
1011         /*foreach($arr as $x) {
1012                 if($x['id'] != $x['parent']) {
1013                         $p = find_thread_parent_index($parents,$x);
1014                         if($p !== false)
1015                                 $parents[$p]['children'][] = $x;
1016                 }
1017         }*/
1018         if(count($parents)) {
1019                 foreach($parents as $k => $v) {
1020                         if(count($parents[$k]['children'])) {
1021                                 $parents[$k]['children'] = sort_item_children($parents[$k]['children']);
1022                                 /*$y = $parents[$k]['children'];
1023                                 usort($y,'sort_thr_created_rev');
1024                                 $parents[$k]['children'] = $y;*/
1025                         }
1026                 }
1027         }
1028
1029         $ret = array();
1030         if(count($parents)) {
1031                 foreach($parents as $x) {
1032                         $ret[] = $x;
1033                         if(count($x['children']))
1034                                 add_children_to_list($x['children'], $ret);
1035                                 /*foreach($x['children'] as $y)
1036                                         $ret[] = $y;*/
1037                 }
1038         }
1039
1040         return $ret;
1041 }
1042
1043
1044 function sort_thr_created($a,$b) {
1045         return strcmp($b['created'],$a['created']);
1046 }
1047
1048 function sort_thr_created_rev($a,$b) {
1049         return strcmp($a['created'],$b['created']);
1050 }
1051
1052 function sort_thr_commented($a,$b) {
1053         return strcmp($b['commented'],$a['commented']);
1054 }
1055
1056 function find_thread_parent_index($arr,$x) {
1057         foreach($arr as $k => $v)
1058                 if($v['id'] == $x['parent'])
1059                         return $k;
1060         return false;
1061 }
1062
1063 function render_location_google($item) {
1064         $location = (($item['location']) ? '<a target="map" title="' . $item['location'] . '" href="http://maps.google.com/?q=' . urlencode($item['location']) . '">' . $item['location'] . '</a>' : '');
1065         $coord = (($item['coord']) ? '<a target="map" title="' . $item['coord'] . '" href="http://maps.google.com/?q=' . urlencode($item['coord']) . '">' . $item['coord'] . '</a>' : '');
1066         if($coord) {
1067                 if($location)
1068                         $location .= '<br /><span class="smalltext">(' . $coord . ')</span>';
1069                 else
1070                         $location = '<span class="smalltext">' . $coord . '</span>';
1071         }
1072         return $location;
1073 }