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