]> git.mxchange.org Git - friendica.git/blob - mod/network.php
585c063f567da09689fbc9567606f09a3abd4694
[friendica.git] / mod / network.php
1 <?php
2 function network_init(&$a) {
3         if(! local_user()) {
4                 notice( t('Permission denied.') . EOL);
5                 return;
6         }
7
8         $is_a_date_query = false;
9
10         if($a->argc > 1) {
11                 for($x = 1; $x < $a->argc; $x ++) {
12                         if(is_a_date_arg($a->argv[$x])) {
13                                 $is_a_date_query = true;
14                                 break;
15                         }
16                 }
17         }
18
19     // convert query string to array and remove first element (which is friendica args)
20     $query_array = array();
21     parse_str($a->query_string, $query_array);
22     array_shift($query_array);
23
24         // fetch last used network view and redirect if needed
25         if(! $is_a_date_query) {
26                 $sel_tabs = network_query_get_sel_tab($a);
27                 $sel_nets = network_query_get_sel_net();
28                 $sel_groups = network_query_get_sel_group($a);
29                 $last_sel_tabs = get_pconfig(local_user(), 'network.view','tab.selected');
30                 $last_sel_nets = get_pconfig(local_user(), 'network.view', 'net.selected');
31                 $last_sel_groups = get_pconfig(local_user(), 'network.view', 'group.selected');
32
33                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
34                 $remember_net = ($sel_nets === false && $last_sel_nets && $last_sel_nets !== 'all');
35                 $remember_group = ($sel_groups === false && $last_sel_groups && $last_sel_groups != 0);
36
37                 $net_baseurl = '/network';
38                 $net_args = array();
39
40                 if($remember_group) {
41                         $net_baseurl .= '/' . $last_sel_groups; // Note that the group number must come before the "/new" tab selection
42                 }
43                 else if($sel_groups !== false) {
44                         $net_baseurl .= '/' . $sel_groups;
45                 }
46
47                 if($remember_tab) {
48                         // redirect if current selected tab is '/network' and
49                         // last selected tab is _not_ '/network?f=&order=comment'.
50                         // and this isn't a date query
51
52                         $tab_baseurls = array(
53                                 '',             //all
54                                 '',             //postord
55                                 '',             //conv
56                                 '/new', //new
57                                 '',             //starred
58                                 '',             //bookmarked
59                                 '',             //spam
60                         );
61                         $tab_args = array(
62                                 'f=&order=comment',     //all
63                                 'f=&order=post',                //postord
64                                 'f=&conv=1',                    //conv
65                                 '',                                     //new
66                                 'f=&star=1',                    //starred
67                                 'f=&bmark=1',                   //bookmarked
68                                 'f=&spam=1',                    //spam
69                         );
70
71                         $k = array_search('active', $last_sel_tabs);
72
73                         $net_baseurl .= $tab_baseurls[$k];
74
75             // parse out tab queries
76             $dest_qa = array();
77             $dest_qs = $tab_args[$k];
78             parse_str( $dest_qs, $dest_qa);
79             $net_args = array_merge($net_args, $dest_qa);
80                 }
81                 else if($sel_tabs[4] === 'active') {
82                         // The '/new' tab is selected
83                         $net_baseurl .= '/new';
84                 }
85
86                 if($remember_net) {
87                         $net_args['nets'] = $last_sel_nets;
88                 }
89
90                 if($remember_tab || $remember_net || $remember_group) {
91                         $net_args = array_merge($query_array, $net_args);
92                         $net_queries = build_querystring($net_args);
93
94                         $redir_url = ($net_queries ? $net_baseurl."?".$net_queries : $net_baseurl);
95                         goaway($a->get_baseurl() . $redir_url);
96                 }
97         }
98
99         if(x($_GET['nets']) && $_GET['nets'] === 'all')
100                 unset($_GET['nets']);
101
102         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
103
104         set_pconfig(local_user(), 'network.view', 'group.selected', $group_id);
105
106         require_once('include/group.php');
107         require_once('include/contact_widgets.php');
108         require_once('include/items.php');
109
110         if(! x($a->page,'aside'))
111                 $a->page['aside'] = '';
112
113         $search = ((x($_GET,'search')) ? escape_tags($_GET['search']) : '');
114
115         if(x($_GET,'save')) {
116                 $r = q("select * from `search` where `uid` = %d and `term` = '%s' limit 1",
117                         intval(local_user()),
118                         dbesc($search)
119                 );
120                 if(! count($r)) {
121                         q("insert into `search` ( `uid`,`term` ) values ( %d, '%s') ",
122                                 intval(local_user()),
123                                 dbesc($search)
124                         );
125                 }
126         }
127         if(x($_GET,'remove')) {
128                 q("delete from `search` where `uid` = %d and `term` = '%s'",
129                         intval(local_user()),
130                         dbesc($search)
131                 );
132         }
133
134         // search terms header
135         if(x($_GET,'search')) {
136                 $a->page['content'] .= '<h2>' . t('Search Results For:') . ' '  . $search . '</h2>';
137         }
138
139         $a->page['aside'] .= (feature_enabled(local_user(),'groups') ? group_side('network/0','network',true,$group_id) : '');
140         $a->page['aside'] .= posted_date_widget($a->get_baseurl() . '/network',local_user(),false);
141         $a->page['aside'] .= networks_widget($a->get_baseurl(true) . '/network',(x($_GET, 'nets') ? $_GET['nets'] : ''));
142         $a->page['aside'] .= saved_searches($search);
143         $a->page['aside'] .= fileas_widget($a->get_baseurl(true) . '/network',(x($_GET, 'file') ? $_GET['file'] : ''));
144
145 }
146
147 function saved_searches($search) {
148
149         if(! feature_enabled(local_user(),'savedsearch'))
150                 return '';
151
152         $a = get_app();
153
154         $srchurl = '/network?f='
155                 . ((x($_GET,'cid'))   ? '&cid='   . $_GET['cid']   : '')
156                 . ((x($_GET,'star'))  ? '&star='  . $_GET['star']  : '')
157                 . ((x($_GET,'bmark')) ? '&bmark=' . $_GET['bmark'] : '')
158                 . ((x($_GET,'conv'))  ? '&conv='  . $_GET['conv']  : '')
159                 . ((x($_GET,'nets'))  ? '&nets='  . $_GET['nets']  : '')
160                 . ((x($_GET,'cmin'))  ? '&cmin='  . $_GET['cmin']  : '')
161                 . ((x($_GET,'cmax'))  ? '&cmax='  . $_GET['cmax']  : '')
162                 . ((x($_GET,'file'))  ? '&file='  . $_GET['file']  : '');
163         ;
164
165         $o = '';
166
167         $r = q("select `id`,`term` from `search` WHERE `uid` = %d",
168                 intval(local_user())
169         );
170
171         $saved = array();
172
173         if(count($r)) {
174                 foreach($r as $rr) {
175                         $saved[] = array(
176                                 'id'            => $rr['id'],
177                                 'term'                  => $rr['term'],
178                                 'encodedterm'   => urlencode($rr['term']),
179                                 'delete'                => t('Remove term'),
180                                 'selected'              => ($search==$rr['term']),
181                         );
182                 }
183         }
184
185
186         $tpl = get_markup_template("saved_searches_aside.tpl");
187         $o = replace_macros($tpl, array(
188                 '$title'         => t('Saved Searches'),
189                 '$add'           => t('add'),
190                 '$searchbox' => search($search,'netsearch-box',$srchurl,true),
191                 '$saved'         => $saved,
192         ));
193
194         return $o;
195
196 }
197
198 /**
199  * Return selected tab from query
200  *
201  * urls -> returns
202  *              '/network'                                      => $no_active = 'active'
203  *              '/network?f=&order=comment'     => $comment_active = 'active'
204  *              '/network?f=&order=post'        => $postord_active = 'active'
205  *              '/network?f=&conv=1',           => $conv_active = 'active'
206  *              '/network/new',                         => $new_active = 'active'
207  *              '/network?f=&star=1',           => $starred_active = 'active'
208  *              '/network?f=&bmark=1',          => $bookmarked_active = 'active'
209  *              '/network?f=&spam=1',           => $spam_active = 'active'
210  *
211  * @return Array ( $no_active, $comment_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active );
212  */
213 function network_query_get_sel_tab($a) {
214         $no_active='';
215         $starred_active = '';
216         $new_active = '';
217         $bookmarked_active = '';
218         $all_active = '';
219         $search_active = '';
220         $conv_active = '';
221         $spam_active = '';
222         $postord_active = '';
223
224         if(($a->argc > 1 && $a->argv[1] === 'new')
225                 || ($a->argc > 2 && $a->argv[2] === 'new')) {
226                         $new_active = 'active';
227         }
228
229         if(x($_GET,'search')) {
230                 $search_active = 'active';
231         }
232
233         if(x($_GET,'star')) {
234                 $starred_active = 'active';
235         }
236
237         if(x($_GET,'bmark')) {
238                 $bookmarked_active = 'active';
239         }
240
241         if(x($_GET,'conv')) {
242                 $conv_active = 'active';
243         }
244
245         if(x($_GET,'spam')) {
246                 $spam_active = 'active';
247         }
248
249
250
251         if (($new_active == '')
252                 && ($starred_active == '')
253                 && ($bookmarked_active == '')
254                 && ($conv_active == '')
255                 && ($search_active == '')
256                 && ($spam_active == '')) {
257                         $no_active = 'active';
258         }
259
260         if ($no_active=='active' && x($_GET,'order')) {
261                 switch($_GET['order']){
262                  case 'post': $postord_active = 'active'; $no_active=''; break;
263                  case 'comment' : $all_active = 'active'; $no_active=''; break;
264                 }
265         }
266
267         return array($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active);
268 }
269
270 /**
271  * Return selected network from query
272  */
273 function network_query_get_sel_net() {
274         $network = false;
275
276         if(x($_GET,'nets')) {
277                 $network = $_GET['nets'];
278         }
279
280         return $network;
281 }
282
283 function network_query_get_sel_group($a) {
284         $group = false;
285
286         if($a->argc >= 2 && is_numeric($a->argv[1])) {
287                 $group = $a->argv[1];
288         }
289
290         return $group;
291 }
292
293
294 function network_content(&$a, $update = 0) {
295
296         require_once('include/conversation.php');
297
298         if(! local_user()) {
299                 $_SESSION['return_url'] = $a->query_string;
300         return login(false);
301         }
302
303         $arr = array('query' => $a->query_string);
304
305         call_hooks('network_content_init', $arr);
306
307
308         $datequery = $datequery2 = '';
309
310         $group = 0;
311
312         $nouveau = false;
313
314         if($a->argc > 1) {
315                 for($x = 1; $x < $a->argc; $x ++) {
316                         if(is_a_date_arg($a->argv[$x])) {
317                                 if($datequery)
318                                         $datequery2 = escape_tags($a->argv[$x]);
319                                 else {
320                                         $datequery = escape_tags($a->argv[$x]);
321                                         $_GET['order'] = 'post';
322                                 }
323                         }
324                         elseif($a->argv[$x] === 'new') {
325                                 $nouveau = true;
326                         }
327                         elseif(intval($a->argv[$x])) {
328                                 $group = intval($a->argv[$x]);
329                                 $def_acl = array('allow_gid' => '<' . $group . '>');
330                         }
331                 }
332         }
333
334         $o = '';
335
336         // item filter tabs
337         // TODO: fix this logic, reduce duplication
338         //$a->page['content'] .= '<div class="tabs-wrapper">';
339
340         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) = network_query_get_sel_tab($a);
341         // if no tabs are selected, defaults to comments
342         if ($no_active=='active') $all_active='active';
343
344         $cmd = (($datequery) ? '' : $a->cmd);
345         $len_naked_cmd = strlen(str_replace('/new','',$cmd));
346
347         // tabs
348         $tabs = array(
349                 array(
350                         'label' => t('Commented Order'),
351                         'url'=>$a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
352                         'sel'=>$all_active,
353                         'title'=> t('Sort by Comment Date'),
354                 ),
355                 array(
356                         'label' => t('Posted Order'),
357                         'url'=>$a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
358                         'sel'=>$postord_active,
359                         'title' => t('Sort by Post Date'),
360                 ),
361         );
362
363         if(feature_enabled(local_user(),'personal_tab')) {
364                 $tabs[] = array(
365                         'label' => t('Personal'),
366                         'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '') . '&conv=1',
367                         'sel' => $conv_active,
368                         'title' => t('Posts that mention or involve you'),
369                 );
370         }
371
372         if(feature_enabled(local_user(),'new_tab')) {
373                 $tabs[] = array(
374                         'label' => t('New'),
375                         'url' => $a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ($len_naked_cmd ? '/' : '') . 'new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
376                         'sel' => $new_active,
377                         'title' => t('Activity Stream - by date'),
378                 );
379         }
380
381         if(feature_enabled(local_user(),'link_tab')) {
382                 $tabs[] = array(
383                         'label' => t('Shared Links'),
384                         'url'=>$a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '') . '&bmark=1',
385                         'sel'=>$bookmarked_active,
386                         'title'=> t('Interesting Links'),
387                 );
388         }
389
390         if(feature_enabled(local_user(),'star_posts')) {
391                 $tabs[] = array(
392                         'label' => t('Starred'),
393                         'url'=>$a->get_baseurl(true) . '/' . str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '') . '&star=1',
394                         'sel'=>$starred_active,
395                         'title' => t('Favourite Posts'),
396                 );
397         }
398
399         // save selected tab, but only if not in search or file mode
400         if(!x($_GET,'search') && !x($_GET,'file')) {
401                 set_pconfig( local_user(), 'network.view','tab.selected',array($all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) );
402         }
403
404         $arr = array('tabs' => $tabs);
405         call_hooks('network_tabs', $arr);
406
407         $o .= replace_macros(get_markup_template('common_tabs.tpl'), array('$tabs'=> $arr['tabs']));
408
409         // --- end item filter tabs
410
411         $contact_id = $a->cid;
412
413         require_once('include/acl_selectors.php');
414
415         $cid = ((x($_GET,'cid')) ? intval($_GET['cid']) : 0);
416         $star = ((x($_GET,'star')) ? intval($_GET['star']) : 0);
417         $bmark = ((x($_GET,'bmark')) ? intval($_GET['bmark']) : 0);
418         $order = ((x($_GET,'order')) ? notags($_GET['order']) : 'comment');
419         $liked = ((x($_GET,'liked')) ? intval($_GET['liked']) : 0);
420         $conv = ((x($_GET,'conv')) ? intval($_GET['conv']) : 0);
421         $spam = ((x($_GET,'spam')) ? intval($_GET['spam']) : 0);
422         $nets = ((x($_GET,'nets')) ? $_GET['nets'] : '');
423         $cmin = ((x($_GET,'cmin')) ? intval($_GET['cmin']) : 0);
424         $cmax = ((x($_GET,'cmax')) ? intval($_GET['cmax']) : 99);
425         $file = ((x($_GET,'file')) ? $_GET['file'] : '');
426
427
428
429         if(x($_GET,'search') || x($_GET,'file'))
430                 $nouveau = true;
431         if($cid)
432                 $def_acl = array('allow_cid' => '<' . intval($cid) . '>');
433
434         if($nets) {
435                 $r = q("select id from contact where uid = %d and network = '%s' and self = 0",
436                         intval(local_user()),
437                         dbesc($nets)
438                 );
439
440                 $str = '';
441                 if(count($r))
442                         foreach($r as $rr)
443                                 $str .= '<' . $rr['id'] . '>';
444                 if(strlen($str))
445                         $def_acl = array('allow_cid' => $str);
446         }
447         set_pconfig(local_user(), 'network.view', 'net.selected', ($nets ? $nets : 'all'));
448
449 /*if ($update) {
450 print_r($_GET);
451 die("ss");
452 }*/
453
454         if(! $update) {
455                 if($group) {
456                         if(($t = group_public_members($group)) && (! get_pconfig(local_user(),'system','nowarn_insecure'))) {
457                                 notice( sprintf( tt('Warning: This group contains %s member from an insecure network.',
458                                                                         'Warning: This group contains %s members from an insecure network.',
459                                                                         $t), $t ) . EOL);
460                                 notice( t('Private messages to this group are at risk of public disclosure.') . EOL);
461                         }
462                 }
463
464                 nav_set_selected('network');
465
466                 $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false);
467
468                 $x = array(
469                         'is_owner' => true,
470                         'allow_location' => $a->user['allow_location'],
471                         'default_location' => $a->user['default-location'],
472                         'nickname' => $a->user['nickname'],
473                         'lockstate' => ((($group) || ($cid) || ($nets) || (is_array($a->user) && ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) || (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid']))))) ? 'lock' : 'unlock'),
474                         'default_perms' => get_acl_permissions($a->user),
475                         'acl' => populate_acl((($group || $cid || $nets) ? $def_acl : $a->user), $celeb),
476                         'bang' => (($group || $cid || $nets) ? '!' : ''),
477                         'visitor' => 'block',
478                         'profile_uid' => local_user(),
479                         'acl_data' => construct_acl_data($a, $a->user), // For non-Javascript ACL selector
480                 );
481
482                 $o .= status_editor($a,$x);
483
484         }
485
486         // We don't have to deal with ACLs on this page. You're looking at everything
487         // that belongs to you, hence you can see all of it. We will filter by group if
488         // desired.
489
490         $sql_post_table = "";
491         $sql_options  = (($star) ? " and starred = 1 " : '');
492         $sql_options .= (($bmark) ? " and bookmark = 1 " : '');
493         $sql_extra = $sql_options;
494         $sql_extra2 = "";
495         $sql_extra3 = "";
496         $sql_table = "`thread`";
497         $sql_parent = "`iid`";
498
499         if ($nouveau OR strlen($file) OR $update) {
500                 $sql_table = "`item`";
501                 $sql_parent = "`parent`";
502         }
503
504         $sql_nets = (($nets) ? sprintf(" and $sql_table.`network` = '%s' ", dbesc($nets)) : '');
505
506         if($group) {
507                 $r = q("SELECT `name`, `id` FROM `group` WHERE `id` = %d AND `uid` = %d LIMIT 1",
508                         intval($group),
509                         intval($_SESSION['uid'])
510                 );
511                 if(! count($r)) {
512                         if($update)
513                                 killme();
514                         notice( t('No such group') . EOL );
515                         goaway($a->get_baseurl(true) . '/network/0');
516                         // NOTREACHED
517                 }
518
519                 $contacts = expand_groups(array($group));
520
521                 $contact_str_self = "";
522
523                 if((is_array($contacts)) && count($contacts)) {
524                         $contact_str = implode(',',$contacts);
525                         $self = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($_SESSION['uid']));
526                         if (count($self))
527                                 $contact_str_self = ",".$self[0]["id"];
528                 }
529                 else {
530                                 $contact_str = ' 0 ';
531                                 info( t('Group is empty'));
532                 }
533
534                 //$sql_post_table = " INNER JOIN (SELECT DISTINCT(`parent`) FROM `item` WHERE (`contact-id` IN ($contact_str) OR `allow_gid` like '".protect_sprintf('%<'.intval($group).'>%')."') and deleted = 0 ORDER BY `created` DESC) AS `temp1` ON $sql_table.$sql_parent = `temp1`.`parent` ";
535
536                 $sql_extra3 .= " AND `contact-id` IN ($contact_str$contact_str_self) ";
537                 $sql_extra3 .= " AND EXISTS (SELECT id FROM `item` WHERE (`contact-id` IN ($contact_str)  OR `allow_gid` like '".protect_sprintf('%<'.intval($group).'>%')."') and deleted = 0 AND parent = $sql_table.$sql_parent) ";
538                 $o = '<h2>' . t('Group: ') . $r[0]['name'] . '</h2>' . $o;
539         } elseif($cid) {
540
541                 $r = q("SELECT `id`,`name`,`network`,`writable`,`nurl` FROM `contact` WHERE `id` = %d
542                                 AND `blocked` = 0 AND `pending` = 0 LIMIT 1",
543                         intval($cid)
544                 );
545                 if(count($r)) {
546                         $sql_post_table = " INNER JOIN (SELECT DISTINCT(`parent`) FROM `item` WHERE 1 $sql_options AND `contact-id` = ".intval($cid)." and deleted = 0 ORDER BY `item`.`received` DESC) AS `temp1` ON $sql_table.$sql_parent = `temp1`.`parent` ";
547                         $sql_extra = "";
548                         $o = '<h2>' . t('Contact: ') . $r[0]['name'] . '</h2>' . $o;
549                         if($r[0]['network'] === NETWORK_OSTATUS && $r[0]['writable'] && (! get_pconfig(local_user(),'system','nowarn_insecure'))) {
550                                 notice( t('Private messages to this person are at risk of public disclosure.') . EOL);
551                         }
552
553                 }
554                 else {
555                         notice( t('Invalid contact.') . EOL);
556                         goaway($a->get_baseurl(true) . '/network');
557                         // NOTREACHED
558                 }
559         }
560
561         if((! $group) && (! $cid) && (! $update) && (! get_config('theme','hide_eventlist'))) {
562                 $o .= get_birthdays();
563                 $o .= get_events();
564         }
565
566         if($datequery) {
567                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created <= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery))));
568         }
569         if($datequery2) {
570                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created >= '%s' ", dbesc(datetime_convert(date_default_timezone_get(),'',$datequery2))));
571         }
572
573         //$sql_extra2 = (($nouveau) ? '' : " AND `item`.`parent` = `item`.`id` ");
574         $sql_extra2 = (($nouveau) ? '' : $sql_extra2);
575         $sql_extra3 = (($nouveau) ? '' : $sql_extra3);
576         $sql_order = "";
577         $order_mode = "received";
578         $tag = false;
579
580         if(x($_GET,'search')) {
581                 $search = escape_tags($_GET['search']);
582
583                 if(strpos($search,'#') === 0) {
584                         $tag = true;
585                         $search = substr($search,1);
586                 }
587
588                 if (get_config('system','only_tag_search'))
589                         $tag = true;
590
591                 if($tag) {
592                         $sql_extra = "";
593
594                         $sql_post_table = sprintf("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` ",
595                                         dbesc(protect_sprintf($search)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(local_user()));
596                         $sql_order = "`item`.`id`";
597                         $order_mode = "id";
598                 } else {
599                         if (get_config('system','use_fulltext_engine'))
600                                 $sql_extra = sprintf(" AND MATCH (`item`.`body`, `item`.`title`) AGAINST ('%s' in boolean mode) ", dbesc(protect_sprintf($search)));
601                         else
602                                 $sql_extra = sprintf(" AND `item`.`body` REGEXP '%s' ", dbesc(protect_sprintf(preg_quote($search))));
603                         $sql_order = "`item`.`received`";
604                         $order_mode = "received";
605                 }
606         }
607         if(strlen($file)) {
608                 $sql_post_table = sprintf("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` ",
609                                 dbesc(protect_sprintf($file)), intval(TERM_OBJ_POST), intval(TERM_FILE), intval(local_user()));
610                 $sql_order = "`item`.`id`";
611                 $order_mode = "id";
612         }
613
614         if($conv)
615                 $sql_extra3 .= " AND `mention`";
616
617         if($update) {
618
619                 // only setup pagination on initial page view
620                 $pager_sql = '';
621
622         }
623         else {
624                 if( (! get_config('alt_pager', 'global')) && (! get_pconfig(local_user(),'system','alt_pager')) ) {
625                         $r = q("SELECT COUNT(*) AS `total`
626                                 FROM $sql_table $sql_post_table INNER JOIN `contact` ON `contact`.`id` = $sql_table.`contact-id`
627                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
628                                 WHERE $sql_table.`uid` = %d AND $sql_table.`visible` = 1 AND $sql_table.`deleted` = 0
629                                 $sql_extra2 $sql_extra3
630                                 $sql_extra $sql_nets ",
631                                 intval($_SESSION['uid'])
632                         );
633
634                         if(count($r)) {
635                                 $a->set_pager_total($r[0]['total']);
636                         }
637                 }
638
639                 //  check if we serve a mobile device and get the user settings
640                 //  accordingly
641                 if ($a->is_mobile) {
642                     $itemspage_network = get_pconfig(local_user(),'system','itemspage_mobile_network');
643                     $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
644                 } else {
645                     $itemspage_network = get_pconfig(local_user(),'system','itemspage_network');
646                     $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
647                 }
648                 //  now that we have the user settings, see if the theme forces
649                 //  a maximum item number which is lower then the user choice
650                 if(($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network))
651                         $itemspage_network = $a->force_max_items;
652
653                 $a->set_pager_itemspage($itemspage_network);
654                 $pager_sql = sprintf(" LIMIT %d, %d ",intval($a->pager['start']), intval($a->pager['itemspage']));
655         }
656
657         if($nouveau) {
658                 $simple_update = (($update) ? " and `item`.`unseen` = 1 " : '');
659
660                 if ($sql_order == "")
661                         $sql_order = "`item`.`received`";
662
663                 // "New Item View" - show all items unthreaded in reverse created date order
664                 $items = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
665                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`writable`,
666                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
667                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
668                         FROM $sql_table $sql_post_table INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
669                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
670                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1
671                         AND `item`.`deleted` = 0 and `item`.`moderated` = 0
672                         $simple_update
673                         $sql_extra $sql_nets
674                         ORDER BY $sql_order DESC $pager_sql ",
675                         intval($_SESSION['uid'])
676                 );
677
678                 $update_unseen = ' WHERE uid = ' . intval($_SESSION['uid']) . " AND unseen = 1 $sql_extra $sql_nets";
679         } else {
680
681                 // Normal conversation view
682
683
684                 if($order === 'post') {
685                         $ordering = "`created`";
686                         if ($sql_order == "")
687                                 $order_mode = "created";
688                 } else {
689                         $ordering = "`commented`";
690                         if ($sql_order == "")
691                                 $order_mode = "commented";
692                 }
693
694                 if ($sql_order == "")
695                         $sql_order = "$sql_table.$ordering";
696
697                 if (($_GET["offset"] != ""))
698                         $sql_extra3 .= sprintf(" AND $sql_order <= '%s'", dbesc($_GET["offset"]));
699
700                 // Fetch a page full of parent items for this page
701                 if($update) {
702                         $r = q("SELECT `item`.`parent` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`
703                                 FROM $sql_table $sql_post_table INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
704                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
705                                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND
706                                 (`item`.`deleted` = 0 OR `item`.`verb` = '" . ACTIVITY_LIKE ."' OR `item`.`verb` = '" . ACTIVITY_DISLIKE . "')
707                                 and `item`.`moderated` = 0 and `item`.`unseen` = 1
708                                 $sql_extra3 $sql_extra $sql_nets ORDER BY `item_id` DESC LIMIT 100",
709                                 intval(local_user())
710                         );
711                 } else {
712                         $r = q("SELECT `thread`.`iid` AS `item_id`, `thread`.`network` AS `item_network`, `contact`.`uid` AS `contact_uid`
713                                 FROM $sql_table $sql_post_table INNER JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
714                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
715                                 WHERE `thread`.`uid` = %d AND `thread`.`visible` = 1 AND `thread`.`deleted` = 0
716                                 AND `thread`.`moderated` = 0
717                                 $sql_extra2 $sql_extra3 $sql_extra $sql_nets
718                                 ORDER BY $sql_order DESC $pager_sql ",
719                                 intval(local_user())
720                         );
721                 }
722
723                 // Then fetch all the children of the parents that are on this page
724
725                 $parents_arr = array();
726                 $parents_str = '';
727                 $date_offset = "";
728
729                 if(count($r)) {
730                         foreach($r as $rr)
731                                 if(! in_array($rr['item_id'],$parents_arr))
732                                         $parents_arr[] = $rr['item_id'];
733
734                         $parents_str = implode(", ", $parents_arr);
735
736                         // splitted into separate queries to avoid the problem with very long threads
737                         // so always the last X comments are loaded
738                         // This problem can occur expecially with imported facebook posts
739                         $max_comments = get_config("system", "max_comments");
740                         if ($max_comments == 0)
741                                 $max_comments = 100;
742
743                         $items = array();
744
745                         foreach ($parents_arr AS $parents) {
746 //                                      $sql_extra ORDER BY `item`.`commented` DESC LIMIT %d",
747                                 $thread_items = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
748                                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`alias`, `contact`.`rel`, `contact`.`writable`,
749                                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
750                                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
751                                         FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
752                                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
753                                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0
754                                         AND `item`.`moderated` = 0
755                                         AND `item`.`parent` = %d
756                                         ORDER BY `item`.`commented` DESC LIMIT %d",
757                                         intval(local_user()),
758                                         intval($parents),
759                                         intval($max_comments + 1)
760                                 );
761                                 $items = array_merge($items, $thread_items);
762                         }
763                         $items = conv_sort($items,$ordering);
764                 } else {
765                         $items = array();
766                 }
767
768                 if ($_GET["offset"] == "")
769                         $date_offset = $items[0][$order_mode];
770                 else
771                         $date_offset = $_GET["offset"];
772
773                 $a->page_offset = $date_offset;
774
775                 if($parents_str)
776                         $update_unseen = ' WHERE uid = ' . intval(local_user()) . ' AND unseen = 1 AND parent IN ( ' . dbesc($parents_str) . ' )';
777         }
778
779         // We aren't going to try and figure out at the item, group, and page
780         // level which items you've seen and which you haven't. If you're looking
781         // at the top level network page just mark everything seen.
782
783
784 // The $update_unseen is a bit unreliable if you have stuff coming into your stream from a new contact -
785 // and other feeds that bring in stuff from the past. One can't find it all.
786 // I'm reviving this block to mark everything seen on page 1 of the network as a temporary measure.
787 // The correct solution is to implement a network notifications box just like the system notifications popup
788 // with the ability in the popup to "mark all seen".
789 // Several people are complaining because there are unseen messages they can't find and as time goes
790 // on they just get buried deeper. It has happened to me a couple of times also.
791
792
793         if((! $group) && (! $cid) && (! $star)) {
794                 $r = q("UPDATE `item` SET `unseen` = 0
795                         WHERE `unseen` = 1 AND `uid` = %d",
796                         intval(local_user())
797                 );
798         }
799         else {
800                 if($update_unseen)
801                         $r = q("UPDATE `item` SET `unseen` = 0 $update_unseen");
802         }
803
804         // Set this so that the conversation function can find out contact info for our wall-wall items
805         $a->page_contact = $a->contact;
806
807         $mode = (($nouveau) ? 'network-new' : 'network');
808
809         $o .= conversation($a,$items,$mode,$update);
810
811         if(!$update) {
812                 if( get_config('alt_pager', 'global') || get_pconfig(local_user(),'system','alt_pager') ) {
813                         $o .= alt_pager($a,count($items));
814                 }
815                 else {
816                         $o .= paginate($a);
817                 }
818         }
819
820         return $o;
821 }
822