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