]> git.mxchange.org Git - friendica.git/blob - mod/content.php
All subqueries in tag searches are now reformed. Further SQL improvements
[friendica.git] / mod / content.php
1 <?php
2
3 // This is a purely experimental module and is not yet generally useful.
4
5 // The eventual goal is to provide a json backend to fetch content and fill the current page.
6 // The page will be filled in on the frontend using javascript.
7 // At the present time this page is based on "network", but the hope is to extend to serving
8 // any content (wall, community, search, etc.).
9 // All search parameters, etc. will be managed in javascript and sent as request params.
10 // Security will be managed on the backend.
11 // There is no "pagination query", but we will manage the "current page" on the client
12 // and provide a link to fetch the next page - until there are no pages left to fetch.
13
14 // With the exception of complex tag and text searches, this prototype is incredibly 
15 // fast - e.g. one or two milliseconds to fetch parent items for the current content, 
16 // and 10-20 milliseconds to fetch all the child items.
17
18
19 function content_content(&$a, $update = 0) {
20
21         require_once('include/conversation.php');
22
23
24         // Currently security is based on the logged in user
25
26         if(! local_user()) {
27                 return;
28         }
29
30         $arr = array('query' => $a->query_string);
31
32         call_hooks('content_content_init', $arr);
33
34
35         $datequery = $datequery2 = '';
36
37         $group = 0;
38
39         $nouveau = false;
40
41         if($a->argc > 1) {
42                 for($x = 1; $x < $a->argc; $x ++) {
43                         if(is_a_date_arg($a->argv[$x])) {
44                                 if($datequery)
45                                         $datequery2 = escape_tags($a->argv[$x]);
46                                 else {
47                                         $datequery = escape_tags($a->argv[$x]);
48                                         $_GET['order'] = 'post';
49                                 }
50                         }
51                         elseif($a->argv[$x] === 'new') {
52                                 $nouveau = true;
53                         }
54                         elseif(intval($a->argv[$x])) {
55                                 $group = intval($a->argv[$x]);
56                                 $def_acl = array('allow_gid' => '<' . $group . '>');
57                         }
58                 }
59         }
60
61
62         $o = '';
63
64         
65
66         $contact_id = $a->cid;
67
68         require_once('include/acl_selectors.php');
69
70         $cid = ((x($_GET,'cid')) ? intval($_GET['cid']) : 0);
71         $star = ((x($_GET,'star')) ? intval($_GET['star']) : 0);
72         $bmark = ((x($_GET,'bmark')) ? intval($_GET['bmark']) : 0);
73         $order = ((x($_GET,'order')) ? notags($_GET['order']) : 'comment');
74         $liked = ((x($_GET,'liked')) ? intval($_GET['liked']) : 0);
75         $conv = ((x($_GET,'conv')) ? intval($_GET['conv']) : 0);
76         $spam = ((x($_GET,'spam')) ? intval($_GET['spam']) : 0);
77         $nets = ((x($_GET,'nets')) ? $_GET['nets'] : '');
78         $cmin = ((x($_GET,'cmin')) ? intval($_GET['cmin']) : 0);
79         $cmax = ((x($_GET,'cmax')) ? intval($_GET['cmax']) : 99);
80         $file = ((x($_GET,'file')) ? $_GET['file'] : '');
81
82
83
84         if(x($_GET,'search') || x($_GET,'file'))
85                 $nouveau = true;
86         if($cid)
87                 $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
88
89         if($nets) {
90                 $r = q("select id from contact where uid = %d and network = '%s' and self = 0",
91                         intval(local_user()),
92                         dbesc($nets)
93                 );
94
95                 $str = '';
96                 if(count($r))
97                         foreach($r as $rr)
98                                 $str .= '<' . $rr['id'] . '>';
99                 if(strlen($str))
100                         $def_acl = array('allow_cid' => $str);
101         }
102
103         
104         $sql_options  = (($star) ? " and starred = 1 " : '');
105         $sql_options .= (($bmark) ? " and bookmark = 1 " : '');
106
107         $sql_nets = (($nets) ? sprintf(" and `contact`.`network` = '%s' ", dbesc($nets)) : '');
108
109         $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` $sql_options ) ";
110
111         if($group) {
112                 $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1",
113                         intval($group),
114                         intval($_SESSION['uid'])
115                 );
116                 if(! count($r)) {
117                         if($update)
118                                 killme();
119                         notice( t('No such group') . EOL );
120                         goaway($a->get_baseurl(true) . '/network');
121                         // NOTREACHED
122                 }
123
124                 $contacts = expand_groups(array($group));
125                 if((is_array($contacts)) && count($contacts)) {
126                         $contact_str = implode(',',$contacts);
127                 }
128                 else {
129                                 $contact_str = ' 0 ';
130                                 info( t('Group is empty'));
131                 }
132
133                 $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 $sql_options AND ( `contact-id` IN ( $contact_str ) OR `allow_gid` like '" . protect_sprintf('%<' . intval($group) . '>%') . "' ) and deleted = 0 ) ";
134                 $o = '<h2>' . t('Group: ') . $r[0]['name'] . '</h2>' . $o;
135         }
136         elseif($cid) {
137
138                 $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d 
139                                 AND `blocked` = 0 AND `pending` = 0 LIMIT 1",
140                         intval($cid)
141                 );
142                 if(count($r)) {
143                         $sql_extra = " AND `item`.`parent` IN ( SELECT DISTINCT(`parent`) FROM `item` WHERE 1 $sql_options AND `contact-id` = " . intval($cid) . " and deleted = 0 ) ";
144
145                 }
146                 else {
147                         killme();
148                 }
149         }
150
151
152         $sql_extra3 = '';
153
154         if($datequery) {
155                 $sql_extra3 .= protect_sprintf(sprintf(" AND item.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery))));
156         }
157         if($datequery2) {
158                 $sql_extra3 .= protect_sprintf(sprintf(" AND item.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2))));
159         }
160
161         $sql_extra2 = (($nouveau) ? '' : " AND `item`.`parent` = `item`.`id` ");
162         $sql_extra3 = (($nouveau) ? '' : $sql_extra3);
163         $sql_table = "`item`";
164
165         if(x($_GET,'search')) {
166                 $search = escape_tags($_GET['search']);
167
168                 if(strpos($search,'#') === 0) {
169                         $tag = true;
170                         $search = substr($search,1);
171                 }
172
173                 if (get_config('system','only_tag_search'))
174                         $tag = true;
175
176                 /*if (get_config('system','use_fulltext_engine')) {
177                         if(strpos($search,'#') === 0)
178                                 $sql_extra .= sprintf(" AND (MATCH(tag) AGAINST ('%s' in boolean mode)) ",
179                                         dbesc(protect_sprintf($search))
180                                 );
181                         else
182                                 $sql_extra .= sprintf(" AND (MATCH(`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode)) ",
183                                         dbesc(protect_sprintf($search)),
184                                         dbesc(protect_sprintf($search))
185                                 );
186                 } else {
187                         $sql_extra .= sprintf(" AND ( `item`.`body` like '%s' OR `item`.`tag` like '%s' ) ",
188                                         dbesc(protect_sprintf('%' . $search . '%')),
189                                         dbesc(protect_sprintf('%]' . $search . '[%'))
190                         );
191                 }*/
192
193                 if($tag) {
194                         //$sql_extra = sprintf(" AND `term`.`term` = '%s' AND `term`.`otype` = %d AND `term`.`type` = %d ",
195                         //      dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG));
196                         //$sql_table = "`term` LEFT JOIN `item` ON `item`.`id` = `term`.`oid` AND `item`.`uid` = `term`.`uid` ";
197
198                         $sql_extra = "";
199                         $sql_table = sprintf("`item` INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
200                                 dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(local_user()));
201
202                 } else {
203                         if (get_config('system','use_fulltext_engine'))
204                                 $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
205                         else
206                                 $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
207                 }
208
209         }
210         if(strlen($file)) {
211                 $sql_extra .= file_tag_file_query('item',unxmlify($file));
212         }
213
214         if($conv) {
215                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
216                 $myurl = substr($myurl,strpos($myurl,'://')+3);
217                 $myurl = str_replace('www.','',$myurl);
218                 $diasp_url = str_replace('/profile/','/u/',$myurl);
219                 /*if (get_config('system','use_fulltext_engine'))
220                         $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from $sql_table where (MATCH(`author-link`, `tag`) AGAINST ('%s' in boolean mode) or MATCH(tag) AGAINST ('%s' in boolean mode))) ",
221                                 dbesc(protect_sprintf($myurl)),
222                                 dbesc(protect_sprintf($myurl)),
223                                 dbesc(protect_sprintf($diasp_url))
224                         );
225                 else
226                         $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from $sql_table where ( `author-link` like '%s' or `tag` like '%s' or tag like '%s' )) ",
227                                 dbesc(protect_sprintf('%' . $myurl)),
228                                 dbesc(protect_sprintf('%' . $myurl . ']%')),
229                                 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
230                         );*/
231
232                 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
233                         dbesc(protect_sprintf($myurl)),
234                         dbesc(protect_sprintf($myurl))
235                 );
236         }
237
238         $pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage']));
239
240
241         if($nouveau) {
242                 // "New Item View" - show all items unthreaded in reverse created date order
243
244                 $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,
245                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,
246                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
247                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
248                         FROM $sql_table LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
249                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1
250                         AND `item`.`deleted` = 0 and `item`.`moderated` = 0
251                         $simple_update
252                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
253                         $sql_extra $sql_nets
254                         ORDER BY `item`.`received` DESC $pager_sql ",
255                         intval($_SESSION['uid'])
256                 );
257
258         }
259         else {
260
261                 // Normal conversation view
262
263
264                 if($order === 'post')
265                                 $ordering = "`created`";
266                 else
267                                 $ordering = "`commented`";
268
269                 $start = dba_timer();
270
271                 $r = q("SELECT `item`.`id` AS `item_id`, `contact`.`uid` AS `contact_uid`
272                         FROM $sql_table LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
273                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0
274                         AND `item`.`moderated` = 0 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
275                         AND `item`.`parent` = `item`.`id`
276                         $sql_extra3 $sql_extra $sql_nets
277                         ORDER BY `item`.$ordering DESC $pager_sql ",
278                         intval(local_user())
279                 );
280
281                 $first = dba_timer();
282
283
284                 // Then fetch all the children of the parents that are on this page
285
286                 $parents_arr = array();
287                 $parents_str = '';
288
289                 if(count($r)) {
290                         foreach($r as $rr)
291                                 if(! in_array($rr['item_id'],$parents_arr))
292                                         $parents_arr[] = $rr['item_id'];
293                         $parents_str = implode(', ', $parents_arr);
294
295                         $items = q("SELECT `item`.*, `item`.`id` AS `item_id`,
296                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,
297                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
298                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
299                                 FROM $sql_table LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
300                                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0
301                                 AND `item`.`moderated` = 0
302                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
303                                 AND `item`.`parent` IN ( %s )
304                                 $sql_extra ",
305                                 intval(local_user()),
306                                 dbesc($parents_str)
307                         );
308
309                         $second = dba_timer();
310
311                         $items = conv_sort($items,$ordering);
312
313                 } else {
314                         $items = array();
315                 }
316         }
317
318
319         logger('parent dba_timer: ' . sprintf('%01.4f',$first - $start));
320         logger('child  dba_timer: ' . sprintf('%01.4f',$second - $first));
321
322         // Set this so that the conversation function can find out contact info for our wall-wall items
323         $a->page_contact = $a->contact;
324
325         $mode = (($nouveau) ? 'network-new' : 'network');
326
327         $o = render_content($a,$items,$mode,false);
328
329
330         header('Content-type: application/json');
331         echo json_encode($o);
332         killme();
333 }
334
335
336
337 function render_content(&$a, $items, $mode, $update, $preview = false) {
338
339
340         require_once('include/bbcode.php');
341
342         $ssl_state = ((local_user()) ? true : false);
343
344         $profile_owner = 0;
345         $page_writeable      = false;
346
347         $previewing = (($preview) ? ' preview ' : '');
348
349         if($mode === 'network') {
350                 $profile_owner = local_user();
351                 $page_writeable = true;
352         }
353
354         if($mode === 'profile') {
355                 $profile_owner = $a->profile['profile_uid'];
356                 $page_writeable = can_write_wall($a,$profile_owner);
357         }
358
359         if($mode === 'notes') {
360                 $profile_owner = local_user();
361                 $page_writeable = true;
362         }
363
364         if($mode === 'display') {
365                 $profile_owner = $a->profile['uid'];
366                 $page_writeable = can_write_wall($a,$profile_owner);
367         }
368
369         if($mode === 'community') {
370                 $profile_owner = 0;
371                 $page_writeable = false;
372         }
373
374         if($update)
375                 $return_url = $_SESSION['return_url'];
376         else
377                 $return_url = $_SESSION['return_url'] = $a->query_string;
378
379         load_contact_links(local_user());
380
381         $cb = array('items' => $items, 'mode' => $mode, 'update' => $update, 'preview' => $preview);
382         call_hooks('conversation_start',$cb);
383
384         $items = $cb['items'];
385
386         $cmnt_tpl    = get_markup_template('comment_item.tpl');
387         $tpl         = 'wall_item.tpl';
388         $wallwall    = 'wallwall_item.tpl';
389         $hide_comments_tpl = get_markup_template('hide_comments.tpl');
390
391         $alike = array();
392         $dlike = array();
393         
394         
395         // array with html for each thread (parent+comments)
396         $threads = array();
397         $threadsid = -1;
398         
399         if($items && count($items)) {
400
401                 if($mode === 'network-new' || $mode === 'search' || $mode === 'community') {
402
403                         // "New Item View" on network page or search page results 
404                         // - just loop through the items and format them minimally for display
405
406                         //$tpl = get_markup_template('search_item.tpl');
407                         $tpl = 'search_item.tpl';
408
409                         foreach($items as $item) {
410                                 $threadsid++;
411
412                                 $comment     = '';
413                                 $owner_url   = '';
414                                 $owner_photo = '';
415                                 $owner_name  = '';
416                                 $sparkle     = '';
417
418                                 if($mode === 'search' || $mode === 'community') {
419                                         if(((activity_match($item['verb'],ACTIVITY_LIKE)) || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
420                                                 && ($item['id'] != $item['parent']))
421                                                 continue;
422                                         $nickname = $item['nickname'];
423                                 }
424                                 else
425                                         $nickname = $a->user['nickname'];
426                                 
427                                 // prevent private email from leaking.
428                                 if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
429                                                 continue;
430                         
431                                 $profile_name   = ((strlen($item['author-name']))   ? $item['author-name']   : $item['name']);
432                                 if($item['author-link'] && (! $item['author-name']))
433                                         $profile_name = $item['author-link'];
434
435
436
437                                 $sp = false;
438                                 $profile_link = best_link_url($item,$sp);
439                                 if($profile_link === 'mailbox')
440                                         $profile_link = '';
441                                 if($sp)
442                                         $sparkle = ' sparkle';
443                                 else
444                                         $profile_link = zrl($profile_link);                                     
445
446                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
447                                 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
448                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
449                                 else
450                                         $profile_avatar = ((strlen($item['author-avatar'])) ? $a->get_cached_avatar_image($item['author-avatar']) : $item['thumb']);
451
452                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
453                                 call_hooks('render_location',$locate);
454
455                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
456
457                                 localize_item($item);
458                                 if($mode === 'network-new')
459                                         $dropping = true;
460                                 else
461                                         $dropping = false;
462
463
464                                 $drop = array(
465                                         'dropping' => $dropping,
466                                         'select' => t('Select'), 
467                                         'delete' => t('Delete'),
468                                 );
469
470                                 $star = false;
471                                 $isstarred = "unstarred";
472                                 
473                                 $lock = false;
474                                 $likebuttons = false;
475                                 $shareable = false;
476
477                                 $body = prepare_body($item,true);
478
479                                 if($a->theme['template_engine'] === 'internal') {
480                                         $name_e = template_escape($profile_name);
481                                         $title_e = template_escape($item['title']);
482                                         $body_e = template_escape($body);
483                                         $text_e = strip_tags(template_escape($body));
484                                         $location_e = template_escape($location);
485                                         $owner_name_e = template_escape($owner_name);
486                                 }
487                                 else {
488                                         $name_e = $profile_name;
489                                         $title_e = $item['title'];
490                                         $body_e = $body;
491                                         $text_e = strip_tags($body);
492                                         $location_e = $location;
493                                         $owner_name_e = $owner_name;
494                                 }
495                                 
496                                 //$tmp_item = replace_macros($tpl,array(
497                                 $tmp_item = array(
498                                         'template' => $tpl,
499                                         'id' => (($preview) ? 'P0' : $item['item_id']),
500                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
501                                         'profile_url' => $profile_link,
502                                         'item_photo_menu' => item_photo_menu($item),
503                                         'name' => $name_e,
504                                         'sparkle' => $sparkle,
505                                         'lock' => $lock,
506                                         'thumb' => $profile_avatar,
507                                         'title' => $title_e,
508                                         'body' => $body_e,
509                                         'text' => $text_e,
510                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
511                                         'location' => $location_e,
512                                         'indent' => '',
513                                         'owner_name' => $owner_name_e,
514                                         'owner_url' => $owner_url,
515                                         'owner_photo' => $owner_photo,
516                                         'plink' => get_plink($item),
517                                         'edpost' => false,
518                                         'isstarred' => $isstarred,
519                                         'star' => $star,
520                                         'drop' => $drop,
521                                         'vote' => $likebuttons,
522                                         'like' => '',
523                                         'dislike' => '',
524                                         'comment' => '',
525                                         'conv' => (($preview) ? '' : array('href'=> $a->get_baseurl($ssl_state) . '/display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
526                                         'previewing' => $previewing,
527                                         'wait' => t('Please wait'),
528                                 );
529
530                                 $arr = array('item' => $item, 'output' => $tmp_item);
531                                 call_hooks('display_item', $arr);
532
533                                 $threads[$threadsid]['id'] = $item['item_id'];
534                                 $threads[$threadsid]['items'] = array($arr['output']);
535
536                         }
537
538                 }
539                 else
540                 {
541                         // Normal View
542
543
544                         // Figure out how many comments each parent has
545                         // (Comments all have gravity of 6)
546                         // Store the result in the $comments array
547
548                         $comments = array();
549                         foreach($items as $item) {
550                                 if((intval($item['gravity']) == 6) && ($item['id'] != $item['parent'])) {
551                                         if(! x($comments,$item['parent']))
552                                                 $comments[$item['parent']] = 1;
553                                         else
554                                                 $comments[$item['parent']] += 1;
555                                 } elseif(! x($comments,$item['parent'])) 
556                                         $comments[$item['parent']] = 0; // avoid notices later on
557                         }
558
559                         // map all the like/dislike activities for each parent item 
560                         // Store these in the $alike and $dlike arrays
561
562                         foreach($items as $item) {
563                                 like_puller($a,$item,$alike,'like');
564                                 like_puller($a,$item,$dlike,'dislike');
565                         }
566
567                         $comments_collapsed = false;
568                         $comments_seen = 0;
569                         $comment_lastcollapsed = false;
570                         $comment_firstcollapsed = false;
571                         $blowhard = 0;
572                         $blowhard_count = 0;
573
574
575                         foreach($items as $item) {
576
577                                 $comment = '';
578                                 $template = $tpl;
579                                 $commentww = '';
580                                 $sparkle = '';
581                                 $owner_url = $owner_photo = $owner_name = '';
582
583                                 // We've already parsed out like/dislike for special treatment. We can ignore them now
584
585                                 if(((activity_match($item['verb'],ACTIVITY_LIKE)) 
586                                         || (activity_match($item['verb'],ACTIVITY_DISLIKE))) 
587                                         && ($item['id'] != $item['parent']))
588                                         continue;
589
590                                 $toplevelpost = (($item['id'] == $item['parent']) ? true : false);
591
592
593                                 // Take care of author collapsing and comment collapsing
594                                 // (author collapsing is currently disabled)
595                                 // If a single author has more than 3 consecutive top-level posts, squash the remaining ones.
596                                 // If there are more than two comments, squash all but the last 2.
597                         
598                                 if($toplevelpost) {
599
600                                         $item_writeable = (($item['writable'] || $item['self']) ? true : false);
601
602                                         $comments_seen = 0;
603                                         $comments_collapsed = false;
604                                         $comment_lastcollapsed  = false;
605                                         $comment_firstcollapsed = false;
606                                         
607                                         $threadsid++;
608                                         $threads[$threadsid]['id'] = $item['item_id'];
609                                         $threads[$threadsid]['private'] = $item['private'];
610                                         $threads[$threadsid]['items'] = array();
611
612                                 }
613                                 else {
614
615                                         // prevent private email reply to public conversation from leaking.
616                                         if($item['network'] === NETWORK_MAIL && local_user() != $item['uid'])
617                                                         continue;
618
619                                         $comments_seen ++;
620                                         $comment_lastcollapsed  = false;
621                                         $comment_firstcollapsed = false;
622                                 }       
623
624                                 $override_comment_box = ((($page_writeable) && ($item_writeable)) ? true : false);
625                                 $show_comment_box = ((($page_writeable) && ($item_writeable) && ($comments_seen == $comments[$item['parent']])) ? true : false);
626
627
628                                 if(($comments[$item['parent']] > 2) && ($comments_seen <= ($comments[$item['parent']] - 2)) && ($item['gravity'] == 6)) {
629
630                                         if (!$comments_collapsed){
631                                                 $threads[$threadsid]['num_comments'] = sprintf( tt('%d comment','%d comments',$comments[$item['parent']]),$comments[$item['parent']] );
632                                                 $threads[$threadsid]['hidden_comments_num'] = $comments[$item['parent']];
633                                                 $threads[$threadsid]['hidden_comments_text'] = tt('comment', 'comments', $comments[$item['parent']]);
634                                                 $threads[$threadsid]['hide_text'] = t('show more');
635                                                 $comments_collapsed = true;
636                                                 $comment_firstcollapsed = true;
637                                         }
638                                 }
639                                 if(($comments[$item['parent']] > 2) && ($comments_seen == ($comments[$item['parent']] - 1))) {
640
641                                         $comment_lastcollapsed = true;
642                                 }
643
644                                 $redirect_url = $a->get_baseurl($ssl_state) . '/redir/' . $item['cid'] ;
645
646                                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) 
647                                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
648                                         ? t('Private Message')
649                                         : false);
650
651
652                                 // Top-level wall post not written by the wall owner (wall-to-wall)
653                                 // First figure out who owns it. 
654
655                                 $osparkle = '';
656
657                                 if(($toplevelpost) && (! $item['self']) && ($mode !== 'profile')) {
658
659                                         if($item['wall']) {
660
661                                                 // On the network page, I am the owner. On the display page it will be the profile owner.
662                                                 // This will have been stored in $a->page_contact by our calling page.
663                                                 // Put this person as the wall owner of the wall-to-wall notice.
664
665                                                 $owner_url = zrl($a->page_contact['url']);
666                                                 $owner_photo = $a->page_contact['thumb'];
667                                                 $owner_name = $a->page_contact['name'];
668                                                 $template = $wallwall;
669                                                 $commentww = 'ww';      
670                                         }
671
672                                         if((! $item['wall']) && $item['owner-link']) {
673
674                                                 $owner_linkmatch = (($item['owner-link']) && link_compare($item['owner-link'],$item['author-link']));
675                                                 $alias_linkmatch = (($item['alias']) && link_compare($item['alias'],$item['author-link']));
676                                                 $owner_namematch = (($item['owner-name']) && $item['owner-name'] == $item['author-name']);
677                                                 if((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
678
679                                                         // The author url doesn't match the owner (typically the contact)
680                                                         // and also doesn't match the contact alias. 
681                                                         // The name match is a hack to catch several weird cases where URLs are 
682                                                         // all over the park. It can be tricked, but this prevents you from
683                                                         // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
684                                                         // well that it's the same Bob Smith. 
685
686                                                         // But it could be somebody else with the same name. It just isn't highly likely. 
687                                                         
688
689                                                         $owner_url = $item['owner-link'];
690                                                         $owner_photo = $item['owner-avatar'];
691                                                         $owner_name = $item['owner-name'];
692                                                         $template = $wallwall;
693                                                         $commentww = 'ww';
694                                                         // If it is our contact, use a friendly redirect link
695                                                         if((link_compare($item['owner-link'],$item['url'])) 
696                                                                 && ($item['network'] === NETWORK_DFRN)) {
697                                                                 $owner_url = $redirect_url;
698                                                                 $osparkle = ' sparkle';
699                                                         }
700                                                         else
701                                                                 $owner_url = zrl($owner_url);
702                                                 }
703                                         }
704                                 }
705
706                                 $likebuttons = '';
707                                 $shareable = ((($profile_owner == local_user()) && ($item['private'] != 1)) ? true : false); 
708
709                                 if($page_writeable) {
710 /*                                      if($toplevelpost) {  */
711                                                 $likebuttons = array(
712                                                         'like' => array( t("I like this \x28toggle\x29"), t("like")),
713                                                         'dislike' => array( t("I don't like this \x28toggle\x29"), t("dislike")),
714                                                 );
715                                                 if ($shareable) $likebuttons['share'] = array( t('Share this'), t('share'));
716 /*                                      } */
717
718                                         $qc = $qcomment =  null;
719
720                                         if(in_array('qcomment',$a->plugins)) {
721                                                 $qc = ((local_user()) ? get_pconfig(local_user(),'qcomment','words') : null);
722                                                 $qcomment = (($qc) ? explode("\n",$qc) : null);
723                                         }
724
725                                         if(($show_comment_box) || (($show_comment_box == false) && ($override_comment_box == false) && ($item['last-child']))) {
726                                                 $comment = replace_macros($cmnt_tpl,array(
727                                                         '$return_path' => '', 
728                                                         '$jsreload' => (($mode === 'display') ? $_SESSION['return_url'] : ''),
729                                                         '$type' => (($mode === 'profile') ? 'wall-comment' : 'net-comment'),
730                                                         '$id' => $item['item_id'],
731                                                         '$parent' => $item['parent'],
732                                                         '$qcomment' => $qcomment,
733                                                         '$profile_uid' =>  $profile_owner,
734                                                         '$mylink' => $a->contact['url'],
735                                                         '$mytitle' => t('This is you'),
736                                                         '$myphoto' => $a->contact['thumb'],
737                                                         '$comment' => t('Comment'),
738                                                         '$submit' => t('Submit'),
739                                                         '$edbold' => t('Bold'),
740                                                         '$editalic' => t('Italic'),
741                                                         '$eduline' => t('Underline'),
742                                                         '$edquote' => t('Quote'),
743                                                         '$edcode' => t('Code'),
744                                                         '$edimg' => t('Image'),
745                                                         '$edurl' => t('Link'),
746                                                         '$edvideo' => t('Video'),
747                                                         '$preview' => t('Preview'),
748                                                         '$sourceapp' => t($a->sourcename),
749                                                         '$ww' => (($mode === 'network') ? $commentww : ''),
750                                                         '$rand_num' => random_digits(12)
751                                                 ));
752                                         }
753                                 }
754
755                                 if(local_user() && link_compare($a->contact['url'],$item['author-link']))
756                                         $edpost = array($a->get_baseurl($ssl_state)."/editpost/".$item['id'], t("Edit"));
757                                 else
758                                         $edpost = false;
759
760                                 $drop = '';
761                                 $dropping = false;
762
763                                 if((intval($item['contact-id']) && $item['contact-id'] == remote_user()) || ($item['uid'] == local_user()))
764                                         $dropping = true;
765
766                                 $drop = array(
767                                         'dropping' => $dropping,
768                                         'select' => t('Select'), 
769                                         'delete' => t('Delete'),
770                                 );
771
772                                 $star = false;
773                                 $filer = false;
774
775                                 $isstarred = "unstarred";
776                                 if ($profile_owner == local_user()) {
777                                         if($toplevelpost) {
778                                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
779
780                                                 $star = array(
781                                                         'do' => t("add star"),
782                                                         'undo' => t("remove star"),
783                                                         'toggle' => t("toggle star status"),
784                                                         'classdo' => (($item['starred']) ? "hidden" : ""),
785                                                         'classundo' => (($item['starred']) ? "" : "hidden"),
786                                                         'starred' =>  t('starred'),
787                                                         'tagger' => t("add tag"),
788                                                         'classtagger' => "",
789                                                 );
790                                         }
791                                         $filer = t("save to folder");
792                                 }
793
794
795                                 $photo = $item['photo'];
796                                 $thumb = $item['thumb'];
797
798                                 // Post was remotely authored.
799
800                                 $diff_author    = ((link_compare($item['url'],$item['author-link'])) ? false : true);
801
802                                 $profile_name   = (((strlen($item['author-name']))   && $diff_author) ? $item['author-name']   : $item['name']);
803
804                                 if($item['author-link'] && (! $item['author-name']))
805                                         $profile_name = $item['author-link'];
806
807                                 $sp = false;
808                                 $profile_link = best_link_url($item,$sp);
809                                 if($profile_link === 'mailbox')
810                                         $profile_link = '';
811                                 if($sp)
812                                         $sparkle = ' sparkle';
813                                 else
814                                         $profile_link = zrl($profile_link);                                     
815
816                                 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
817                                 if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
818                                         $profile_avatar = $a->contacts[$normalised]['thumb'];
819                                 else
820                                         $profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $a->get_cached_avatar_image($thumb));
821
822                                 $like    = ((x($alike,$item['uri'])) ? format_like($alike[$item['uri']],$alike[$item['uri'] . '-l'],'like',$item['uri']) : '');
823                                 $dislike = ((x($dlike,$item['uri'])) ? format_like($dlike[$item['uri']],$dlike[$item['uri'] . '-l'],'dislike',$item['uri']) : '');
824
825                                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
826                                 call_hooks('render_location',$locate);
827
828                                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_google($locate));
829
830                                 $indent = (($toplevelpost) ? '' : ' comment');
831
832                                 $shiny = "";
833                                 if(strcmp(datetime_convert('UTC','UTC',$item['created']),datetime_convert('UTC','UTC','now - 12 hours')) > 0)
834                                         $shiny = 'shiny'; 
835
836                                 // 
837                                 localize_item($item);
838
839
840                                 $tags=array();
841                                 foreach(explode(',',$item['tag']) as $tag){
842                                         $tag = trim($tag);
843                                         if ($tag!="") $tags[] = bbcode($tag);
844                                 }
845
846                                 // Build the HTML
847
848                                 $body = prepare_body($item,true);
849                                 //$tmp_item = replace_macros($template,
850
851                                 if($a->theme['template_engine'] === 'internal') {
852                                         $body_e = template_escape($body);
853                                         $text_e = strip_tags(template_escape($body));
854                                         $name_e = template_escape($profile_name);
855                                         $title_e = template_escape($item['title']);
856                                         $location_e = template_escape($location);
857                                         $owner_name_e = template_escape($owner_name);
858                                 }
859                                 else {
860                                         $body_e = $body;
861                                         $text_e = strip_tags($body);
862                                         $name_e = $profile_name;
863                                         $title_e = $item['title'];
864                                         $location_e = $location;
865                                         $owner_name_e = $owner_name;
866                                 }
867
868                                 $tmp_item = array(
869                                         // collapse comments in template. I don't like this much...
870                                         'comment_firstcollapsed' => $comment_firstcollapsed,
871                                         'comment_lastcollapsed' => $comment_lastcollapsed,
872                                         // template to use to render item (wall, walltowall, search)
873                                         'template' => $template,
874                                         
875                                         'type' => implode("",array_slice(explode("/",$item['verb']),-1)),
876                                         'tags' => $tags,
877                                         'body' => $body_e,
878                                         'text' => $text_e,
879                                         'id' => $item['item_id'],
880                                         'linktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
881                                         'olinktitle' => sprintf( t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
882                                         'to' => t('to'),
883                                         'wall' => t('Wall-to-Wall'),
884                                         'vwall' => t('via Wall-To-Wall:'),
885                                         'profile_url' => $profile_link,
886                                         'item_photo_menu' => item_photo_menu($item),
887                                         'name' => $name_e,
888                                         'thumb' => $profile_avatar,
889                                         'osparkle' => $osparkle,
890                                         'sparkle' => $sparkle,
891                                         'title' => $title_e,
892                                         'ago' => (($item['app']) ? sprintf( t('%s from %s'),relative_date($item['created']),$item['app']) : relative_date($item['created'])),
893                                         'lock' => $lock,
894                                         'location' => $location_e,
895                                         'indent' => $indent,
896                                         'shiny' => $shiny,
897                                         'owner_url' => $owner_url,
898                                         'owner_photo' => $owner_photo,
899                                         'owner_name' => $owner_name_e,
900                                         'plink' => get_plink($item),
901                                         'edpost' => $edpost,
902                                         'isstarred' => $isstarred,
903                                         'star' => $star,
904                                         'filer' => $filer,
905                                         'drop' => $drop,
906                                         'vote' => $likebuttons,
907                                         'like' => $like,
908                                         'dislike' => $dislike,
909                                         'comment' => $comment,
910                                         'previewing' => $previewing,
911                                         'wait' => t('Please wait'),
912
913                                 );
914
915
916                                 $arr = array('item' => $item, 'output' => $tmp_item);
917                                 call_hooks('display_item', $arr);
918
919                                 $threads[$threadsid]['items'][] = $arr['output'];
920                         }
921                 }
922         }
923
924
925         return $threads;
926
927 }