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