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