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