API: Redo r62540 for all modules, easier than I first imagined
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * Class for fetching backlink lists, approximate backlink counts and partitions.
4 * Instances of this class should typically be fetched with $title->getBacklinkCache().
5 *
6 * Ideally you should only get your backlinks from here when you think there is some
7 * advantage in caching them. Otherwise it's just a waste of memory.
8 */
9 class BacklinkCache {
10 var $partitionCache = array();
11 var $fullResultCache = array();
12 var $title;
13 var $db;
14
15 const CACHE_EXPIRY = 3600;
16
17 /**
18 * Create a new BacklinkCache
19 */
20 function __construct( $title ) {
21 $this->title = $title;
22 }
23
24 /**
25 * Clear locally stored data
26 */
27 function clear() {
28 $this->partitionCache = array();
29 $this->fullResultCache = array();
30 unset( $this->db );
31 }
32
33 /**
34 * Set the Database object to use
35 */
36 public function setDB( $db ) {
37 $this->db = $db;
38 }
39
40 protected function getDB() {
41 if ( !isset( $this->db ) ) {
42 $this->db = wfGetDB( DB_SLAVE );
43 }
44 return $this->db;
45 }
46
47 /**
48 * Get the backlinks for a given table. Cached in process memory only.
49 * @param $table String
50 * @param $startId Integer or false
51 * @param $endId Integer or false
52 * @return TitleArray
53 */
54 public function getLinks( $table, $startId = false, $endId = false ) {
55 wfProfileIn( __METHOD__ );
56
57 $fromField = $this->getPrefix( $table ) . '_from';
58
59 if ( $startId || $endId ) {
60 // Partial range, not cached
61 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
62 $conds = $this->getConditions( $table );
63 // Use the from field in the condition rather than the joined page_id,
64 // because databases are stupid and don't necessarily propagate indexes.
65 if ( $startId ) {
66 $conds[] = "$fromField >= " . intval( $startId );
67 }
68 if ( $endId ) {
69 $conds[] = "$fromField <= " . intval( $endId );
70 }
71 $res = $this->getDB()->select(
72 array( $table, 'page' ),
73 array( 'page_namespace', 'page_title', 'page_id' ),
74 $conds,
75 __METHOD__,
76 array(
77 'STRAIGHT_JOIN',
78 'ORDER BY' => $fromField
79 ) );
80 $ta = TitleArray::newFromResult( $res );
81 wfProfileOut( __METHOD__ );
82 return $ta;
83 }
84
85 if ( !isset( $this->fullResultCache[$table] ) ) {
86 wfDebug( __METHOD__ . ": from DB\n" );
87 $res = $this->getDB()->select(
88 array( $table, 'page' ),
89 array( 'page_namespace', 'page_title', 'page_id' ),
90 $this->getConditions( $table ),
91 __METHOD__,
92 array(
93 'STRAIGHT_JOIN',
94 'ORDER BY' => $fromField,
95 ) );
96 $this->fullResultCache[$table] = $res;
97 }
98 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
99 wfProfileOut( __METHOD__ );
100 return $ta;
101 }
102
103 /**
104 * Get the field name prefix for a given table
105 */
106 protected function getPrefix( $table ) {
107 static $prefixes = array(
108 'pagelinks' => 'pl',
109 'imagelinks' => 'il',
110 'categorylinks' => 'cl',
111 'templatelinks' => 'tl',
112 'redirect' => 'rd',
113 );
114
115 if ( isset( $prefixes[$table] ) ) {
116 return $prefixes[$table];
117 } else {
118 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
119 }
120 }
121
122 /**
123 * Get the SQL condition array for selecting backlinks, with a join on the page table
124 */
125 protected function getConditions( $table ) {
126 $prefix = $this->getPrefix( $table );
127
128 switch ( $table ) {
129 case 'pagelinks':
130 case 'templatelinks':
131 case 'redirect':
132 $conds = array(
133 "{$prefix}_namespace" => $this->title->getNamespace(),
134 "{$prefix}_title" => $this->title->getDBkey(),
135 "page_id={$prefix}_from"
136 );
137 break;
138 case 'imagelinks':
139 $conds = array(
140 'il_to' => $this->title->getDBkey(),
141 'page_id=il_from'
142 );
143 break;
144 case 'categorylinks':
145 $conds = array(
146 'cl_to' => $this->title->getDBkey(),
147 'page_id=cl_from',
148 );
149 break;
150 default:
151 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
152 }
153 return $conds;
154 }
155
156 /**
157 * Get the approximate number of backlinks
158 */
159 public function getNumLinks( $table ) {
160 if ( isset( $this->fullResultCache[$table] ) ) {
161 return $this->fullResultCache[$table]->numRows();
162 }
163
164 if ( isset( $this->partitionCache[$table] ) ) {
165 $entry = reset( $this->partitionCache[$table] );
166 return $entry['numRows'];
167 }
168
169 $titleArray = $this->getLinks( $table );
170 return $titleArray->count();
171 }
172
173 /**
174 * Partition the backlinks into batches.
175 * Returns an array giving the start and end of each range. The first batch has
176 * a start of false, and the last batch has an end of false.
177 *
178 * @param $table String: the links table name
179 * @param $batchSize Integer
180 * @return Array
181 */
182 public function partition( $table, $batchSize ) {
183 // Try cache
184 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
185 wfDebug( __METHOD__ . ": got from partition cache\n" );
186 return $this->partitionCache[$table][$batchSize]['batches'];
187 }
188
189 $this->partitionCache[$table][$batchSize] = false;
190 $cacheEntry =& $this->partitionCache[$table][$batchSize];
191
192 // Try full result cache
193 if ( isset( $this->fullResultCache[$table] ) ) {
194 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
195 wfDebug( __METHOD__ . ": got from full result cache\n" );
196 return $cacheEntry['batches'];
197 }
198
199 // Try memcached
200 global $wgMemc;
201 $memcKey = wfMemcKey(
202 'backlinks',
203 md5( $this->title->getPrefixedDBkey() ),
204 $table,
205 $batchSize
206 );
207 $memcValue = $wgMemc->get( $memcKey );
208
209 if ( is_array( $memcValue ) ) {
210 $cacheEntry = $memcValue;
211 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
212 return $cacheEntry['batches'];
213 }
214 // Fetch from database
215 $this->getLinks( $table );
216 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
217 // Save to memcached
218 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
219 wfDebug( __METHOD__ . ": got from database\n" );
220 return $cacheEntry['batches'];
221 }
222
223 /**
224 * Partition a DB result with backlinks in it into batches
225 */
226 protected function partitionResult( $res, $batchSize ) {
227 $batches = array();
228 $numRows = $res->numRows();
229 $numBatches = ceil( $numRows / $batchSize );
230
231 for ( $i = 0; $i < $numBatches; $i++ ) {
232 if ( $i == 0 ) {
233 $start = false;
234 } else {
235 $rowNum = intval( $numRows * $i / $numBatches );
236 $res->seek( $rowNum );
237 $row = $res->fetchObject();
238 $start = $row->page_id;
239 }
240
241 if ( $i == $numBatches - 1 ) {
242 $end = false;
243 } else {
244 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
245 $res->seek( $rowNum );
246 $row = $res->fetchObject();
247 $end = $row->page_id - 1;
248 }
249
250 # Sanity check order
251 if ( $start && $end && $start > $end ) {
252 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
253 }
254
255 $batches[] = array( $start, $end );
256 }
257 return array( 'numRows' => $numRows, 'batches' => $batches );
258 }
259 }