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