source: extensions/whois_online/online.php @ 6201

Last change on this file since 6201 was 6201, checked in by vdigital, 14 years ago

New: Piwigo 2.1 support
Fix: Non active menu => Icon is active
Fix: Active the right menu (Tools or Plugins) depending on the default access.
Change: CSS review.
Bug bypass on language.
Part of a code review.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 14.4 KB
Line 
1<?php
2
3if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
4global $conf, $conf_whois, $prefixeTable;
5include_once(WHOIS_ONLINE_PATH.'include/wo_functions.inc.php');
6
7define('ONLINE_LEVEL', (100+$conf_whois['Delete level'])/100);
8define('ONLINE_LIMIT', $conf_whois['Obsolete limit']);
9
10/* Admin menus are always available */
11add_event_handler('get_admin_plugin_menu_links', 'whois_add_icon' );
12/* On Active */
13if ($conf_whois['Active']) {
14        $conf['Whois Online Update'] = true;
15        add_event_handler('loc_begin_picture', 'whois_online_management');
16        add_event_handler('loc_begin_index', 'whois_online_management');
17        add_event_handler('register_user', 'whois_online_register');
18        if ($conf_whois['Default display'] or (defined('IN_ADMIN') and IN_ADMIN)) 
19                add_event_handler('loc_begin_page_tail', 'whois_default_display' );
20}
21
22
23/*
24                Main process: Analyze, set new values and prepare displayed values.
25               
26                Update on parameter...
27*/
28function whois_online_management()
29{
30        global $user, $conf, $conf_whois, $template, $page, $lang, $lang_info;
31        load_language('plugin.lang', WHOIS_ONLINE_PATH);
32        srand((float)time());
33
34  pwg_debug('*********** start Online_management ***********');
35        if (!isset($conf_whois['Active'])) $conf_whois = whois_online_conf();
36
37        $online = whois_online_get_data();
38
39        $global = $online[0];
40        unset($online[0]);
41        $sid = session_id();
42       
43        // Step 1 - Find the User and/or IP/session_id
44        foreach ($online as $key => $record) {
45                // 1st case: Same IP and same member (Proxy guests are viewed as one)
46                if ($record['IP'] == $_SERVER['REMOTE_ADDR']
47                        and $record['username'] == $user['username'] ) {
48                                $visit = $record;
49                                $v = $key;
50                                break;
51                }
52                // 2nd case: Same session and user (No doubt)
53                if ($record['session_id'] == $sid
54                        and $record['username'] == $user['username'] ) {
55                                $visit = $record; // Maybe a guest
56                                if (!is_a_guest()) $visit['hidden_IP'] = 'true'; // Maybe Proxy or hidden IP
57                                //$visit['IP'] = $_SERVER['REMOTE_ADDR'];
58                                $v = $key;
59                                break;
60                }
61                // 3rd and last case: Same user_id
62                if ($record['user_id'] == $user['id'] and !is_a_guest()) { // new IP and new session
63                                $visit = $record;
64                                $visit['hidden_IP'] = 'true'; /* Or Generic user or the user is using several connections */
65                                //$visit['IP'] = $_SERVER['REMOTE_ADDR'];
66                                $v = $key;
67                                break;
68                }
69        }
70
71        // Step 2 - Assume a new comer
72        if ( !isset($visit) ) {
73                $ctry = '_' . strtoupper( substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"],6,2) );
74                $visit = Array( 
75                        'IP' => $_SERVER['REMOTE_ADDR'], // First known IP (Is that one true?)
76                        'hidden_IP' => 'false', // supposed a fixed IP
77                        'session_id' => $sid,
78                        'user_id' => $user['id'],
79                        'username' => $user['username'],
80                        'delay' => 0,
81                        'lang' => substr($lang_info['code'],0,2) . $ctry,
82                        'permanent' => 'false', // False: delete after 72 Hours / True: delete after 90 days
83                        'last_access' => time(), // Last access by this user
84                        'elm_ids' => array_fill(0, 10, 0), // 10 last minutes + Last reference minute
85                        'cat_ids' => array_fill(0, 12, 0), // 12 ranges (of 5 minutes) + ref
86                        'tag_ids' => array_fill(0, 24, 0), // 24 hours + ref
87                        'sch_ids' => array_fill(0, 14, 0), // 14 days + ref
88                        'date' => date('Y-m-d'), // Futur usage
89                        'elm_hits' => 0, 'pag_hits' => 0, // elements hits and pages hits by this user
90                        'first_access_date' => date('Y-m-d'), // First access by this user
91                        'dates' => Array(), // 5 last access dates
92                );
93                $online[] = $visit;
94                $v = count($online);
95        }
96
97        // Step 3 - Monitor this access
98        $base = script_basename();
99        // Picture page
100        if (isset($page['image_id']) and $base == 'picture') {
101                whois_online_track($visit['elm_ids'], $page['image_id'],$visit['dates']);
102                if (isset($page['tags']))
103                whois_online_track($visit['tag_ids'], $page['image_id'],$visit['dates']);
104                if (isset($page['search']))
105                whois_online_track($visit['sch_ids'], $page['image_id'],$visit['dates']);
106                $visit['elm_hits']++;
107                $global['elm_hits']++;
108        }
109        // Category page
110        if (isset($page['category']['id']) and $base == 'index')
111                whois_online_track($visit['cat_ids'], $page['category']['id'],$visit['dates']);
112        // Page index
113        if (!isset($page['category']['id']) and !isset($page['image_id']))
114                whois_online_track($visit['cat_ids'], '' ,$visit['dates']);
115        $visit['pag_hits']++;
116        $global['pag_hits']++;
117
118        // Step 4 - Identify current range
119        $current = floor(time() / 60);                  // minutes for Unix time origin
120        $minute = $current % 10;                                                // (0-9) current minute
121        $five = floor($current / 5);    // (0-11) last 5 minutes range
122        $hour = floor($current / 60);   // (0-11) last hours
123        $day = floor($current / 1440); // (0-13) last days
124        if (isset($global['elm_ids'][10])) $old = $global['elm_ids'][10]; // previous minute (last one, or maybe 60 minutes ago or more).
125        else $old = $current; /* Only the first time or prevent wrong changes */
126
127        // Step 5 - Hits by range
128        if ($current != $old) {
129                $global['elm_ids'][11] = $global['elm_ids'][$minute];
130                $raz = min($current-$old, 10);
131        // 5.1 - $global['elm_ids'] ( hits by minute range )
132                for ($i=0;$i<$raz;$i++) {
133                        $global['elm_ids'][($minute+10-$i)%10] = 0;
134                }
135        // 5.2 - $global['cat_ids'] ( hits by 5 minutes range )
136                if (isset($global['cat_ids'][12])) $oldfive = $global['cat_ids'][12];
137                else $oldfive = floor($old / 5);
138                $raz = min($five - $oldfive, 12);
139                for ($i=0;$i<$raz;$i++) {
140                        $global['cat_ids'][($five+12-$i)%12] = 0; // Reset in backside
141                }
142        // 5.3 - $global['tag_ids'] (hits by hours )
143                if (count($global['tag_ids'])<25) $global['tag_ids'] = array_fill(0, 24, 0);
144                if (isset($global['tag_ids'][24])) $oldhour = $global['tag_ids'][24];
145                else $oldhour = floor($old / 60);
146                $raz = min($hour - $oldhour, 24);
147                for ($i=0;$i<$raz;$i++) {
148                        $global['tag_ids'][($hour+24-$i)%24] = 0; // Reset in backside
149                }
150        // 5.4 - $global['sch_ids'] ( hits by days )
151                if (isset($global['sch_ids'][14])) $oldday = $global['sch_ids'][14];
152                else $oldday = floor($old / 1440);
153                $raz = min($day - $oldday, 14);
154                for ($i=0;$i<$raz;$i++) {
155                        $global['sch_ids'][($day+14-$i)%14] = 0; // Reset in backside
156                }
157        }
158        $global['elm_ids'][$minute]++;
159        $global['cat_ids'][$five%12]++;
160        $global['tag_ids'][$hour%12]++;
161        $global['sch_ids'][$day%14]++;
162  // !!! WARNING  !!! WARNING !!! WARNING !!! WARNING !!!
163        $global['elm_ids'][10] = $current; // reference minute has changed
164        $global['cat_ids'][12] = $five;
165        $global['tag_ids'][24] = $hour;
166        $global['sch_ids'][14] = $day;
167  // !!! WARNING  !!! WARNING !!! WARNING !!! WARNING !!!
168
169        // 5.5 - Add in previous
170  if (!isset($global['any_previous'])) {
171                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
172                        ' ADD `same_previous` VARCHAR( 255 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
173                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
174                        ' ADD `any_previous` VARCHAR( 255 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
175                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
176                        ' ADD `user_agent` VARCHAR( 160 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
177        }
178
179        $antiaspi = array(
180    'diff' => '20 pages in 00:00:10' , // Banned for 20 access in 10 seconds or less
181    'same' => '15 pages in 00:00:30' , // Banned for 15 access on the same page in 30 seconds or less
182    'banned during' => '23:59:59' ,    // Banned time hh:mm:ss or any valid MySQL datetime expression 'YYYY-MM-DD HH:MM:SS'
183    'only guest' => true ,             // True, registred members won't be banned
184    'only picture' => false ,          // True, Check only on picture pages
185    'allowed ip' => array()            // Allowed IP array (Bots, or your fixed IP)
186  );
187  if (isset($conf['antiaspi'])) $antiaspi = array_merge($antiaspi, $conf['antiaspi']);
188
189        // For AntiAspi follow ANY PREVIOUS access
190        $access = '0:';
191        list($max_any, $maxtext) = explode(' pages in ', $antiaspi['diff']);
192        $maxtime = whois_online_duration($maxtext);
193        $prev='';
194        $previous = (isset($visit['any_previous'])) ? explode(' ', $visit['any_previous']):Array();
195        foreach ($previous as $v) {
196                $old = explode(':', $v);
197                $old[0] += $visit['delay']; 
198                if ($old[0]<$maxtime) $prev .= $old[0].': ';
199        }
200        $prev = $access . ' ' . $prev;
201        $prev = substr($prev, 0, -2);
202        $visit['any_previous'] = $prev;
203        // For AntiAspi follow ANY SAME PICTURE access
204        $access = '0:';
205        $same_elem = (isset($page['image_id'])) ? $page['image_id']:'0';
206        list($max_same, $maxtext) = explode(' pages in ', $antiaspi['same']);
207        $maxtime = whois_online_duration($maxtext);
208        $access .= $same_elem . ':';
209        $prev='';
210        $previous = (isset($visit['same_previous'])) ? explode(' ', $visit['same_previous']):Array();
211        foreach ($previous as $v) {
212                $old = explode(':', $v);
213                $old[0] += $visit['delay'];
214                if ($old[0]<$maxtime and $old[1]==$same_elem) $prev .= $old[0].':'.$old[1].': ';
215        }
216        $prev = $access . ' ' . $prev;
217        $prev = substr($prev, 0, -2);
218        $visit['same_previous'] = $prev;
219       
220        // Check limits of $visit['any_previous'] and $visit['same_previous']
221        // by 256 characters
222        // by $max_any and by $max_same
223        while (strlen($visit['any_previous'])>256) {
224          $previous = explode(' ',$visit['any_previous']);
225                $oldest = array_pop($previous);
226                $visit['any_previous'] = implode(' ', $previous);
227        }
228        $ctr_any = count(explode(' ',$visit['any_previous']));
229        while (strlen($visit['same_previous'])>256) {
230          $previous = explode(' ',$visit['same_previous']);
231                $oldest = array_pop($previous);
232                $visit['same_previous'] = implode(' ', $previous);
233        }
234        $ctr_same = count(explode(' ',$visit['same_previous']));
235       
236        $visit['user_agent'] = substr($_SERVER['HTTP_USER_AGENT'],0,160);
237        $Vip =& $visit['IP'];
238        $visit['Allowed_SE'] = false;
239  if (!empty($antiaspi['allowed ip']))
240  {
241    $allowed_ips = str_replace(array('.', '%'), array('\.', '.*?'), $antiaspi['allowed ip']);
242    foreach ($allowed_ips as $ip)
243    {
244      if (preg_match("#" . $ip . "#", $Vip)) { $visit['Allowed_SE'] = true; break; }
245    }
246  }
247       
248        // Step 6 - Update (on Conf_Update and trace) and send trace to determine global tracing or not
249        $dtrace = 0;
250        if ($user['status'] == 'admin') $dtrace += $conf_whois['Administrators'];
251        elseif ($user['status'] == 'webmaster') $dtrace += $conf_whois['Webmasters'];
252        else $dtrace = 2;
253        if ($conf['Whois Online Update'] and $dtrace > 0) whois_online_update($global, $visit, $dtrace);
254
255        // Step 7 - Find your recent visits (These image_ids are presumely authorized)
256        $my_ids = $visit['elm_ids'];
257        sort($my_ids);
258        unset($my_ids[0]);
259        $url_visited = (count($my_ids)>0) ? make_index_url(array('list' => $my_ids)).'&amp;review':'';
260
261        // Step 8 - Guest count and Member list
262        $h24 = 0; $h1 = 0; $guest = 0;
263        $list = array();
264        $elm = array(); $excl = array(); // Get images_ids from all and from the current visitor
265        foreach ($online as $k => $monit)
266        {
267                if ($user['id']==$monit['user_id']) $excl = $monit['elm_ids'];
268                else $elm = array_merge($elm, $monit['elm_ids']);
269                if ($monit['delay'] <= (24*3600)) $h24++;
270                if ($monit['delay'] <= 3600) $h1++;
271                // Less than 5 minutes: users are considered as still online...
272                if ($monit['delay'] <= 300) {
273                        if ($monit['user_id'] == $conf['guest_id']) $guest++;
274                        else $list[] = $monit['username'];
275                }
276        }
277        // The first (and current) access are not recorded in $online
278        // As visitor you are not expecting your access to be already counted: Ok that the case
279        // but you are expecting to see you as a member in the member list if you are: and there it is
280        if ($visit['user_id'] != $conf['guest_id'] ) $list[] = $visit['username'];
281        $list = array_unique($list);
282       
283        if (count($list) > $conf_whois['Users']['max']) {
284                $conf_whois['Users']['max'] = count($list);
285                $conf_whois['Users']['When'] = time();
286                $conf['Whois Online'] = serialize($conf_whois);
287                pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
288    VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
289        }
290
291        // Step 9 - Review pictures viewed by others (all images except yours)
292        $elm = array_diff( array_unique($elm), $excl );
293        shuffle($elm);
294        $elm = array_slice($elm,0,($conf['top_number']+50));
295        sort($elm);
296        array_shift($elm);
297        $elm[] = 0; // Check if authorized pictures
298        $query = 'SELECT DISTINCT(image_id)
299  FROM '.IMAGE_CATEGORY_TABLE.'
300    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
301  WHERE image_id IN ('.implode(',', $elm ).')
302    '.get_sql_condition_FandF(
303      array(
304          'forbidden_categories' => 'category_id',
305          'visible_categories' => 'category_id',
306          'visible_images' => 'id'
307        ), "\n  AND") . ';';
308        $ids = array_from_query($query, 'image_id');
309        shuffle($ids);
310        $ids = array_slice($ids, 0, $conf['top_number']); // Keep some
311        $url_someothers = (isset($ids[0])) ? make_index_url(array('list' => $ids)).'&amp;others':'';
312
313        // Random page title change
314        $url_type = pwg_get_session_var('whois_url_type', ''); /* previous review or others */
315        $list_ids = pwg_get_session_var('whois_list_ids', ''); /* previous list/xx,yy,zz, ... */
316        $list_section = (isset($page['section']) and $page['section'] == 'list') ? true:false;
317        $same_ids = (isset($page['list']) and $page['list'] == $list_ids) ? true:false;
318        if ($list_section and isset($_GET['review'])) {
319                $url_type = 'Whois_review';
320                $same_ids = true;
321        }
322        if ($list_section and isset($_GET['others'])) {
323                $url_type = 'Whois_others';
324                $same_ids = true;
325        }
326        if ($list_section and $same_ids and isset($page['list'])) $list_ids = $page['list'];
327        else $url_type = ''; // Not the same list
328        pwg_set_session_var('whois_list_ids', $list_ids);
329        pwg_set_session_var('whois_url_type', $url_type);
330        if ($url_type != '' and $list_section)
331  $page['title'] = '<a href="'.duplicate_index_url(array('start'=>0)).'">'
332                    .l10n($url_type).'</a>';
333
334       
335        // Step 10 - Prepare data to display
336        $yesterday = ($day+13) % 14;
337        $template->assign('Whois', array(
338                'Total' => $global['pag_hits'],
339                'Image' => $global['elm_hits'],
340                'Other' => ($global['pag_hits']-$global['elm_hits']),
341                'Current_minute' => $global['elm_ids'][$minute],
342                'Previous_minute' => $global['elm_ids'][($minute+9) % 10],
343                'Current_5mins' => $global['elm_ids'][$minute]
344                                                                        + $global['elm_ids'][($minute+9) % 10]
345                                                                        + $global['elm_ids'][($minute+8) % 10]
346                                                                        + $global['elm_ids'][($minute+7) % 10]
347                                                                        + $global['elm_ids'][($minute+6) % 10],
348                'Current_10mins' => array_sum(array_slice($global['elm_ids'],0,10)),
349                'Current_hour' => array_sum(array_slice($global['cat_ids'],0,12)),
350                'Current_24h' => array_sum(array_slice($global['tag_ids'],0,24)),
351                'Yesterday' => $global['sch_ids'][$yesterday],
352                'Users_Last_day' => $h24,
353                'Users_Last_hour' => $h1,
354                'Guests' => $guest,
355                'Online' => $list,
356                'Review_url' => $url_someothers,
357                'Their_ids' => $ids,
358                'Seen_url' => $url_visited,
359                'My_ids' => $my_ids,
360                'Slideshow' => isset($_GET['slideshow']) ? true:false,
361        ));
362        $template->assign('Online', $global );
363
364        pwg_debug('end Online_management');
365}
366?>
Note: See TracBrowser for help on using the repository browser.