source: extensions/whois_online/online.php @ 5811

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

Fixes:

MySQL 4.1 support
Alternate reading solutions: file_get_contents / fsockopen / curl
Replace of deprecated functions as of PHP 5.3.0

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 25.5 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/* Secure Config */
7if (!isset($conf_whois['Active'])) $conf_whois = whois_online_conf();
8
9function whois_online_conf()
10{
11        global $conf;
12        $default = array(
13          'Active' => true,
14          'Delete level' => 20,
15          'Radar limit' => 25,
16          'Webmasters' => 2, // Normal
17          'Administrators' => 2,
18          'Obsolete limit' => 20,
19                'Default display' => true,
20          'Add to Plugins menu' => false,
21          'Add icon to History' => true,
22          'Keep data' => true,
23          'Search id' => 0,
24          'Users' => Array('max' => 0, 'When' => date('Y-m-d'), 'count' => 0),
25        );
26        $conf_whois = array_merge($default, unserialize($conf['Whois Online']));
27        if ((!isset($conf_whois['Version'])) or $conf_whois['Version'] != WHOIS_ONLINE_VER
28                or $conf['Whois Online'] != serialize($conf_whois)) {
29                $conf_whois['Version'] = WHOIS_ONLINE_VER;
30                $conf['Whois Online'] = serialize($conf_whois);
31                pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
32          VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
33        }
34        return $conf_whois;
35}
36
37define('ONLINE_LEVEL', (100+$conf_whois['Delete level'])/100);
38define('ONLINE_LIMIT', $conf_whois['Obsolete limit']);
39
40/* Admin menus are always available */
41add_event_handler('get_admin_plugin_menu_links', 'whois_add_icon' );
42/* On Active */
43if ($conf_whois['Active']) {
44        $conf['Whois Online Update'] = true;
45        add_event_handler('loc_begin_picture', 'whois_online_management');
46        add_event_handler('loc_begin_index', 'whois_online_management');
47        add_event_handler('register_user', 'whois_online_register');
48        if ($conf_whois['Default display'] or (defined('IN_ADMIN') and IN_ADMIN)) add_event_handler('loc_begin_page_tail', 'whois_default_display' );
49}
50
51if ( !function_exists('pwg_get_contents') ) {
52        function pwg_get_contents($url, $mode='') {
53
54                global $pwg_mode, $pwg_prev_host;
55                $timeout = 5; // will be a parameter (only for the socket)
56
57                $host = (strtolower(substr($url,0,7)) == 'http://') ? substr($url,7) : $url;
58                $host = (strtolower(substr($host,0,8)) == 'https://') ? substr($host,8) : $host;
59                $doc = substr($host, strpos($host, '/'));
60                $host = substr($host, 0, strpos($host, '/'));
61
62                if ($pwg_prev_host != $host) $pwg_mode = ''; // What was possible with one website could be different with another
63                $pwg_prev_host = $host;
64                if (isset($pwg_mode)) $mode = $pwg_mode;
65                if ($mode == 'r') $mode = '';
66                // $mode = 'ch'; // Forcing a test '' all, 'fs' fsockopen, 'ch' cURL
67
68        // 1 - The simplest solution: file_get_contents
69        // Contraint: php.ini
70        //      ; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
71        //      allow_url_fopen = On
72                if ( $mode == '' ) {
73                  if ( true === (bool) ini_get('allow_url_fopen') ) { 
74                                $value = file_get_contents($url);
75                                if ( $value !== false and substr($value,0,21) != '<!DOCTYPE HTML PUBLIC') {
76                                        return $value;
77                                }
78                        }
79                }
80                if ( $mode == '' ) $mode = 'fs';
81                if ( $pwg_mode == '' ) $pwg_mode = 'fs'; // Remind it
82        // 2 - Often accepted access: fsockopen
83                if ($mode == 'fs') {
84                        $fs = fsockopen($host, 80, $errno, $errstr, $timeout);
85                        if ( $fs !== false ) {
86                                fwrite($fs, 'GET ' . $doc . " HTTP/1.1\r\n");
87                                fwrite($fs, 'Host: ' . $host . "\r\n");
88                                fwrite($fs, "Connection: Close\r\n\r\n");
89                                stream_set_blocking($fs, TRUE);
90                                stream_set_timeout($fs,$timeout); // Again the $timeout on the get
91                                $info = stream_get_meta_data($fs);
92                                $value = '';
93                                while ((!feof($fs)) && (!$info['timed_out'])) {
94                                                                $value .= fgets($fs, 4096);
95                                                                $info = stream_get_meta_data($fs);
96                                                                flush();
97                                }
98                                if ( $info['timed_out'] === false  and substr($value,0,21) != '<!DOCTYPE HTML PUBLIC') return $value;
99                        }
100                }
101
102                if ( $pwg_mode == 'fs' ) $pwg_mode = 'ch'; // Remind it
103        // 3 - Sometime another solution: curl_exec
104        // See http://fr2.php.net/manual/en/curl.installation.php
105          if (function_exists('curl_init') and $pwg_mode == 'ch') {
106                        $ch = @curl_init();
107                        @curl_setopt($ch, CURLOPT_URL, $url);
108                        @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
109                        @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
110                        @curl_setopt($ch, CURLOPT_HEADER, 1);
111                        @curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
112                        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
113                        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
114                        $value = @curl_exec($ch);
115                        $header_length = @curl_getinfo($ch, CURLINFO_HEADER_SIZE);
116                        $status = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
117                        @curl_close($value);
118                        if ($value !== false and $status >= 200 and $status < 400) {
119                                $value = substr($value, $header_length);
120                                // echo '<br/>-ch- ('. $value . ') <br/>';
121                                return $value;
122                        }
123                        else $pwg_mode = 'failed'; // Sorry but remind it as well
124                }
125
126                // No other solutions
127                return false;
128        }
129}
130// Assume the Default display on pages
131function whois_default_display() {
132        global $template;
133        $template->set_filenames(array( 'Whois_display' => dirname(__FILE__).'/default.tpl'));
134        $template->pparse('Whois_display');
135}
136
137// Add admin links
138function whois_add_icon($menu) {
139        global $conf_whois, $lang;
140        if ($conf_whois['Add icon to History'])
141                $lang['History'] .= '</a> <a class="external" href="' . get_admin_plugin_menu_link(WHOIS_ONLINE_PATH.'config.php') . '">
142                        <img class="button" src="' . WHOIS_ONLINE_PATH . 'icons/Whois_tuner.gif" alt="Whois Online configuration" title="Whois Online configuration" /></a>';
143        if ($conf_whois['Add to Plugins menu']) array_push($menu, array(
144                                'NAME' => 'Whois Online',
145                                'URL' => get_admin_plugin_menu_link(WHOIS_ONLINE_PATH.'config.php'),
146                        ));
147        return $menu;
148}
149
150// Template function
151function Whois_most($text, $count, $when, $format) {
152 return sprintf(l10n($text),$count,date(l10n($format),$when));
153}
154
155// New member
156function whois_online_register($who) {
157        global $conf, $conf_whois;
158        $conf_whois['Users']['count'] = $who['id'];
159        $conf['Whois Online'] = serialize($conf_whois);
160        pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
161  VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
162        return;
163}
164
165function whois_country($trace, $bypass = false) {
166  if (!isset($trace['country'])) {
167                        pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . ' ADD `country` VARCHAR( 255 ) NOT NULL AFTER `lang` ;');
168                        $trace['country']='';
169        }
170        $c = array();
171        if ($trace['country']!='') $c = @unserialize(htmlspecialchars_decode($trace['country']));
172        if (isset($c['Code']) and $c['Code']!='' and $c['Code']!='__') return $c; 
173        if ($bypass and isset($c['Code']) and $c['Code']=='__') return $c;
174    $result = pwg_get_contents ('http://api.hostip.info/get_html.php?ip=' . $trace['IP'], 'r');
175        if ( $result !== false ) { 
176                $tokens = preg_split("/[:]+/", $result);
177                $c = array ('Name' => $tokens[1], 'City' => substr($tokens[3],0,-3));
178                if (strpos ($c['Name'], '?') === FALSE) {
179                        $tokens = preg_split ("/[\(\)]/", $c['Name']);
180                        $c['Code'] = isset($tokens[1]) ? $tokens[1]:'__';
181                        $c['Name'] = ucwords ( strtolower( substr($c['Name'],0,-5)));
182                }
183        }
184        else $c = Array('Code' => '__', 'Name' => l10n('Unknown country'), 'City' => 'N/A',);
185        if ($c['Code'] == 'Private Address') {
186                $c['Name'] = l10n('Private Address');
187                $c['City'] = l10n('N/A');
188                $c['Code'] = '__';
189        }
190        $new = htmlspecialchars(serialize($c),ENT_QUOTES,'UTF-8');
191        if ($new == $trace['country']) return $c;
192        pwg_query('UPDATE ' . WHOIS_ONLINE_TABLE . '
193      SET `country` = \'' . $new . '\'
194    WHERE `session_id` = \'' . $trace['session_id'] . '\';');
195  return $c;
196}
197
198function whois_flag($trace, &$step, $limit = 10) {
199  $flag = WHOIS_ONLINE_PATH . 'flags/' . $trace['Country']['Code'] . '.jpg';
200        if (file_exists($flag)) return $flag;
201        if ( $step > $limit ) return WHOIS_ONLINE_PATH . 'flags/__.jpg';
202        $f = fopen  ('http://api.hostip.info/flag.php?ip=' . $trace['IP'], 'r');
203        $result='';
204        while ($l = fgets ($f, 1024)) $result .= $l;
205        fclose ($f);
206                $f = fopen($flag,"w+");
207        fputs($f,$result);
208        fclose($f);
209  return $flag;
210}
211
212// Read all data
213function whois_online_get_data($order='') {
214        $remove = "''"; // Nothing to remove ( = an empty session_id)
215        $ctr = 0; $Online[0] = '';
216        $result = pwg_query('SELECT * FROM ' . WHOIS_ONLINE_TABLE . $order . ';');
217        while($row=mysql_fetch_array($result)) {
218                $row['delay'] = (int) time() - $row['last_access'];
219                $row['elm_ids'] = explode(' ', $row['last_elm_ids']);
220                $row['cat_ids'] = explode(' ', $row['last_cat_ids']);
221                $row['tag_ids'] = explode(' ', $row['last_tag_ids']);
222                $row['sch_ids'] = explode(' ', $row['last_sch_ids']);
223                $row['dates'] = explode(' ', $row['last_dates']);
224                $ctr++;
225                if ( $row['IP'] != 'global' and $row['permanent'] == 'false'
226                        and $row['delay'] > (float)( 60 * 60 * 24 * 3 )) $remove .= ", '" . $row['session_id'] . "'";
227                elseif ($row['IP'] == 'global') $Online[0] = $row;
228                else $Online[] = $row;
229        }
230        // Out of 7 visits: Reduce registered visits for 3 days without access
231        if ($remove != "''" and $ctr > (count($Online) * ONLINE_LEVEL)
232                and ($ctr-count($Online)) > ONLINE_LIMIT and ($Online[0]['pag_hits']%7)==0) {
233                pwg_query('DELETE FROM ' . WHOIS_ONLINE_TABLE . ' WHERE `session_id` IN ('. $remove .')
234                                AND `permanent` = \'false\' AND `IP` <> \'global\';');
235                if (($Online[0]['pag_hits']%13)==0) @pwg_query('OPTIMIZE TABLE ' . WHOIS_ONLINE_TABLE . ';');
236        }
237        return $Online;
238}
239
240// Update global and update/create current session_id
241function whois_online_update(&$global, &$dedicated, &$gtrace)
242{
243        global $lang_info;
244        // Rewrite the global record
245        if ( $gtrace == 2 ) {
246                $query = 'REPLACE INTO ' . WHOIS_ONLINE_TABLE . ' (`IP`, `hidden_IP`, `session_id`,`user_id`,`username`,`lang`,
247                `permanent`,`last_access`,`last_elm_ids`, `last_cat_ids`, `last_tag_ids`, `last_sch_ids`,
248                `first_access_date`, `last_dates`, `elm_hits`, `pag_hits`)
249                        VALUES (\'global\', \'true\',\'global\', 0, \''. $global['username'] .'\', \'--\', \'true\', \''
250                        . time()  .'\',  \''
251                        . implode(' ',$global['elm_ids']) . '\', \''
252                        . implode(' ',$global['cat_ids']) . '\', \''
253                        . implode(' ',$global['tag_ids']) . '\', \''
254                        . implode(' ',$global['sch_ids']) . '\', \''
255                        . $global['first_access_date'] . '\', \'\', \''
256                        . $global['elm_hits'] . '\', \'' . $global['pag_hits'] . '\');';
257                pwg_query($query);
258        }
259        // Write or Rewrite the dedicated record
260        $query = 'REPLACE INTO ' . WHOIS_ONLINE_TABLE . ' (`IP`, `hidden_IP`, `session_id`,`user_id`,`username`,`lang`, `user_agent`,
261        `any_previous`, `same_previous`, `permanent`,`last_access`,`last_elm_ids`, `last_cat_ids`, `last_tag_ids`, `last_sch_ids`,
262        `first_access_date`, `last_dates`, `elm_hits`, `pag_hits`)
263                VALUES (\''. $dedicated['IP'] .'\', \''
264                . $dedicated['hidden_IP'] .'\', \''. $dedicated['session_id'] .'\', \''
265                . $dedicated['user_id'] .'\', \''. $dedicated['username'] .'\', \''
266                . substr($lang_info['code'],0,2) .'\', \''
267                . $dedicated['user_agent'] .'\', \''
268                . $dedicated['any_previous'] .'\', \''
269                . $dedicated['same_previous'] .'\', \''
270                . $dedicated['permanent'] . '\', \''. time() .'\',  \''
271                . implode(' ',$dedicated['elm_ids']) . '\', \''
272                . implode(' ',$dedicated['cat_ids']) . '\', \''
273                . implode(' ',$dedicated['tag_ids']) . '\', \''
274                . implode(' ',$dedicated['sch_ids']) . '\', \''
275                . $dedicated['first_access_date'] . '\', \''
276                . implode(' ',$dedicated['dates']) . '\', \''
277                . $dedicated['elm_hits'] . '\', \''
278                . $dedicated['pag_hits'] . '\');';
279        pwg_query($query);
280}
281
282// Data tracking
283// Parameters:
284//  - Array of Ids
285//  - New ID
286//  - Array of dates
287// => Add the ID if needed, Add Today if needed
288function whois_online_track(&$key, $id, &$date) {
289        if ($id != '') array_unshift($key, $id);
290        $key = array_unique($key);
291        if (count($key)>10) array_pop($key);
292        array_unshift($date, date('Y-m-d'));
293        $date = array_unique($date);
294        if (count($date)>5) array_pop($date);
295        return;
296}
297
298// Antiaspi delay conversion in seconds
299// delay in "HH:ii:ss" or "d :HH:ii:ss"
300// return delay in seconds
301function whois_online_duration($date_string)
302{
303 list($s, $i, $H, $d, $more) = 
304   array_merge(array_reverse(
305           explode(" ",str_ireplace(':',' ', $date_string))),
306                 array(0,0,0,0,0));
307 $t = time();
308 return strtotime(sprintf("+%s days %s hours %s minutes %s seconds", 
309   $d, $H, $i, $s), $t) - $t;
310}
311
312/*
313                Main process: Analyze, set new values and prepare displayed values.
314               
315                Update on parameter...
316*/
317function whois_online_management()
318{
319        global $user, $conf, $conf_whois, $template, $page, $lang, $lang_info;
320        load_language('plugin.lang', WHOIS_ONLINE_PATH);
321        srand((float)time());
322
323  pwg_debug('*********** start Online_management ***********');
324        if (!isset($conf_whois['Active'])) $conf_whois = whois_online_conf();
325
326        $online = whois_online_get_data();
327
328        $global = $online[0];
329        unset($online[0]);
330        $sid = session_id();
331       
332        // Step 1 - Find the User and/or IP/session_id
333        foreach ($online as $key => $record) {
334                // 1st case: Same IP and same member (Proxy guests are viewed as one)
335                if ($record['IP'] == $_SERVER['REMOTE_ADDR']
336                        and $record['username'] == $user['username'] ) {
337                                $visit = $record;
338                                $v = $key;
339                                break;
340                }
341                // 2nd case: Same session and user (No doubt)
342                if ($record['session_id'] == $sid
343                        and $record['username'] == $user['username'] ) {
344                                $visit = $record; // Maybe a guest
345                                if (!is_a_guest()) $visit['hidden_IP'] = 'true'; // Maybe Proxy or hidden IP
346                                //$visit['IP'] = $_SERVER['REMOTE_ADDR'];
347                                $v = $key;
348                                break;
349                }
350                // 3rd and last case: Same user_id
351                if ($record['user_id'] == $user['id'] and !is_a_guest()) { // new IP and new session
352                                $visit = $record;
353                                $visit['hidden_IP'] = 'true'; /* Or Generic user or the user is using several connections */
354                                //$visit['IP'] = $_SERVER['REMOTE_ADDR'];
355                                $v = $key;
356                                break;
357                }
358        }
359
360        // Step 2 - Assume a new comer
361        if ( !isset($visit) ) {
362                $visit = Array( 
363                        'IP' => $_SERVER['REMOTE_ADDR'], // First known IP (Is that one true?)
364                        'hidden_IP' => 'false', // supposed a fixed IP
365                        'session_id' => $sid,
366                        'user_id' => $user['id'],
367                        'username' => $user['username'],
368                        'delay' => 0,
369                        'lang' => substr($lang_info['code'],0,2),
370                        'permanent' => 'false', // False: delete after 72 Hours / True: delete after 90 days
371                        'last_access' => time(), // Last access by this user
372                        'elm_ids' => array_fill(0, 10, 0), // 10 last minutes + Last reference minute
373                        'cat_ids' => array_fill(0, 12, 0), // 12 ranges (of 5 minutes) + ref
374                        'tag_ids' => array_fill(0, 24, 0), // 24 hours + ref
375                        'sch_ids' => array_fill(0, 14, 0), // 14 days + ref
376                        'date' => date('Y-m-d'), // Futur usage
377                        'elm_hits' => 0, 'pag_hits' => 0, // elements hits and pages hits by this user
378                        'first_access_date' => date('Y-m-d'), // First access by this user
379                        'dates' => Array(), // 5 last access dates
380                );
381                $online[] = $visit;
382                $v = count($online);
383        }
384
385        // Step 3 - Monitor this access
386        $base = script_basename();
387        // Picture page
388        if (isset($page['image_id']) and $base == 'picture') {
389                whois_online_track($visit['elm_ids'], $page['image_id'],$visit['dates']);
390                if (isset($page['tags']))
391                whois_online_track($visit['tag_ids'], $page['image_id'],$visit['dates']);
392                if (isset($page['search']))
393                whois_online_track($visit['sch_ids'], $page['image_id'],$visit['dates']);
394                $visit['elm_hits']++;
395                $global['elm_hits']++;
396        }
397        // Category page
398        if (isset($page['category']['id']) and $base == 'index')
399                whois_online_track($visit['cat_ids'], $page['category']['id'],$visit['dates']);
400        // Page index
401        if (!isset($page['category']['id']) and !isset($page['image_id']))
402                whois_online_track($visit['cat_ids'], '' ,$visit['dates']);
403        $visit['pag_hits']++;
404        $global['pag_hits']++;
405
406        // Step 4 - Identify current range
407        $current = floor(time() / 60);                  // minutes for Unix time origin
408        $minute = $current % 10;                                                // (0-9) current minute
409        $five = floor($current / 5);    // (0-11) last 5 minutes range
410        $hour = floor($current / 60);   // (0-11) last hours
411        $day = floor($current / 1440); // (0-13) last days
412        if (isset($global['elm_ids'][10])) $old = $global['elm_ids'][10]; // previous minute (last one, or maybe 60 minutes ago or more).
413        else $old = $current; /* Only the first time or prevent wrong changes */
414
415        // Step 5 - Hits by range
416        if ($current != $old) {
417                $global['elm_ids'][11] = $global['elm_ids'][$minute];
418                $raz = min($current-$old, 10);
419        // 5.1 - $global['elm_ids'] ( hits by minute range )
420                for ($i=0;$i<$raz;$i++) {
421                        $global['elm_ids'][($minute+10-$i)%10] = 0;
422                }
423        // 5.2 - $global['cat_ids'] ( hits by 5 minutes range )
424                if (isset($global['cat_ids'][12])) $oldfive = $global['cat_ids'][12];
425                else $oldfive = floor($old / 5);
426                $raz = min($five - $oldfive, 12);
427                for ($i=0;$i<$raz;$i++) {
428                        $global['cat_ids'][($five+12-$i)%12] = 0; // Reset in backside
429                }
430        // 5.3 - $global['tag_ids'] (hits by hours )
431                if (count($global['tag_ids'])<25) $global['tag_ids'] = array_fill(0, 24, 0);
432                if (isset($global['tag_ids'][24])) $oldhour = $global['tag_ids'][24];
433                else $oldhour = floor($old / 60);
434                $raz = min($hour - $oldhour, 24);
435                for ($i=0;$i<$raz;$i++) {
436                        $global['tag_ids'][($hour+24-$i)%24] = 0; // Reset in backside
437                }
438        // 5.4 - $global['sch_ids'] ( hits by days )
439                if (isset($global['sch_ids'][14])) $oldday = $global['sch_ids'][14];
440                else $oldday = floor($old / 1440);
441                $raz = min($day - $oldday, 14);
442                for ($i=0;$i<$raz;$i++) {
443                        $global['sch_ids'][($day+14-$i)%14] = 0; // Reset in backside
444                }
445        }
446        $global['elm_ids'][$minute]++;
447        $global['cat_ids'][$five%12]++;
448        $global['tag_ids'][$hour%12]++;
449        $global['sch_ids'][$day%14]++;
450  // !!! WARNING  !!! WARNING !!! WARNING !!! WARNING !!!
451        $global['elm_ids'][10] = $current; // reference minute has changed
452        $global['cat_ids'][12] = $five;
453        $global['tag_ids'][24] = $hour;
454        $global['sch_ids'][14] = $day;
455  // !!! WARNING  !!! WARNING !!! WARNING !!! WARNING !!!
456
457        // 5.5 - Add in previous
458  if (!isset($global['any_previous'])) {
459                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
460                        ' ADD `same_previous` VARCHAR( 255 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
461                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
462                        ' ADD `any_previous` VARCHAR( 255 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
463                pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . 
464                        ' ADD `user_agent` VARCHAR( 160 ) NOT NULL DEFAULT \'\'  AFTER `country`;');
465        }
466
467        $antiaspi = array(
468    'diff' => '20 pages in 00:00:10' , // Banned for 20 access in 10 seconds or less
469    'same' => '15 pages in 00:00:30' , // Banned for 15 access on the same page in 30 seconds or less
470    'banned during' => '23:59:59' ,    // Banned time hh:mm:ss or any valid MySQL datetime expression 'YYYY-MM-DD HH:MM:SS'
471    'only guest' => true ,             // True, registred members won't be banned
472    'only picture' => false ,          // True, Check only on picture pages
473    'allowed ip' => array()            // Allowed IP array (Bots, or your fixed IP)
474  );
475  if (isset($conf['antiaspi'])) $antiaspi = array_merge($antiaspi, $conf['antiaspi']);
476
477        // For AntiAspi follow ANY PREVIOUS access
478        $access = '0:';
479        list($max_any, $maxtext) = explode(' pages in ', $antiaspi['diff']);
480        $maxtime = whois_online_duration($maxtext);
481        $prev='';
482        $previous = (isset($visit['any_previous'])) ? explode(' ', $visit['any_previous']):Array();
483        foreach ($previous as $v) {
484                $old = explode(':', $v);
485                $old[0] += $visit['delay']; 
486                if ($old[0]<$maxtime) $prev .= $old[0].': ';
487        }
488        $prev = $access . ' ' . $prev;
489        $prev = substr($prev, 0, -2);
490        $visit['any_previous'] = $prev;
491        // For AntiAspi follow ANY SAME PICTURE access
492        $access = '0:';
493        $same_elem = (isset($page['image_id'])) ? $page['image_id']:'0';
494        list($max_same, $maxtext) = explode(' pages in ', $antiaspi['same']);
495        $maxtime = whois_online_duration($maxtext);
496        $access .= $same_elem . ':';
497        $prev='';
498        $previous = (isset($visit['same_previous'])) ? explode(' ', $visit['same_previous']):Array();
499        foreach ($previous as $v) {
500                $old = explode(':', $v);
501                $old[0] += $visit['delay'];
502                if ($old[0]<$maxtime and $old[1]==$same_elem) $prev .= $old[0].':'.$old[1].': ';
503        }
504        $prev = $access . ' ' . $prev;
505        $prev = substr($prev, 0, -2);
506        $visit['same_previous'] = $prev;
507       
508        // Check limits of $visit['any_previous'] and $visit['same_previous']
509        // by 256 characters
510        // by $max_any and by $max_same
511        while (strlen($visit['any_previous'])>256) {
512          $previous = explode(' ',$visit['any_previous']);
513                $oldest = array_pop($previous);
514                $visit['any_previous'] = implode(' ', $previous);
515        }
516        $ctr_any = count(explode(' ',$visit['any_previous']));
517        while (strlen($visit['same_previous'])>256) {
518          $previous = explode(' ',$visit['same_previous']);
519                $oldest = array_pop($previous);
520                $visit['same_previous'] = implode(' ', $previous);
521        }
522        $ctr_same = count(explode(' ',$visit['same_previous']));
523       
524        $visit['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
525        $Vip =& $visit['IP'];
526        $visit['Allowed_SE'] = false;
527  if (!empty($antiaspi['allowed ip']))
528  {
529    $allowed_ips = str_replace(array('.', '%'), array('\.', '.*?'), $antiaspi['allowed ip']);
530    foreach ($allowed_ips as $ip)
531    {
532      if (preg_match("#" . $ip . "#", $Vip)) { $visit['Allowed_SE'] = true; break; }
533    }
534  }
535       
536        // Step 6 - Update (on Conf_Update and trace) and send trace to determine global tracing or not
537        $dtrace = 0;
538        if ($user['status'] == 'admin') $dtrace += $conf_whois['Administrators'];
539        elseif ($user['status'] == 'webmaster') $dtrace += $conf_whois['Webmasters'];
540        else $dtrace = 2;
541        if ($conf['Whois Online Update'] and $dtrace > 0) whois_online_update($global, $visit, $dtrace);
542
543        // Step 7 - Find your recent visits (These image_ids are presumely authorized)
544        $my_ids = $visit['elm_ids'];
545        sort($my_ids);
546        unset($my_ids[0]);
547        $url_visited = (count($my_ids)>0) ? make_index_url(array('list' => $my_ids)).'&amp;review':'';
548
549        // Step 8 - Guest count and Member list
550        $h24 = 0; $h1 = 0; $guest = 0;
551        $list = array();
552        $elm = array(); $excl = array(); // Get images_ids from all and from the current visitor
553        foreach ($online as $k => $monit)
554        {
555                if ($user['id']==$monit['user_id']) $excl = $monit['elm_ids'];
556                else $elm = array_merge($elm, $monit['elm_ids']);
557                if ($monit['delay'] <= (24*3600)) $h24++;
558                if ($monit['delay'] <= 3600) $h1++;
559                // Less than 5 minutes: users are considered as still online...
560                if ($monit['delay'] <= 300) {
561                        if ($monit['user_id'] == $conf['guest_id']) $guest++;
562                        else $list[] = $monit['username'];
563                }
564        }
565        // The first (and current) access are not recorded in $online
566        // As visitor you are not expecting your access to be already counted: Ok that the case
567        // but you are expecting to see you as a member in the member list if you are: and there it is
568        if ($visit['user_id'] != $conf['guest_id'] ) $list[] = $visit['username'];
569        $list = array_unique($list);
570       
571        if (count($list) > $conf_whois['Users']['max']) {
572                $conf_whois['Users']['max'] = count($list);
573                $conf_whois['Users']['When'] = time();
574                $conf['Whois Online'] = serialize($conf_whois);
575                pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
576    VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
577        }
578
579        // Step 9 - Review pictures viewed by others (all images except yours)
580        $elm = array_diff( array_unique($elm), $excl );
581        shuffle($elm);
582        $elm = array_slice($elm,0,($conf['top_number']+50));
583        sort($elm);
584        array_shift($elm);
585        $elm[] = 0; // Check if authorized pictures
586        $query = 'SELECT DISTINCT(image_id)
587  FROM '.IMAGE_CATEGORY_TABLE.'
588    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
589  WHERE image_id IN ('.implode(',', $elm ).')
590    '.get_sql_condition_FandF(
591      array(
592          'forbidden_categories' => 'category_id',
593          'visible_categories' => 'category_id',
594          'visible_images' => 'id'
595        ), "\n  AND") . ';';
596        $ids = array_from_query($query, 'image_id');
597        shuffle($ids);
598        $ids = array_slice($ids, 0, $conf['top_number']); // Keep some
599        $url_someothers = (isset($ids[0])) ? make_index_url(array('list' => $ids)).'&amp;others':'';
600
601        // Random page title change
602        $url_type = pwg_get_session_var('whois_url_type', ''); /* previous review or others */
603        $list_ids = pwg_get_session_var('whois_list_ids', ''); /* previous list/xx,yy,zz, ... */
604        $list_section = (isset($page['section']) and $page['section'] == 'list') ? true:false;
605        $same_ids = (isset($page['list']) and $page['list'] == $list_ids) ? true:false;
606        if ($list_section and isset($_GET['review'])) {
607                $url_type = 'Whois_review';
608                $same_ids = true;
609        }
610        if ($list_section and isset($_GET['others'])) {
611                $url_type = 'Whois_others';
612                $same_ids = true;
613        }
614        if ($list_section and $same_ids and isset($page['list'])) $list_ids = $page['list'];
615        else $url_type = ''; // Not the same list
616        pwg_set_session_var('whois_list_ids', $list_ids);
617        pwg_set_session_var('whois_url_type', $url_type);
618        if ($url_type != '' and $list_section)
619  $page['title'] = '<a href="'.duplicate_index_url(array('start'=>0)).'">'
620                    .l10n($url_type).'</a>';
621
622       
623        // Step 10 - Prepare data to display
624        $yesterday = ($day+13) % 14;
625        $template->assign('Whois', array(
626                'Total' => $global['pag_hits'],
627                'Image' => $global['elm_hits'],
628                'Other' => ($global['pag_hits']-$global['elm_hits']),
629                'Current_minute' => $global['elm_ids'][$minute],
630                'Previous_minute' => $global['elm_ids'][($minute+9) % 10],
631                'Current_5mins' => $global['elm_ids'][$minute]
632                                                                        + $global['elm_ids'][($minute+9) % 10]
633                                                                        + $global['elm_ids'][($minute+8) % 10]
634                                                                        + $global['elm_ids'][($minute+7) % 10]
635                                                                        + $global['elm_ids'][($minute+6) % 10],
636                'Current_10mins' => array_sum(array_slice($global['elm_ids'],0,10)),
637                'Current_hour' => array_sum(array_slice($global['cat_ids'],0,12)),
638                'Current_24h' => array_sum(array_slice($global['tag_ids'],0,24)),
639                'Yesterday' => $global['sch_ids'][$yesterday],
640                'Users_Last_day' => $h24,
641                'Users_Last_hour' => $h1,
642                'Guests' => $guest,
643                'Online' => $list,
644                'Review_url' => $url_someothers,
645                'Their_ids' => $ids,
646                'Seen_url' => $url_visited,
647                'My_ids' => $my_ids,
648                'Slideshow' => isset($_GET['slideshow']) ? true:false,
649        ));
650        $template->assign('Online', $global );
651
652        pwg_debug('end Online_management');
653}
654?>
Note: See TracBrowser for help on using the repository browser.