<?php
	// check if $ip is a valid one and returns the type as int
	function is_valid_ip( $ip )
	{
		if (filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
			return 4;
		else if (filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
			return 6;
		else
			return false;
	}

	// return the description of a class based on the "classes" db table
	function description( $category )
	{
		global $cache;
		if( !isset( $cache['categories'] ) )
		{
			$res = get_db_rows( "SELECT * FROM classes" );
			while ( $row = get_db_tuple( $res ) )
				$cache['categories'][$row['classid']] = $row;
		}
		if (!isset( $cache['categories'][$category] ))
			return false; // returns false if non-existent
			
		$ret = '';
		if (!empty($cache['categories'][$category]['description']))
			$ret .= $cache['categories'][$category]['description'];
		else
			$ret .= 'no information about this type available';
			
		return $ret;
	}

	// return the typename of a class based on the "classes" db table
	function ClassInfo( $id, $field = 'description')
	{
		global $cache;
		if( !isset( $cache['classes'] ) )
		{
			$res = get_db_rows( "SELECT * FROM classes" );
			while ( $row = get_db_tuple( $res ) )
				$cache['classes'][$row['classid']] = $row;
		}
		if (!isset( $cache['classes'][$id] ) || !isset( $cache['classes'][$id][$field] ))
			return false; // returns false if non-existent
			
		$ret = '';
		if (!empty( $cache['classes'][$id]['url'] ))
			$ret .= '<a style="color:inherit" rel="external" title="click here for more information" href="'.$cache['classes'][$id]['url'].'">';
		if (!empty($cache['classes'][$id][$field]))
			$ret .= $cache['classes'][$id][$field];
		if (!empty( $cache['classes'][$id]['url'] ))
			$ret .= '</a>';
			
		return $ret;
	}

	// is $category a valid ban class based on the "classes" db table?
	function is_valid_type( $category )
	{
		return description($category) ? true : false;
	}

	// returns true if the ban class requires admin removal of members
	function immutable( $type=false )
	{
		$arr_immutable = [1, 2];
		return $type ? false : in_array( $type, $arr_immutable );
	}
	
	function reverse_ip( $ip ) {
		if( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) )
			return implode( '.', array_reverse( explode( '.', $ip ) ) );
		else if( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) )
		{
			$unpack = unpack( 'H*hex', inet_pton( $ip ));
			return implode( '.', array_reverse( str_split( $unpack['hex'] ) ) );
		}
		else
			return false;
	}
	
	// helper function for ip_in_range regarding ipv6
	function inet_to_bits( $inet ) 
	{
		$unpacked = unpack( 'A16', $inet );
		$unpacked = str_split( $unpacked[1] );
		$binaryip = '';
		foreach ( $unpacked as $char )
			$binaryip .= str_pad( decbin( ord( $char ) ), 8, '0', STR_PAD_LEFT );
		return $binaryip;
	}    

	// determine if an ip is in the given range
	function ip_in_range( $ip, $range )
	{
		if (count(explode('/', $range)) < 2)
			return false;
		list( $subnet, $mask ) = explode( '/', $range );
		if( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) && filter_var( $subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) )
			return ( ( ip2long( $ip ) & ~( ( 1 << ( 32 - $mask ) ) - 1 ) ) == ip2long( $subnet ) );
		else if( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 )  && filter_var( $subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) )
			return ( substr( inet_to_bits( inet_pton( $ip ) ), 0, $mask) == substr( inet_to_bits( inet_pton( $subnet ) ), 0, $mask ) );
		else
			return false;
	}

	// check if $ip is whitelisted
	function whitelisted( $ip )
	{
		global $cache;
		if ( !isset( $cache['whitelist'] ) )
		{
			$res = get_db_rows( "SELECT * FROM whitelist" );
			while ( $row = get_db_tuple( $res ) )
				$cache['whitelist'][$row['ip']] = $row['description'];
		}
		foreach( array_keys( $cache['whitelist'] ) AS $mask)
		{
			if ( ip_in_range( $ip, $mask ) )
				return $cache['whitelist'][$mask];
		}
		return false;
	}

	function is_valid_email( $email )
	{
		list( $user, $host ) = explode( '@', $email, 2 );
		$mxhost = array();
		$mxprio = array();
		getmxrr( $host, $mxhost, $mxprio );
		$lowest = -1;
		$counter = 0;
		$peak = 10000;
		foreach( $mxprio AS $seek )
		{
			if( $seek < $peak )
			{
				$peak = $seek;
				$lowest = $counter;
			}
			$counter++;
		}
		$mxtouse = ($lowest != -1 ? $mxhost[$lowest] : '');

		if( empty( $mxtouse ) )
			return 'No MX record found for ' . $host;

		$smtp = fsockopen( $mxtouse, 25, $errno, $errstr, 10 );
		if( !$smtp )
			return 'Unable to connect to ' . $mxtouse;

		// Get greeting
		$line = fread( $smtp, 1024 );
		if( !preg_match( '/^220/', $line ) )
		{
			fclose( $smtp );
			return 'MX replied &quot;' . $line . '&quot; instead of a greeting';
		}

		// Send HELO and await 250
		fwrite( $smtp, "HELO mailchecker\r\n" );
		$line = fgets( $smtp, 512 );
		if( !preg_match( '/^250/' ,$line ) )
		{
			fclose( $smtp );
			return 'MX replied &quot;' . $line . '&quot; after HELO';
		}

		// Send MAIL FROM and await 250
		fwrite( $smtp, 'MAIL FROM: <mailtest-' . $user . '@' . $_SERVER['HTTP_HOST'] . ">\r\n" );
		$line = fgets( $smtp, 512 );
		if( !preg_match( '/^250/', $line ) )
		{
			fclose( $smtp );
			return 'MX replied &quot;' . $line . '&quot; after MAIL';
		}

		// Send RCPT TO and wait for the result :)
		fwrite( $smtp, "RCPT TO: <$email>\r\n" );
		$line = fgets( $smtp, 512 );
		$code = intval( substr( $line, 0, 3 ));
		$fcodes = array( 550, 552, 553, 521);
		if( in_array( $code, $fcodes ) )
		{
			fclose( $smtp );
			return 'MX replied &quot;' . $line . '&quot; after RCPT';
		}

		fclose( $smtp );
		return 0;
	}

	function _getasn( $ip )
	{
		$data = get_db_tuple( get_db_rows("SELECT asn FROM ip2info WHERE '".$ip."'::inet BETWEEN ip_start AND ip_stop ORDER BY ip_start DESC LIMIT 1"));
		return $data['asn'];
	}
	
	function _getcountry( $ip )
	{
		$data = get_db_tuple( get_db_rows("SELECT country FROM ip2info WHERE '".$ip."'::inet BETWEEN ip_start AND ip_stop ORDER BY ip_start DESC LIMIT 1"));
		return ($data ? $data['country'] : false);
	}
	
	function get_whois( $ip )
	{
		$result = array();
		$res = get_db_rows("SELECT * FROM whoiscache WHERE '".db_escape($ip)."'::inet << cidr::cidr AND ts > now()::abstime::int4 - (7*86400)");
		if (db_num_rows($res))
		{
			while ($tuple = get_db_tuple($res, DB_ASSOC))
				$result[] = $tuple;
			return $result;
		}
		
		$data = exec('/usr/bin/env whois '.$ip, $output);
		
		$a = 0;
		$asn = 0;
		
		foreach($output AS $line)
		{
			if (empty($line))
				continue;
				
			$data = explode(' ', $line, 2);
			if (!isset($data[1]))
				continue;
				
			$data[0] = strtolower(str_replace(':', '', $data[0]));
			$data[1] = trim($data[1]);
			
			switch($data[0])
			{
				case 'netrange':
				case 'inetnum':
					$a++;
					$result[$a]['range'] = $data[1];
					$result[$a]['asn'] = $asn;
					break;
					
				case 'abuse-mailbox':
				case 'orgabuseemail':
				case 'orgtechemail':
				case 'orgnocemail':
					$result[$a]['email'][] = $data[1];
					break;
					
				case 'origin':
				case 'originas':
					$asnt = str_replace('as','', strtolower($data[1]));
					if ($asnt)
					{
						$result[$a]['asn'] = $asnt;
						$asn = $asnt;
					}
					break;
					
				case 'route':
				case 'cidr':
					$result[$a]['cidr'] = $data[1];
					break;
					
				default:
					continue(2);
			}		
		}
		
		$reply = array();
		foreach($result AS $res)
		{
			if (isset($res['range']))
			{
				if (!isset($res['cidr']))
				{
					// calculate cidr here, for now, we break
					continue;
				}
				unset($res['range']);
			}
			
			if (!isset($res['cidr']))
				continue;
			
			$res['email'] = implode(' ', array_unique($res['email']));
			get_db_rows("INSERT INTO whoiscache (cidr, asn, emails) VALUES('".$res['cidr']."','".$res['asn']."','".db_escape($res['email'])."')");
			$reply[] = $res;
		}
		return $reply;
	}

	function _islisted( $ip )
	{
		global $cache;
		if( !isset( $cache['listed'][$ip] ) )
		{
			$tuple = get_db_tuple( get_db_rows( "SELECT id FROM blacklist WHERE ip::inet='" . $ip . "'::inet AND listed=1 LIMIT 1" ) );
			$cache['listed'][$ip] = ( $tuple ? true : false );
		}
		return $cache['listed'][$ip];
	}

	function _isprivate($ip)
	{
		if( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) )
		{		
			// ipv4 in ipv6 mapping
			if( preg_match( '/^2002:([0-9a-f]+):([0-9a-f]+):/i', $ip, $matches ) )
			{
				$result = str_pad( $matches[1], 4, 0, STR_PAD_LEFT ) . str_pad( $matches[2], 4, 0, STR_PAD_LEFT );
				$sip = array();
				for( $i = 0; $i < strlen( $result ); $i = $i + 2 )
					$sip[] = base_convert( substr( $result, $i, 2 ), 16, 10 );
				return _isprivate( implode( '.', $sip ) );
			}
			
			if( preg_match( '/^::ffff:0:([0-9\.]+)/', $ip, $matches ) )
				return _isprivate( $matches[1] );
		}
		
		$data = get_db_tuple(get_db_rows("SELECT 1 from ip2info where '".$ip."'::inet between ip_start and ip_stop"));
		if (!$data)
			return true;
		return false;
	}
	
	function _istor( $ip )
	{
		$res = get_db_rows("SELECT exit FROM torcache WHERE ip='".db_escape($ip)."'::inet AND ts > now()::abstime::int - 300 LIMIT 1");
		if (db_num_rows($res))
		{
			$tuple = get_db_tuple($res, DB_ASSOC);
			return intval($tuple['exit']);
		}
		$data = checkdnsrr( reverse_ip($ip).'.torexit.dan.me.uk', 'TXT');
		get_db_rows("INSERT INTO torcache (ip, exit) VALUES ('".db_escape($ip)."','".($data ? 1 : 0)."')");
		return $data;
	}
	
	// simple code -> countryname conversion
	function countryname( $code )
	{
		if( $code == 'AF' ) return 'Afghanistan';
		if( $code == 'AX' ) return 'Aland Islands';
		if( $code == 'AL' ) return 'Albania';
		if( $code == 'DZ' ) return 'Algeria';
		if( $code == 'AS' ) return 'American Samoa';
		if( $code == 'AD' ) return 'Andorra';
		if( $code == 'AO' ) return 'Angola';
		if( $code == 'AI' ) return 'Anguilla';
		if( $code == 'AQ' ) return 'Antarctica';
		if( $code == 'AG' ) return 'Antigua and Barbuda';
		if( $code == 'AR' ) return 'Argentina';
		if( $code == 'AM' ) return 'Armenia';
		if( $code == 'AW' ) return 'Aruba';
		if( $code == 'AU' ) return 'Australia';
		if( $code == 'AT' ) return 'Austria';
		if( $code == 'AZ' ) return 'Azerbaijan';
		if( $code == 'BS' ) return 'Bahamas the';
		if( $code == 'BH' ) return 'Bahrain';
		if( $code == 'BD' ) return 'Bangladesh';
		if( $code == 'BB' ) return 'Barbados';
		if( $code == 'BY' ) return 'Belarus';
		if( $code == 'BE' ) return 'Belgium';
		if( $code == 'BZ' ) return 'Belize';
		if( $code == 'BJ' ) return 'Benin';
		if( $code == 'BM' ) return 'Bermuda';
		if( $code == 'BT' ) return 'Bhutan';
		if( $code == 'BO' ) return 'Bolivia';
		if( $code == 'BA' ) return 'Bosnia and Herzegovina';
		if( $code == 'BW' ) return 'Botswana';
		if( $code == 'BV' ) return 'Bouvet Island (Bouvetoya)';
		if( $code == 'BR' ) return 'Brazil';
		if( $code == 'IO' ) return 'British Indian Ocean Territory (Chagos Archipelago)';
		if( $code == 'VG' ) return 'British Virgin Islands';
		if( $code == 'BN' ) return 'Brunei Darussalam';
		if( $code == 'BG' ) return 'Bulgaria';
		if( $code == 'BF' ) return 'Burkina Faso';
		if( $code == 'BI' ) return 'Burundi';
		if( $code == 'KH' ) return 'Cambodia';
		if( $code == 'CM' ) return 'Cameroon';
		if( $code == 'CA' ) return 'Canada';
		if( $code == 'CV' ) return 'Cape Verde';
		if( $code == 'KY' ) return 'Cayman Islands';
		if( $code == 'CF' ) return 'Central African Republic';
		if( $code == 'TD' ) return 'Chad';
		if( $code == 'CL' ) return 'Chile';
		if( $code == 'CN' ) return 'China';
		if( $code == 'CX' ) return 'Christmas Island';
		if( $code == 'CC' ) return 'Cocos (Keeling) Islands';
		if( $code == 'CO' ) return 'Colombia';
		if( $code == 'KM' ) return 'Comoros the';
		if( $code == 'CD' ) return 'Congo';
		if( $code == 'CG' ) return 'Congo the';
		if( $code == 'CK' ) return 'Cook Islands';
		if( $code == 'CR' ) return 'Costa Rica';
		if( $code == 'CI' ) return 'Cote d\'Ivoire';
		if( $code == 'HR' ) return 'Croatia';
		if( $code == 'CU' ) return 'Cuba';
		if( $code == 'CY' ) return 'Cyprus';
		if( $code == 'CZ' ) return 'Czech Republic';
		if( $code == 'DK' ) return 'Denmark';
		if( $code == 'DJ' ) return 'Djibouti';
		if( $code == 'DM' ) return 'Dominica';
		if( $code == 'DO' ) return 'Dominican Republic';
		if( $code == 'EC' ) return 'Ecuador';
		if( $code == 'EG' ) return 'Egypt';
		if( $code == 'SV' ) return 'El Salvador';
		if( $code == 'GQ' ) return 'Equatorial Guinea';
		if( $code == 'ER' ) return 'Eritrea';
		if( $code == 'EE' ) return 'Estonia';
		if( $code == 'ET' ) return 'Ethiopia';
		if( $code == 'FO' ) return 'Faroe Islands';
		if( $code == 'FK' ) return 'Falkland Islands (Malvinas)';
		if( $code == 'FJ' ) return 'Fiji the Fiji Islands';
		if( $code == 'FI' ) return 'Finland';
		if( $code == 'FR' ) return 'France, French Republic';
		if( $code == 'GF' ) return 'French Guiana';
		if( $code == 'PF' ) return 'French Polynesia';
		if( $code == 'TF' ) return 'French Southern Territories';
		if( $code == 'GA' ) return 'Gabon';
		if( $code == 'GM' ) return 'Gambia';
		if( $code == 'GE' ) return 'Georgia';
		if( $code == 'DE' ) return 'Germany';
		if( $code == 'GH' ) return 'Ghana';
		if( $code == 'GI' ) return 'Gibraltar';
		if( $code == 'GR' ) return 'Greece';
		if( $code == 'GL' ) return 'Greenland';
		if( $code == 'GD' ) return 'Grenada';
		if( $code == 'GP' ) return 'Guadeloupe';
		if( $code == 'GU' ) return 'Guam';
		if( $code == 'GT' ) return 'Guatemala';
		if( $code == 'GG' ) return 'Guernsey';
		if( $code == 'GN' ) return 'Guinea';
		if( $code == 'GW' ) return 'Guinea-Bissau';
		if( $code == 'GY' ) return 'Guyana';
		if( $code == 'HT' ) return 'Haiti';
		if( $code == 'HM' ) return 'Heard Island and McDonald Islands';
		if( $code == 'VA' ) return 'Holy See (Vatican City State)';
		if( $code == 'HN' ) return 'Honduras';
		if( $code == 'HK' ) return 'Hong Kong';
		if( $code == 'HU' ) return 'Hungary';
		if( $code == 'IS' ) return 'Iceland';
		if( $code == 'IN' ) return 'India';
		if( $code == 'ID' ) return 'Indonesia';
		if( $code == 'IR' ) return 'Iran';
		if( $code == 'IQ' ) return 'Iraq';
		if( $code == 'IE' ) return 'Ireland';
		if( $code == 'IM' ) return 'Isle of Man';
		if( $code == 'IL' ) return 'Israel';
		if( $code == 'IT' ) return 'Italy';
		if( $code == 'JM' ) return 'Jamaica';
		if( $code == 'JP' ) return 'Japan';
		if( $code == 'JE' ) return 'Jersey';
		if( $code == 'JO' ) return 'Jordan';
		if( $code == 'KZ' ) return 'Kazakhstan';
		if( $code == 'KE' ) return 'Kenya';
		if( $code == 'KI' ) return 'Kiribati';
		if( $code == 'KP' ) return 'Korea';
		if( $code == 'KR' ) return 'Korea';
		if( $code == 'KW' ) return 'Kuwait';
		if( $code == 'KG' ) return 'Kyrgyz Republic';
		if( $code == 'LA' ) return 'Lao';
		if( $code == 'LV' ) return 'Latvia';
		if( $code == 'LB' ) return 'Lebanon';
		if( $code == 'LS' ) return 'Lesotho';
		if( $code == 'LR' ) return 'Liberia';
		if( $code == 'LY' ) return 'Libyan Arab Jamahiriya';
		if( $code == 'LI' ) return 'Liechtenstein';
		if( $code == 'LT' ) return 'Lithuania';
		if( $code == 'LU' ) return 'Luxembourg';
		if( $code == 'MO' ) return 'Macao';
		if( $code == 'MK' ) return 'Macedonia';
		if( $code == 'MG' ) return 'Madagascar';
		if( $code == 'MW' ) return 'Malawi';
		if( $code == 'MY' ) return 'Malaysia';
		if( $code == 'MV' ) return 'Maldives';
		if( $code == 'ML' ) return 'Mali';
		if( $code == 'MT' ) return 'Malta';
		if( $code == 'MH' ) return 'Marshall Islands';
		if( $code == 'MQ' ) return 'Martinique';
		if( $code == 'MR' ) return 'Mauritania';
		if( $code == 'MU' ) return 'Mauritius';
		if( $code == 'YT' ) return 'Mayotte';
		if( $code == 'MX' ) return 'Mexico';
		if( $code == 'FM' ) return 'Micronesia';
		if( $code == 'MD' ) return 'Moldova';
		if( $code == 'MC' ) return 'Monaco';
		if( $code == 'MN' ) return 'Mongolia';
		if( $code == 'ME' ) return 'Montenegro';
		if( $code == 'MS' ) return 'Montserrat';
		if( $code == 'MA' ) return 'Morocco';
		if( $code == 'MZ' ) return 'Mozambique';
		if( $code == 'MM' ) return 'Myanmar';
		if( $code == 'NA' ) return 'Namibia';
		if( $code == 'NR' ) return 'Nauru';
		if( $code == 'NP' ) return 'Nepal';
		if( $code == 'AN' ) return 'Netherlands Antilles';
		if( $code == 'NL' ) return 'Netherlands';
		if( $code == 'NC' ) return 'New Caledonia';
		if( $code == 'NZ' ) return 'New Zealand';
		if( $code == 'NI' ) return 'Nicaragua';
		if( $code == 'NE' ) return 'Niger';
		if( $code == 'NG' ) return 'Nigeria';
		if( $code == 'NU' ) return 'Niue';
		if( $code == 'NF' ) return 'Norfolk Island';
		if( $code == 'MP' ) return 'Northern Mariana Islands';
		if( $code == 'NO' ) return 'Norway';
		if( $code == 'OM' ) return 'Oman';
		if( $code == 'PK' ) return 'Pakistan';
		if( $code == 'PW' ) return 'Palau';
		if( $code == 'PS' ) return 'Palestinian Territory';
		if( $code == 'PA' ) return 'Panama';
		if( $code == 'PG' ) return 'Papua New Guinea';
		if( $code == 'PY' ) return 'Paraguay';
		if( $code == 'PE' ) return 'Peru';
		if( $code == 'PH' ) return 'Philippines';
		if( $code == 'PN' ) return 'Pitcairn Islands';
		if( $code == 'PL' ) return 'Poland';
		if( $code == 'PT' ) return 'Portugal, Portuguese Republic';
		if( $code == 'PR' ) return 'Puerto Rico';
		if( $code == 'QA' ) return 'Qatar';
		if( $code == 'RE' ) return 'Reunion';
		if( $code == 'RO' ) return 'Romania';
		if( $code == 'RU' ) return 'Russian Federation';
		if( $code == 'RW' ) return 'Rwanda';
		if( $code == 'BL' ) return 'Saint Barthelemy';
		if( $code == 'SH' ) return 'Saint Helena';
		if( $code == 'KN' ) return 'Saint Kitts and Nevis';
		if( $code == 'LC' ) return 'Saint Lucia';
		if( $code == 'MF' ) return 'Saint Martin';
		if( $code == 'PM' ) return 'Saint Pierre and Miquelon';
		if( $code == 'VC' ) return 'Saint Vincent and the Grenadines';
		if( $code == 'WS' ) return 'Samoa';
		if( $code == 'SM' ) return 'San Marino';
		if( $code == 'ST' ) return 'Sao Tome and Principe';
		if( $code == 'SA' ) return 'Saudi Arabia';
		if( $code == 'SN' ) return 'Senegal';
		if( $code == 'RS' ) return 'Serbia';
		if( $code == 'SC' ) return 'Seychelles';
		if( $code == 'SL' ) return 'Sierra Leone';
		if( $code == 'SG' ) return 'Singapore';
		if( $code == 'SK' ) return 'Slovakia (Slovak Republic)';
		if( $code == 'SI' ) return 'Slovenia';
		if( $code == 'SB' ) return 'Solomon Islands';
		if( $code == 'SO' ) return 'Somalia, Somali Republic';
		if( $code == 'ZA' ) return 'South Africa';
		if( $code == 'GS' ) return 'South Georgia and the South Sandwich Islands';
		if( $code == 'ES' ) return 'Spain';
		if( $code == 'LK' ) return 'Sri Lanka';
		if( $code == 'SD' ) return 'Sudan';
		if( $code == 'SR' ) return 'Suriname';
		if( $code == 'SJ' ) return 'Svalbard & Jan Mayen Islands';
		if( $code == 'SZ' ) return 'Swaziland';
		if( $code == 'SE' ) return 'Sweden';
		if( $code == 'CH' ) return 'Switzerland, Swiss Confederation';
		if( $code == 'SY' ) return 'Syrian Arab Republic';
		if( $code == 'TW' ) return 'Taiwan';
		if( $code == 'TJ' ) return 'Tajikistan';
		if( $code == 'TZ' ) return 'Tanzania';
		if( $code == 'TH' ) return 'Thailand';
		if( $code == 'TL' ) return 'Timor-Leste';
		if( $code == 'TG' ) return 'Togo';
		if( $code == 'TK' ) return 'Tokelau';
		if( $code == 'TO' ) return 'Tonga';
		if( $code == 'TT' ) return 'Trinidad and Tobago';
		if( $code == 'TN' ) return 'Tunisia';
		if( $code == 'TR' ) return 'Turkey';
		if( $code == 'TM' ) return 'Turkmenistan';
		if( $code == 'TC' ) return 'Turks and Caicos Islands';
		if( $code == 'TV' ) return 'Tuvalu';
		if( $code == 'UG' ) return 'Uganda';
		if( $code == 'UA' ) return 'Ukraine';
		if( $code == 'AE' ) return 'United Arab Emirates';
		if( $code == 'GB' ) return 'United Kingdom';
		if( $code == 'US' ) return 'United States of America';
		if( $code == 'UM' ) return 'United States Minor Outlying Islands';
		if( $code == 'VI' ) return 'United States Virgin Islands';
		if( $code == 'UY' ) return 'Uruguay, Eastern Republic of';
		if( $code == 'UZ' ) return 'Uzbekistan';
		if( $code == 'VU' ) return 'Vanuatu';
		if( $code == 'VE' ) return 'Venezuela';
		if( $code == 'VN' ) return 'Vietnam';
		if( $code == 'WF' ) return 'Wallis and Futuna';
		if( $code == 'EH' ) return 'Western Sahara';
		if( $code == 'YE' ) return 'Yemen';
		if( $code == 'ZM' ) return 'Zambia';
		if( $code == 'ZW' ) return 'Zimbabwe';
		if( $code == 'BQ' ) return 'Bonaire, Sint Eustatius and Saba';
		if( $code == 'A1' ) return 'Anonymous Proxy';
		if( $code == 'A2' ) return 'Satellite Provider';
		if( $code == '00' ) return 'Unknown';
		if( $code == 'CW' ) return 'Curaçao';
		if( $code == 'EU' ) return 'Europe';
		if ($code == 'FX' ) return 'France, Metropolitan';
		return $code;
	}
	
	function google_portsearch($ip)
	{
		$data = get_db_tuple(get_db_rows("SELECT ports FROM google_proxyport where ip='".$ip."'"));
		if ($data)
			return $data['ports'];
			
		$params = array (
			'start'		=> 0,
			'num'		=> 20,
			'q'			=> 'proxy+'.$ip,
			'filter'	=> 0,
			'hl'		=> 'en',
			'ie'		=> 'utf-8',
			'oe'		=> 'utf-8'
		);

		$url = 'https://www.google.com/search?' . http_build_query($params);
		if (!$ch = curl_init($url))
			return false;
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($ch);
		curl_close($ch);
		if (preg_match_all('/.em.'.str_replace('.','\.', $ip).'..em.\:([0-9]+)/', $response, $matches))
		{
			$ports = implode(',', array_unique($matches[1]));
			get_db_rows("INSERT INTO google_proxyport (ip,ports,source) VALUES ('".$ip."','".$ports."','".MIRROR_NAME."')");
			return $ports;
		}
		
		return false;
	}
	
	function newFilter($ip, $type, $rpcid, $port=false)
	{
		$data = get_db_tuple(get_db_rows("SELECT id from blacklist where ip::inet='".$ip."'::inet AND type=".$type." AND uid_add=".$rpcid." AND listed=1".($port ? " AND port=".$port : "")." LIMIT 1"));
		return $data ? true : false;
	}
	
	function testEntry($ip, $type=false, $port=false)
	{
		if (!$ip) return false;
		$types = (!$type ? ['http', 'https', 'socks4', 'socks5','opendns'] : (!is_array($type) ? [$type] : $type));
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, 'http://89.18.174.160/ptest');
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		echo ' '.$ip.' '.$port;
		foreach($types AS $type)
		{
			echo ' '.$type.':';
			switch($type)
			{
				case 'http':
				case 'https':
				case 'socks4':
				case 'socks5':
					if (!$port) break;
					curl_setopt($ch, CURLOPT_PROXY, $type.'://'.$ip.':'.$port);
					$res = curl_exec($ch);
					if (curl_errno($ch))
					{
						echo ' ('.curl_errno($ch).'/'.curl_error($ch).')';
						switch(curl_errno($ch))
						{
							case 7:
							case 52:
							case 56:
								echo ' no longer active';
								curl_close($ch);
								return false;
							case 6:
							case 57:
								break;
							case 28:
								echo ' timed out';
								curl_close($ch);
								return true;
							default:
								echo ' curl error';
						}
					}
					if (trim($res) == 'GOTCHA')
					{
						echo ' active (GOTCHA)';
						curl_close($ch);
						return ['ip' => $ip, 'type' => $type, 'port' => $port];
					}
					else
						echo ' none ('.$res.')';
					break;
				case 'opendns':
					$test = exec('dig +short test.openresolver.com TXT @'.$ip);
					if ($test == '"open-resolver-detected"')
					{
						echo ' active';
						return ['ip' => $ip, 'type' => $type];
					}
			}
		}
		curl_close($ch);
		echo ' closed';
		return false;
	}
	
	function lapseTimer(&$start)
	{
		$dif = microtime(true) - $start;
		$start = microtime(true);
		return sprintf('%f', $dif);
	}
?>
