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