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