aboutsummaryrefslogtreecommitdiffstats
path: root/includes/BlockCache.php
blob: 8b49a0142c13d356ada07769f4e822def93bc94f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php

# Object for fast lookup of IP blocks
# Represents a memcached value, and in some sense, the entire ipblocks table

class BlockCache
{
	var $mData = false, $mMemcKey;

	function BlockCache( $deferLoad = false, $dbName = '' )
	{
		global $wgDBname;

		if ( $dbName == '' ) {
			$dbName = $wgDBname;
		}

		$this->mMemcKey = $dbName.':ipblocks';

		if ( !$deferLoad ) {
			$this->load();
		}
	}

	function load()
	{
		global $wgUseMemCached, $wgMemc;

		if ( $this->mData === false) {
			$saveMemc = false;
			# Try memcached
			if ( $wgUseMemCached ) {
				$this->mData = $wgMemc->get( $this->mMemcKey );
				if ( !$this->mData ) {
					$saveMemc = true;
				}
			}

			if ( !is_array( $this->mData ) ) {
				# Load from DB
				$this->mData = array();
				Block::enumBlocks( 'wfBlockCacheInsert', '' ); # Calls $this->insert()
			}
			
			if ( $saveMemc ) {
				$wgMemc->set( $this->mMemcKey, $this->mData, 0 );
			}
		}
	}

	function insert( &$block )
	{
		if ( $block->mUser == 0 ) {
			$nb = $block->getNetworkBits();
			$ipint = $block->getIntegerAddr();
			$index = $ipint >> ( 32 - $nb );

			if ( !array_key_exists( $nb, $this->mData ) ) {
				$this->mData[$nb] = array();
			}
		
			$this->mData[$nb][$index] = 1;
		}
	}
		
	function get( $ip )
	{
		$this->load();
		$ipint = ip2long( $ip );
		$blocked = false;

		foreach ( $this->mData as $networkBits => $blockInts ) {
			if ( array_key_exists( $ipint >> ( 32 - $networkBits ), $blockInts ) ) {
				$blocked = true;
				break;
			}
		}
		if ( $blocked ) {
			# Clear low order bits
			if ( $networkBits != 32 ) {
				$ip .= '/'.$networkBits;
				$ip = Block::normaliseRange( $ip );
			}
			$block = new Block();
			$block->load( $ip );
		} else {
			$block = false;
		}

		return $block;
	}

	function clear()
	{
		global $wgUseMemCached, $wgMemc;

		$this->mData = false;
		if ( $wgUseMemCached ) {
			$wgMemc->delete( $this->mMemcKey );
		}
	}

	function clearLocal()
	{
		$this->mData = false;
	}
}

function wfBlockCacheInsert( $block, $tag )
{
	global $wgBlockCache;
	$wgBlockCache->insert( $block );
}