source: extensions/whois_online/include/wo_functions.inc.php @ 6172

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

Fix: Flags are coming back

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 12.4 KB
Line 
1<?php
2/* Functions */
3
4/* Secure Config */
5if (!isset($conf['Whois Online']) or !isset($conf_whois['Active'])) $conf_whois = whois_online_conf();
6
7function whois_online_conf()
8{
9        global $conf;
10        $default = array(
11          'Active' => true,
12          'Delete level' => 20,
13          'Radar limit' => 25,
14          'Webmasters' => 2, // Normal
15          'Administrators' => 2,
16          'Obsolete limit' => 20,
17                'Default display' => true,
18          'Add to Plugins menu' => false,
19          'Add icon to History' => true,
20          'Keep data' => true,
21          'Search id' => 0,
22          'Users' => Array('max' => 0, 'When' => date('Y-m-d'), 'count' => 0),
23        );
24        if (!isset($conf['Whois Online'])) $conf['Whois Online'] = serialize(Array());
25        $conf_whois = array_merge($default, unserialize($conf['Whois Online']));
26        if ((!isset($conf_whois['Version'])) or $conf_whois['Version'] != WHOIS_ONLINE_VER
27                or $conf['Whois Online'] != serialize($conf_whois)) {
28                $conf_whois['Version'] = WHOIS_ONLINE_VER;
29                $conf['Whois Online'] = serialize($conf_whois);
30                pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
31          VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
32        }
33        return $conf_whois;
34}
35
36
37if ( !function_exists('pwg_get_contents') ) {
38        function pwg_get_contents($url, $mode='') {
39
40                global $pwg_mode, $pwg_prev_host;
41                $timeout = 5; // will be a parameter (only for the socket)
42
43                $host = (strtolower(substr($url,0,7)) == 'http://') ? substr($url,7) : $url;
44                $host = (strtolower(substr($host,0,8)) == 'https://') ? substr($host,8) : $host;
45                $doc = substr($host, strpos($host, '/'));
46                $host = substr($host, 0, strpos($host, '/'));
47
48                if ($pwg_prev_host != $host) $pwg_mode = ''; // What was possible with one website could be different with another
49                $pwg_prev_host = $host;
50                if (isset($pwg_mode)) $mode = $pwg_mode;
51                if ($mode == 'r') $mode = '';
52                // $mode = 'ch'; // Forcing a test '' all, 'fs' fsockopen, 'ch' cURL
53
54        // 1 - The simplest solution: file_get_contents
55        // Contraint: php.ini
56        //      ; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
57        //      allow_url_fopen = On
58                if ( $mode == '' ) {
59                  if ( true === (bool) ini_get('allow_url_fopen') ) { 
60                                $value = file_get_contents($url);
61                                if ( $value !== false and substr($value,0,21) != '<!DOCTYPE HTML PUBLIC') {
62                                        return $value;
63                                }
64                        }
65                }
66                if ( $mode == '' ) $mode = 'fs';
67                if ( $pwg_mode == '' ) $pwg_mode = 'fs'; // Remind it
68        // 2 - Often accepted access: fsockopen
69                if ($mode == 'fs') {
70                        $fs = fsockopen($host, 80, $errno, $errstr, $timeout);
71                        if ( $fs !== false ) {
72                                fwrite($fs, 'GET ' . $doc . " HTTP/1.1\r\n");
73                                fwrite($fs, 'Host: ' . $host . "\r\n");
74                                fwrite($fs, "Connection: Close\r\n\r\n");
75                                stream_set_blocking($fs, TRUE);
76                                stream_set_timeout($fs,$timeout); // Again the $timeout on the get
77                                $info = stream_get_meta_data($fs);
78                                $value = '';
79                                while ((!feof($fs)) && (!$info['timed_out'])) {
80                                                                $value .= fgets($fs, 4096);
81                                                                $info = stream_get_meta_data($fs);
82                                                                flush();
83                                }
84                                if ( $info['timed_out'] === false  and substr($value,0,21) != '<!DOCTYPE HTML PUBLIC') return $value;
85                        }
86                }
87
88                if ( $pwg_mode == 'fs' ) $pwg_mode = 'ch'; // Remind it
89        // 3 - Sometime another solution: curl_exec
90        // See http://fr2.php.net/manual/en/curl.installation.php
91          if (function_exists('curl_init') and $pwg_mode == 'ch') {
92                        $ch = @curl_init();
93                        @curl_setopt($ch, CURLOPT_URL, $url);
94                        @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
95                        @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
96                        @curl_setopt($ch, CURLOPT_HEADER, 1);
97                        @curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
98                        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
99                        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
100                        $value = @curl_exec($ch);
101                        $header_length = @curl_getinfo($ch, CURLINFO_HEADER_SIZE);
102                        $status = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
103                        @curl_close($value);
104                        if ($value !== false and $status >= 200 and $status < 400) {
105                                $value = substr($value, $header_length);
106                                // echo '<br/>-ch- ('. $value . ') <br/>';
107                                return $value;
108                        }
109                        else $pwg_mode = 'failed'; // Sorry but remind it as well
110                }
111
112                // No other solutions
113                return false;
114        }
115}
116// Assume the Default display on pages
117function whois_default_display() {
118        global $template;
119        $template->set_filenames(array( 'Whois_display' => dirname(__FILE__).'/../default.tpl'));
120        $template->pparse('Whois_display');
121}
122
123// Add admin links
124function whois_add_icon($menu) {
125        global $conf_whois, $lang;
126        if ($conf_whois['Add icon to History'])
127                $lang['History'] .= '</a> <a class="external" href="' . get_admin_plugin_menu_link(WHOIS_ONLINE_PATH.'config.php') . '">
128                        <img class="button" src="' . WHOIS_ONLINE_PATH . 'icons/Whois_tuner.gif" alt="Whois Online configuration" title="Whois Online configuration" /></a>';
129        if ($conf_whois['Add to Plugins menu']) array_push($menu, array(
130                                'NAME' => 'Whois Online',
131                                'URL' => get_admin_plugin_menu_link(WHOIS_ONLINE_PATH.'config.php'),
132                        ));
133        return $menu;
134}
135
136// Template function
137function Whois_most($text, $count, $when, $format) {
138 return sprintf(l10n($text),$count,date(l10n($format),$when));
139}
140
141// New member
142function whois_online_register($who) {
143        global $conf, $conf_whois;
144        $conf_whois['Users']['count'] = $who['id'];
145        $conf['Whois Online'] = serialize($conf_whois);
146        pwg_query('REPLACE INTO ' . CONFIG_TABLE . " (param,value,comment)
147  VALUES ('Whois Online','". $conf['Whois Online'] ."','Whois Online configuration');");
148        return;
149}
150
151function whois_country($trace, $bypass = false) {
152  if (!isset($trace['country'])) {
153                        pwg_query('ALTER TABLE ' . WHOIS_ONLINE_TABLE . ' ADD `country` VARCHAR( 254 ) NOT NULL AFTER `lang` ;');
154                        $trace['country']='';
155        }
156        $c = array();
157        if ($trace['country']!='') $c = @unserialize(htmlspecialchars_decode($trace['country']));
158        if (isset($c['Code']) and $c['Code']!='' and $c['Code']!='__') return $c; 
159        if ($bypass and isset($c['Code'])) return $c;
160    $result = pwg_get_contents ('http://api.hostip.info/get_html.php?ip=' . $trace['IP'], 'r');
161        if ( $result !== false ) { 
162                $tokens = preg_split("/[:]+/", $result);
163                $c = array ('Name' => $tokens[1], 'City' => substr($tokens[3],0,-3));
164                if (strpos ($c['Name'], '?') === FALSE) {
165                        $c['Code'] = substr($c['Name'],-8,2); # " (Private Address) (XX) City"
166                        $c['Name'] = ucwords ( strtolower( substr($c['Name'],0,-5)));
167                }
168                else $c = Array('Code' => '__', 'Name' => l10n('Unknown country'), 'City' => 'N/A',);
169        }
170        if (stripos($c['Name'], 'Squid')!==false) $c = Array('Code' => '__', 'Name' => l10n('Unknown country'), 'City' => 'N/A',);
171        // else $c = Array('Code' => '__', 'Name' => l10n('Unknown country'), 'City' => 'N/A',);
172        if ($c['Code'] == 'Private Address') {
173                $c['Name'] = l10n('Private Address');
174                $c['City'] = l10n('N/A');
175                $c['Code'] = '__';
176        }
177        $new = htmlspecialchars(serialize($c),ENT_QUOTES,'UTF-8');
178        if ($new == $trace['country']) return $c;
179        pwg_query('UPDATE ' . WHOIS_ONLINE_TABLE . '
180      SET `country` = \'' . $new . '\'
181    WHERE `session_id` = \'' . $trace['session_id'] . '\';');
182  return $c;
183}
184
185function whois_flag($trace, &$step, $limit = 10) {
186  $flag = WHOIS_ONLINE_PATH . 'flags/' . $trace['Country']['Code'] . '.jpg';
187        if (file_exists($flag) and $flag != '__' ) return $flag;
188        if ( $step > $limit ) return WHOIS_ONLINE_PATH . 'flags/__.jpg';
189        $f = fopen  ('http://api.hostip.info/flag.php?ip=' . $trace['IP'], 'r');
190        $result='';
191        while ($l = fgets ($f, 1024)) $result .= $l;
192        fclose ($f);
193                $f = fopen($flag,"w+");
194        fputs($f,$result);
195        fclose($f);
196  return $flag;
197}
198
199// Read all data
200function whois_online_get_data($order='') {
201        $remove = "''"; // Nothing to remove ( = an empty session_id)
202        $ctr = 0; $Online[0] = '';
203        $result = pwg_query('SELECT * FROM ' . WHOIS_ONLINE_TABLE . $order . ';');
204        while($row=mysql_fetch_array($result)) {
205                $row['delay'] = (int) time() - $row['last_access'];
206                $row['elm_ids'] = explode(' ', $row['last_elm_ids']);
207                $row['cat_ids'] = explode(' ', $row['last_cat_ids']);
208                $row['tag_ids'] = explode(' ', $row['last_tag_ids']);
209                $row['sch_ids'] = explode(' ', $row['last_sch_ids']);
210                $row['dates'] = explode(' ', $row['last_dates']);
211                $ctr++;
212                if ( $row['IP'] != 'global' and $row['permanent'] == 'false'
213                        and $row['delay'] > (float)( 60 * 60 * 24 * 3 )) $remove .= ", '" . $row['session_id'] . "'";
214                elseif ($row['IP'] == 'global') $Online[0] = $row;
215                else $Online[] = $row;
216        }
217        // Out of 7 visits: Reduce registered visits for 3 days without access
218        if ($remove != "''" and $ctr > (count($Online) * ONLINE_LEVEL)
219                and ($ctr-count($Online)) > ONLINE_LIMIT and ($Online[0]['pag_hits']%7)==0) {
220                pwg_query('DELETE FROM ' . WHOIS_ONLINE_TABLE . ' WHERE `session_id` IN ('. $remove .')
221                                AND `permanent` = \'false\' AND `IP` <> \'global\';');
222                if (($Online[0]['pag_hits']%13)==0) @pwg_query('OPTIMIZE TABLE ' . WHOIS_ONLINE_TABLE . ';');
223        }
224        return $Online;
225}
226
227// Update global and update/create current session_id
228function whois_online_update(&$global, &$dedicated, &$gtrace)
229{
230        global $lang_info;
231        // Rewrite the global record
232        if ( $gtrace == 2 ) {
233                $query = 'REPLACE INTO ' . WHOIS_ONLINE_TABLE . ' (`IP`, `hidden_IP`, `session_id`,`user_id`,`username`,`lang`,
234                `permanent`,`last_access`,`last_elm_ids`, `last_cat_ids`, `last_tag_ids`, `last_sch_ids`,
235                `first_access_date`, `last_dates`, `elm_hits`, `pag_hits`)
236                        VALUES (\'global\', \'true\',\'global\', 0, \''. $global['username'] .'\', \'--\', \'true\', \''
237                        . time()  .'\',  \''
238                        . implode(' ',$global['elm_ids']) . '\', \''
239                        . implode(' ',$global['cat_ids']) . '\', \''
240                        . implode(' ',$global['tag_ids']) . '\', \''
241                        . implode(' ',$global['sch_ids']) . '\', \''
242                        . $global['first_access_date'] . '\', \'\', \''
243                        . $global['elm_hits'] . '\', \'' . $global['pag_hits'] . '\');';
244                pwg_query($query);
245        }
246        // Write or Rewrite the dedicated record
247        $query = 'REPLACE INTO ' . WHOIS_ONLINE_TABLE . ' (`IP`, `hidden_IP`, `session_id`,`user_id`,`username`,`lang`, `user_agent`,
248        `any_previous`, `same_previous`, `permanent`,`last_access`,`last_elm_ids`, `last_cat_ids`, `last_tag_ids`, `last_sch_ids`,
249        `first_access_date`, `last_dates`, `elm_hits`, `pag_hits`)
250                VALUES (\''. $dedicated['IP'] .'\', \''
251                . $dedicated['hidden_IP'] .'\', \''. $dedicated['session_id'] .'\', \''
252                . $dedicated['user_id'] .'\', \''. $dedicated['username'] .'\', \''
253                . substr($lang_info['code'],0,2) .'\', \''
254                . $dedicated['user_agent'] .'\', \''
255                . $dedicated['any_previous'] .'\', \''
256                . $dedicated['same_previous'] .'\', \''
257                . $dedicated['permanent'] . '\', \''. time() .'\',  \''
258                . implode(' ',$dedicated['elm_ids']) . '\', \''
259                . implode(' ',$dedicated['cat_ids']) . '\', \''
260                . implode(' ',$dedicated['tag_ids']) . '\', \''
261                . implode(' ',$dedicated['sch_ids']) . '\', \''
262                . $dedicated['first_access_date'] . '\', \''
263                . implode(' ',$dedicated['dates']) . '\', \''
264                . $dedicated['elm_hits'] . '\', \''
265                . $dedicated['pag_hits'] . '\');';
266        pwg_query($query);
267}
268
269// Data tracking
270// Parameters:
271//  - Array of Ids
272//  - New ID
273//  - Array of dates
274// => Add the ID if needed, Add Today if needed
275function whois_online_track(&$key, $id, &$date) {
276        if ($id != '') array_unshift($key, $id);
277        $key = array_unique($key);
278        if (count($key)>10) array_pop($key);
279        array_unshift($date, date('Y-m-d'));
280        $date = array_unique($date);
281        if (count($date)>5) array_pop($date);
282        return;
283}
284
285// Antiaspi delay conversion in seconds
286// delay in "HH:ii:ss" or "d :HH:ii:ss"
287// return delay in seconds
288function whois_online_duration($date_string)
289{
290 list($s, $i, $H, $d, $more) = 
291   array_merge(array_reverse(
292           explode(" ",str_ireplace(':',' ', $date_string))),
293                 array(0,0,0,0,0));
294 $t = time();
295 return strtotime(sprintf("+%s days %s hours %s minutes %s seconds", 
296   $d, $H, $i, $s), $t) - $t;
297}
298
299/*
300  returns (mixed): (string) 'bot agent name'  || (bool) false
301  @param (string) HTTP_USER_AGENT
302*/
303function is_a_bot($agent = '') 
304{
305  global $conf;
306        if ($agent == '') $agent = $_SERVER['HTTP_USER_AGENT'];
307        $botlist = array('Teoma', 'alexa', 'froogle', 'Gigabot', 'inktomi',
308        'looksmart', 'URL_Spider_SQL', 'Firefly', 'NationalDirectory', 
309        'Ask Jeeves', 'TECNOSEEK', 'InfoSeek', 'WebFindBot', 'girafabot',
310        'crawler', 'www.galaxy.com', 'Googlebot', 'Scooter', 'Slurp',
311        'msnbot', 'appie', 'FAST', 'WebBug', 'Spade', 'ZyBorg', 'rabaz',
312        'Baiduspider', 'Feedfetcher-Google', 'TechnoratiSnoop', 'Rankivabot',
313        'Mediapartners-Google', 'Sogou web spider', 'WebAlta Crawler');
314  if (isset($conf['search_agents']))
315          $botlist = array_merge( $botlist, array_diff( $conf['search_agents'], $botlist ) );
316  foreach($botlist as $bot) {
317    if (stripos($agent, $bot)!==false) return $bot; 
318  }
319  return false;
320} 
321?>
Note: See TracBrowser for help on using the repository browser.