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