本文整理汇总了PHP中IP::isIPv4方法的典型用法代码示例。如果您正苦于以下问题:PHP IP::isIPv4方法的具体用法?PHP IP::isIPv4怎么用?PHP IP::isIPv4使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IP
的用法示例。
在下文中一共展示了IP::isIPv4方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Construct an IP address representation.
* @param string $address The textual representation of an IP address or CIDR range.
*/
public function __construct($address)
{
// analyze address format
$this->is_valid = IP::isIPAddress($address);
if (!$this->is_valid) {
return;
}
$this->is_ipv4 = IP::isIPv4($address);
$this->is_ipv6 = !$this->is_ipv4 && IP::isIPv6($address);
// analyze address range
$this->is_range = IP::isValidBlock($address);
$this->encoded_range = IP::parseRange($address);
$this->range = array(IP::prettifyIP(IP::formatHex($this->encoded_range[self::START])), IP::prettifyIP(IP::formatHex($this->encoded_range[self::END])));
}
示例2: fnGetGeoIP
function fnGetGeoIP($ip_address = null)
{
if (!isset($ip_address)) {
$ip_address = IP::sanitizeIP(wfGetIP());
}
if (isset($_GET['ip'])) {
$ip_address = IP::sanitizeIP($_GET['ip']);
}
if (!IP::isIPv4($ip_address)) {
throw new UnsupportedGeoIP('Only IPv4 addresses are supported.');
}
$dbr = wfGetDB(DB_SLAVE);
$long_ip = IP::toUnsigned($ip_address);
$conditions = array('begin_ip_long <= ' . $long_ip, $long_ip . ' <= end_ip_long');
$country_code = $dbr->selectField('geoip', 'country_code', $conditions, __METHOD__);
if (!$country_code) {
throw new NotFoundGeoIP('Could not identify the country for the provided IP address.');
}
return $country_code;
}
示例3: newFromString
/**
* @param string $info In the format of "udp://host:port/prefix"
* @return UDPTransport
* @throws InvalidArgumentException
*/
public static function newFromString($info)
{
if (preg_match('!^udp:(?://)?\\[([0-9a-fA-F:]+)\\]:(\\d+)(?:/(.*))?$!', $info, $m)) {
// IPv6 bracketed host
$host = $m[1];
$port = intval($m[2]);
$prefix = isset($m[3]) ? $m[3] : false;
$domain = AF_INET6;
} elseif (preg_match('!^udp:(?://)?([a-zA-Z0-9.-]+):(\\d+)(?:/(.*))?$!', $info, $m)) {
$host = $m[1];
if (!IP::isIPv4($host)) {
$host = gethostbyname($host);
}
$port = intval($m[2]);
$prefix = isset($m[3]) ? $m[3] : false;
$domain = AF_INET;
} else {
throw new InvalidArgumentException(__METHOD__ . ': Invalid UDP specification');
}
return new self($host, $port, $domain, $prefix);
}
示例4: inDnsBlacklist
/**
* Whether the given IP is in a given DNS blacklist.
*
* @param $ip String IP to check
* @param $bases String|Array of Strings: URL of the DNS blacklist
* @return Bool True if blacklisted.
*/
public function inDnsBlacklist($ip, $bases)
{
wfProfileIn(__METHOD__);
$found = false;
// @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
if (IP::isIPv4($ip)) {
# Reverse IP, bug 21255
$ipReversed = implode('.', array_reverse(explode('.', $ip)));
foreach ((array) $bases as $base) {
# Make hostname
$host = "{$ipReversed}.{$base}";
# Send query
$ipList = gethostbynamel($host);
if ($ipList) {
wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n");
$found = true;
break;
} else {
wfDebug("Requested {$host}, not found in {$base}.\n");
}
}
}
wfProfileOut(__METHOD__);
return $found;
}
示例5: doBlock
/**
* Backend block code.
* $userID and $expiry will be filled accordingly
* @return array(message key, arguments) on failure, empty array on success
*/
function doBlock(&$userId = null, &$expiry = null)
{
global $wgUser, $wgSysopUserBans, $wgSysopRangeBans, $wgBlockAllowsUTEdit, $wgBlockCIDRLimit;
$userId = 0;
# Expand valid IPv6 addresses, usernames are left as is
$this->BlockAddress = IP::sanitizeIP($this->BlockAddress);
# isIPv4() and IPv6() are used for final validation
$rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}';
$rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}';
$rxIP = "({$rxIP4}|{$rxIP6})";
# Check for invalid specifications
if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) {
$matches = array();
if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) {
# IPv4
if ($wgSysopRangeBans) {
if (!IP::isIPv4($this->BlockAddress) || $matches[2] > 32) {
return array('ip_range_invalid');
} elseif ($matches[2] < $wgBlockCIDRLimit['IPv4']) {
return array('ip_range_toolarge', $wgBlockCIDRLimit['IPv4']);
}
$this->BlockAddress = Block::normaliseRange($this->BlockAddress);
} else {
# Range block illegal
return array('range_block_disabled');
}
} elseif (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) {
# IPv6
if ($wgSysopRangeBans) {
if (!IP::isIPv6($this->BlockAddress) || $matches[2] > 128) {
return array('ip_range_invalid');
} elseif ($matches[2] < $wgBlockCIDRLimit['IPv6']) {
return array('ip_range_toolarge', $wgBlockCIDRLimit['IPv6']);
}
$this->BlockAddress = Block::normaliseRange($this->BlockAddress);
} else {
# Range block illegal
return array('range_block_disabled');
}
} else {
# Username block
if ($wgSysopUserBans) {
$user = User::newFromName($this->BlockAddress);
if (!is_null($user) && $user->getId()) {
# Use canonical name
$userId = $user->getId();
$this->BlockAddress = $user->getName();
} else {
return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress));
}
} else {
return array('badipaddress');
}
}
}
if ($wgUser->isBlocked() && $wgUser->getId() !== $userId) {
return array('cant-block-while-blocked');
}
$reasonstr = $this->BlockReasonList;
if ($reasonstr != 'other' && $this->BlockReason != '') {
// Entry from drop down menu + additional comment
$reasonstr .= wfMsgForContent('colon-separator') . $this->BlockReason;
} elseif ($reasonstr == 'other') {
$reasonstr = $this->BlockReason;
}
$expirestr = $this->BlockExpiry;
if ($expirestr == 'other') {
$expirestr = $this->BlockOther;
}
if (strlen($expirestr) == 0 || strlen($expirestr) > 50) {
return array('ipb_expiry_invalid');
}
if (false === ($expiry = Block::parseExpiryInput($expirestr))) {
// Bad expiry.
return array('ipb_expiry_invalid');
}
if ($this->BlockHideName) {
// Recheck params here...
if (!$userId || !$wgUser->isAllowed('hideuser')) {
$this->BlockHideName = false;
// IP users should not be hidden
} elseif ($expiry !== 'infinity') {
// Bad expiry.
return array('ipb_expiry_temp');
} elseif (User::edits($userId) > self::HIDEUSER_CONTRIBLIMIT) {
// Typically, the user should have a handful of edits.
// Disallow hiding users with many edits for performance.
return array('ipb_hide_invalid');
}
}
# Create block object
# Note: for a user block, ipb_address is only for display purposes
$block = new Block($this->BlockAddress, $userId, $wgUser->getId(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail, isset($this->BlockAllowUsertalk) ? $this->BlockAllowUsertalk : $wgBlockAllowsUTEdit);
# Should this be privately logged?
$suppressLog = (bool) $this->BlockHideName;
//.........这里部分代码省略.........
示例6: inDnsBlacklist
/**
* Whether the given IP is in a given DNS blacklist.
*
* @param string $ip IP to check
* @param string|array $bases Array of Strings: URL of the DNS blacklist
* @return bool True if blacklisted.
*/
public function inDnsBlacklist($ip, $bases)
{
$found = false;
// @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
if (IP::isIPv4($ip)) {
// Reverse IP, bug 21255
$ipReversed = implode('.', array_reverse(explode('.', $ip)));
foreach ((array) $bases as $base) {
// Make hostname
// If we have an access key, use that too (ProjectHoneypot, etc.)
$basename = $base;
if (is_array($base)) {
if (count($base) >= 2) {
// Access key is 1, base URL is 0
$host = "{$base[1]}.{$ipReversed}.{$base[0]}";
} else {
$host = "{$ipReversed}.{$base[0]}";
}
$basename = $base[0];
} else {
$host = "{$ipReversed}.{$base}";
}
// Send query
$ipList = gethostbynamel($host);
if ($ipList) {
wfDebugLog('dnsblacklist', "Hostname {$host} is {$ipList[0]}, it's a proxy says {$basename}!");
$found = true;
break;
} else {
wfDebugLog('dnsblacklist', "Requested {$host}, not found in {$basename}.");
}
}
}
return $found;
}
示例7: wfErrorLog
/**
* Log to a file without getting "file size exceeded" signals.
*
* Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
* send lines to the specified port, prefixed by the specified prefix and a space.
*
* @param string $text
* @param string $file Filename
* @throws MWException
*/
function wfErrorLog($text, $file)
{
if (substr($file, 0, 4) == 'udp:') {
# Needs the sockets extension
if (preg_match('!^(tcp|udp):(?://)?\\[([0-9a-fA-F:]+)\\]:(\\d+)(?:/(.*))?$!', $file, $m)) {
// IPv6 bracketed host
$host = $m[2];
$port = intval($m[3]);
$prefix = isset($m[4]) ? $m[4] : false;
$domain = AF_INET6;
} elseif (preg_match('!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\\d+)(?:/(.*))?$!', $file, $m)) {
$host = $m[2];
if (!IP::isIPv4($host)) {
$host = gethostbyname($host);
}
$port = intval($m[3]);
$prefix = isset($m[4]) ? $m[4] : false;
$domain = AF_INET;
} else {
throw new MWException(__METHOD__ . ': Invalid UDP specification');
}
// Clean it up for the multiplexer
if (strval($prefix) !== '') {
$text = preg_replace('/^/m', $prefix . ' ', $text);
// Limit to 64KB
if (strlen($text) > 65506) {
$text = substr($text, 0, 65506);
}
if (substr($text, -1) != "\n") {
$text .= "\n";
}
} elseif (strlen($text) > 65507) {
$text = substr($text, 0, 65507);
}
$sock = socket_create($domain, SOCK_DGRAM, SOL_UDP);
if (!$sock) {
return;
}
socket_sendto($sock, $text, strlen($text), 0, $host, $port);
socket_close($sock);
} else {
wfSuppressWarnings();
$exists = file_exists($file);
$size = $exists ? filesize($file) : false;
if (!$exists || $size !== false && $size + strlen($text) < 0x7fffffff) {
file_put_contents($file, $text, FILE_APPEND);
}
wfRestoreWarnings();
}
}
示例8: inDnsBlacklist
/**
* Whether the given IP is in a given DNS blacklist.
*
* @param $ip String IP to check
* @param $bases String|Array of Strings: URL of the DNS blacklist
* @return Bool True if blacklisted.
*/
public function inDnsBlacklist($ip, $bases)
{
wfProfileIn(__METHOD__);
$found = false;
// @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
if (IP::isIPv4($ip)) {
# Reverse IP, bug 21255
$ipReversed = implode('.', array_reverse(explode('.', $ip)));
foreach ((array) $bases as $base) {
# Make hostname
# If we have an access key, use that too (ProjectHoneypot, etc.)
if (is_array($base)) {
if (count($base) >= 2) {
# Access key is 1, base URL is 0
$host = "{$base[1]}.{$ipReversed}.{$base[0]}";
} else {
$host = "{$ipReversed}.{$base[0]}";
}
} else {
$host = "{$ipReversed}.{$base}";
}
# Send query
$ipList = gethostbynamel($host);
if ($ipList) {
wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n");
$found = true;
break;
} else {
wfDebug("Requested {$host}, not found in {$base}.\n");
}
}
}
wfProfileOut(__METHOD__);
return $found;
}
示例9: execute
public function execute()
{
global $wgContLang;
$db = $this->getDB();
$params = $this->extractRequestParams();
$this->requireMaxOneParameter($params, 'users', 'ip');
$prop = array_flip($params['prop']);
$fld_id = isset($prop['id']);
$fld_user = isset($prop['user']);
$fld_userid = isset($prop['userid']);
$fld_by = isset($prop['by']);
$fld_byid = isset($prop['byid']);
$fld_timestamp = isset($prop['timestamp']);
$fld_expiry = isset($prop['expiry']);
$fld_reason = isset($prop['reason']);
$fld_range = isset($prop['range']);
$fld_flags = isset($prop['flags']);
$result = $this->getResult();
$this->addTables('ipblocks');
$this->addFields(array('ipb_auto', 'ipb_id', 'ipb_timestamp'));
$this->addFieldsIf(array('ipb_address', 'ipb_user'), $fld_user || $fld_userid);
$this->addFieldsIf('ipb_by_text', $fld_by);
$this->addFieldsIf('ipb_by', $fld_byid);
$this->addFieldsIf('ipb_expiry', $fld_expiry);
$this->addFieldsIf('ipb_reason', $fld_reason);
$this->addFieldsIf(array('ipb_range_start', 'ipb_range_end'), $fld_range);
$this->addFieldsIf(array('ipb_anon_only', 'ipb_create_account', 'ipb_enable_autoblock', 'ipb_block_email', 'ipb_deleted', 'ipb_allow_usertalk'), $fld_flags);
$this->addOption('LIMIT', $params['limit'] + 1);
$this->addTimestampWhereRange('ipb_timestamp', $params['dir'], $params['start'], $params['end']);
// Include in ORDER BY for uniqueness
$this->addWhereRange('ipb_id', $params['dir'], null, null);
if (!is_null($params['continue'])) {
$cont = explode('|', $params['continue']);
$this->dieContinueUsageIf(count($cont) != 2);
$op = $params['dir'] == 'newer' ? '>' : '<';
$continueTimestamp = $db->addQuotes($db->timestamp($cont[0]));
$continueId = (int) $cont[1];
$this->dieContinueUsageIf($continueId != $cont[1]);
$this->addWhere("ipb_timestamp {$op} {$continueTimestamp} OR " . "(ipb_timestamp = {$continueTimestamp} AND " . "ipb_id {$op}= {$continueId})");
}
if (isset($params['ids'])) {
$this->addWhereFld('ipb_id', $params['ids']);
}
if (isset($params['users'])) {
$usernames = array();
foreach ((array) $params['users'] as $u) {
$usernames[] = $this->prepareUsername($u);
}
$this->addWhereFld('ipb_address', $usernames);
$this->addWhereFld('ipb_auto', 0);
}
if (isset($params['ip'])) {
$blockCIDRLimit = $this->getConfig()->get('BlockCIDRLimit');
if (IP::isIPv4($params['ip'])) {
$type = 'IPv4';
$cidrLimit = $blockCIDRLimit['IPv4'];
$prefixLen = 0;
} elseif (IP::isIPv6($params['ip'])) {
$type = 'IPv6';
$cidrLimit = $blockCIDRLimit['IPv6'];
$prefixLen = 3;
// IP::toHex output is prefixed with "v6-"
} else {
$this->dieUsage('IP parameter is not valid', 'param_ip');
}
# Check range validity, if it's a CIDR
list($ip, $range) = IP::parseCIDR($params['ip']);
if ($ip !== false && $range !== false && $range < $cidrLimit) {
$this->dieUsage("{$type} CIDR ranges broader than /{$cidrLimit} are not accepted", 'cidrtoobroad');
}
# Let IP::parseRange handle calculating $upper, instead of duplicating the logic here.
list($lower, $upper) = IP::parseRange($params['ip']);
# Extract the common prefix to any rangeblock affecting this IP/CIDR
$prefix = substr($lower, 0, $prefixLen + floor($cidrLimit / 4));
# Fairly hard to make a malicious SQL statement out of hex characters,
# but it is good practice to add quotes
$lower = $db->addQuotes($lower);
$upper = $db->addQuotes($upper);
$this->addWhere(array('ipb_range_start' . $db->buildLike($prefix, $db->anyString()), 'ipb_range_start <= ' . $lower, 'ipb_range_end >= ' . $upper, 'ipb_auto' => 0));
}
if (!is_null($params['show'])) {
$show = array_flip($params['show']);
/* Check for conflicting parameters. */
if (isset($show['account']) && isset($show['!account']) || isset($show['ip']) && isset($show['!ip']) || isset($show['range']) && isset($show['!range']) || isset($show['temp']) && isset($show['!temp'])) {
$this->dieUsageMsg('show');
}
$this->addWhereIf('ipb_user = 0', isset($show['!account']));
$this->addWhereIf('ipb_user != 0', isset($show['account']));
$this->addWhereIf('ipb_user != 0 OR ipb_range_end > ipb_range_start', isset($show['!ip']));
$this->addWhereIf('ipb_user = 0 AND ipb_range_end = ipb_range_start', isset($show['ip']));
$this->addWhereIf('ipb_expiry = ' . $db->addQuotes($db->getInfinity()), isset($show['!temp']));
$this->addWhereIf('ipb_expiry != ' . $db->addQuotes($db->getInfinity()), isset($show['temp']));
$this->addWhereIf('ipb_range_end = ipb_range_start', isset($show['!range']));
$this->addWhereIf('ipb_range_end > ipb_range_start', isset($show['range']));
}
if (!$this->getUser()->isAllowed('hideuser')) {
$this->addWhereFld('ipb_deleted', 0);
}
// Purge expired entries on one in every 10 queries
if (!mt_rand(0, 10)) {
//.........这里部分代码省略.........
示例10: inDnsBlacklist
/**
* Whether the given IP is in a given DNS blacklist.
*
* @param $ip \string IP to check
* @param $base \string URL of the DNS blacklist
* @return \bool True if blacklisted.
*/
function inDnsBlacklist($ip, $base)
{
wfProfileIn(__METHOD__);
$found = false;
$host = '';
// FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
if (IP::isIPv4($ip)) {
# Make hostname
$host = "{$ip}.{$base}";
# Send query
$ipList = gethostbynamel($host);
if ($ipList) {
wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n");
$found = true;
} else {
wfDebug("Requested {$host}, not found in {$base}.\n");
}
}
wfProfileOut(__METHOD__);
return $found;
}
示例11: normaliseRange
/**
* Gets rid of uneeded numbers in quad-dotted/octet IP strings
* For example, 127.111.113.151/24 -> 127.111.113.0/24
*/
static function normaliseRange($range)
{
$parts = explode('/', $range);
if (count($parts) == 2) {
// IPv6
if (IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128) {
$bits = $parts[1];
$ipint = IP::toUnsigned6($parts[0]);
# Native 32 bit functions WONT work here!!!
# Convert to a padded binary number
$network = wfBaseConvert($ipint, 10, 2, 128);
# Truncate the last (128-$bits) bits and replace them with zeros
$network = str_pad(substr($network, 0, $bits), 128, 0, STR_PAD_RIGHT);
# Convert back to an integer
$network = wfBaseConvert($network, 2, 10);
# Reform octet address
$newip = IP::toOctet($network);
$range = "{$newip}/{$parts[1]}";
} else {
if (IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32) {
$shift = 32 - $parts[1];
$ipint = IP::toUnsigned($parts[0]);
$ipint = $ipint >> $shift << $shift;
$newip = long2ip($ipint);
$range = "{$newip}/{$parts[1]}";
}
}
}
return $range;
}
示例12: GetGoogleWebsitesList
function GetGoogleWebsitesList($g)
{
$sock = new sockets();
$DisableGoogleSSL = $sock->GET_INFO("DisableGoogleSSL");
if (!is_numeric($DisableGoogleSSL)) {
$DisableGoogleSSL = 0;
}
if ($DisableGoogleSSL == 0) {
if ($GLOBALS["OUTPUT"]) {
echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Goolge SSL is allowed\n";
}
return $g;
}
$q = new mysql_squid_builder();
$arrayDN = $q->GetFamilySitestt(null, true);
while (list($table, $fff) = each($arrayDN)) {
if (preg_match("#\\.(gov|gouv|gor|org|net|web|ac)\\.#", "google.{$table}")) {
continue;
}
$array[] = "www.google.{$table}";
$array[] = "google.{$table}";
}
$ipaddr = gethostbyname("nosslsearch.google.com");
$ip = new IP();
$unix = new unix();
$php5 = $unix->LOCATE_PHP5_BIN();
$OK = true;
if (!$ip->isIPv4($ipaddr)) {
$OK = false;
}
if (!$OK) {
if ($ip->isIPv6($ipaddr)) {
$OK = true;
}
}
if (!$OK) {
if ($GLOBALS["OUTPUT"]) {
echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]}, Unable to resolve nosslsearch.google.com\n";
}
return $g;
}
while (list($a, $googlesite) = each($array)) {
$g[] = "--address=/{$googlesite}/{$ipaddr}";
$g[] = "--cname={$googlesite},nosslsearch.google.com";
}
return $g;
}
示例13: ipv4_add
function ipv4_add()
{
$ip = new IP();
if (!$ip->isIPv4($_POST["RemoteAddAddr"])) {
echo "No an IPv4 address...\n";
return;
}
$sock = new sockets();
$datas = explode("\n", $sock->GET_INFO("PowerDNSListenAddr"));
while (list($index, $ipmask) = each($datas)) {
$array[$ipmask] = $ipmask;
}
$array[$_POST["RemoteAddAddr"]] = $_POST["RemoteAddAddr"];
while (list($index, $ipmask) = each($array)) {
$f[] = $ipmask;
}
$sock->SaveConfigFile(@implode("\n", $f), "PowerDNSListenAddr");
$sock->getFrameWork("cmd.php?pdns-restart=yes");
}
示例14: dump
function dump()
{
$ipaddr = gethostbyname("nosslsearch.google.com");
$ip = new IP();
$OK = true;
if (!$ip->isIPv4($ipaddr)) {
$OK = false;
}
if (!$OK) {
if ($ip->isIPv6($ipaddr)) {
$OK = true;
}
}
if (!$OK) {
echo "Failed nosslsearch.google.com `{$ipaddr}` not an IP address...!!!\n";
return;
}
$array = GetWebsitesList();
if (count($array) == 0) {
echo "Failed!!! -> GetWebsitesList();\n";
return;
}
while (list($table, $fff) = each($array)) {
echo "{$fff}\t{$ipaddr}\n";
}
}
示例15: doBlock
/**
* Backend block code.
* $userID and $expiry will be filled accordingly
* @return array(message key, arguments) on failure, empty array on success
*/
function doBlock(&$userId = null, &$expiry = null)
{
global $wgUser, $wgSysopUserBans, $wgSysopRangeBans, $wgBlockAllowsUTEdit;
$userId = 0;
# Expand valid IPv6 addresses, usernames are left as is
$this->BlockAddress = IP::sanitizeIP($this->BlockAddress);
# isIPv4() and IPv6() are used for final validation
$rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}';
$rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}';
$rxIP = "({$rxIP4}|{$rxIP6})";
# Check for invalid specifications
if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) {
$matches = array();
if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) {
# IPv4
if ($wgSysopRangeBans) {
if (!IP::isIPv4($this->BlockAddress) || $matches[2] < 16 || $matches[2] > 32) {
return array('ip_range_invalid');
}
$this->BlockAddress = Block::normaliseRange($this->BlockAddress);
} else {
# Range block illegal
return array('range_block_disabled');
}
} else {
if (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) {
# IPv6
if ($wgSysopRangeBans) {
if (!IP::isIPv6($this->BlockAddress) || $matches[2] < 64 || $matches[2] > 128) {
return array('ip_range_invalid');
}
$this->BlockAddress = Block::normaliseRange($this->BlockAddress);
} else {
# Range block illegal
return array('range_block_disabled');
}
} else {
# Username block
if ($wgSysopUserBans) {
$user = User::newFromName($this->BlockAddress);
if (!is_null($user) && $user->getId()) {
# Use canonical name
$userId = $user->getId();
$this->BlockAddress = $user->getName();
} else {
return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress));
}
} else {
return array('badipaddress');
}
}
}
}
if ($wgUser->isBlocked() && $wgUser->getId() !== $userId) {
return array('cant-block-while-blocked');
}
$reasonstr = $this->BlockReasonList;
if ($reasonstr != 'other' && $this->BlockReason != '') {
// Entry from drop down menu + additional comment
$reasonstr .= ': ' . $this->BlockReason;
} elseif ($reasonstr == 'other') {
$reasonstr = $this->BlockReason;
}
$expirestr = $this->BlockExpiry;
if ($expirestr == 'other') {
$expirestr = $this->BlockOther;
}
if (strlen($expirestr) == 0 || strlen($expirestr) > 50) {
return array('ipb_expiry_invalid');
}
if (false === ($expiry = Block::parseExpiryInput($expirestr))) {
// Bad expiry.
return array('ipb_expiry_invalid');
}
if ($this->BlockHideName && $expiry != 'infinity') {
// Bad expiry.
return array('ipb_expiry_temp');
}
# Create block
# Note: for a user block, ipb_address is only for display purposes
$block = new Block($this->BlockAddress, $userId, $wgUser->getId(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail, isset($this->BlockAllowUsertalk) ? $this->BlockAllowUsertalk : $wgBlockAllowsUTEdit);
if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) {
if (!$block->insert()) {
if (!$this->BlockReblock) {
return array('ipb_already_blocked');
} else {
# This returns direct blocks before autoblocks/rangeblocks, since we should
# be sure the user is blocked by now it should work for our purposes
$currentBlock = Block::newFromDB($this->BlockAddress, $userId);
if ($block->equals($currentBlock)) {
return array('ipb_already_blocked');
}
$currentBlock->delete();
$block->insert();
$log_action = 'reblock';
//.........这里部分代码省略.........