source: extensions/whois_online/online.php @ 5954

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

[ 2.0.m ]

Fix: IE8 User agent could be too long
Fix: Failure on localisation (a French internet provider blocks external get_files)
Fix: Loss of previous collected data


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