source: extensions/whois_online/online.php @ 6193

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

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