Back out r95396 and friends
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * File for BacklinkCache class
4 * @file
5 */
6
7 /**
8 * Class for fetching backlink lists, approximate backlink counts and
9 * partitions. This is a shared cache.
10 *
11 * Instances of this class should typically be fetched with the method
12 * $title->getBacklinkCache().
13 *
14 * Ideally you should only get your backlinks from here when you think
15 * there is some advantage in caching them. Otherwise it's just a waste
16 * of memory.
17 *
18 * Introduced by r47317
19 *
20 * @internal documentation reviewed on 18 Mar 2011 by hashar
21 *
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Ashar Voultoiz
26 */
27 class BacklinkCache {
28
29 /**
30 * Multi dimensions array representing batches. Keys are:
31 * > (string) links table name
32 * > 'numRows' : Number of rows for this link table
33 * > 'batches' : array( $start, $end )
34 *
35 * @see BacklinkCache::partitionResult()
36 *
37 * Cleared with BacklinkCache::clear()
38 */
39 protected $partitionCache = array();
40
41 /**
42 * Contains the whole links from a database result.
43 * This is raw data that will be partitioned in $partitionCache
44 *
45 * Initialized with BacklinkCache::getLinks()
46 * Cleared with BacklinkCache::clear()
47 */
48 protected $fullResultCache = array();
49
50 /**
51 * Local copy of a database object.
52 *
53 * Accessor: BacklinkCache::getDB()
54 * Mutator : BacklinkCache::setDB()
55 * Cleared with BacklinkCache::clear()
56 */
57 protected $db;
58
59 /**
60 * Local copy of a Title object
61 */
62 protected $title;
63
64 const CACHE_EXPIRY = 3600;
65
66 /**
67 * Create a new BacklinkCache
68 * @param Title $title : Title object to create a backlink cache for.
69 */
70 function __construct( $title ) {
71 $this->title = $title;
72 }
73
74 /**
75 * Serialization handler, diasallows to serialize the database to prevent
76 * failures after this class is deserialized from cache with dead DB
77 * connection.
78 *
79 * @return array
80 */
81 function __sleep() {
82 return array( 'partitionCache', 'fullResultCache', 'title' );
83 }
84
85 /**
86 * Clear locally stored data and database object.
87 */
88 public function clear() {
89 $this->partitionCache = array();
90 $this->fullResultCache = array();
91 unset( $this->db );
92 }
93
94 /**
95 * Set the Database object to use
96 *
97 * @param $db DatabaseBase
98 */
99 public function setDB( $db ) {
100 $this->db = $db;
101 }
102
103 /**
104 * Get the slave connection to the database
105 * When non existing, will initialize the connection.
106 * @return Database object
107 */
108 protected function getDB() {
109 if ( !isset( $this->db ) ) {
110 $this->db = wfGetDB( DB_SLAVE );
111 }
112
113 return $this->db;
114 }
115
116 /**
117 * Get the backlinks for a given table. Cached in process memory only.
118 * @param $table String
119 * @param $startId Integer or false
120 * @param $endId Integer or false
121 * @return TitleArrayFromResult
122 */
123 public function getLinks( $table, $startId = false, $endId = false ) {
124 wfProfileIn( __METHOD__ );
125
126 $fromField = $this->getPrefix( $table ) . '_from';
127
128 if ( $startId || $endId ) {
129 // Partial range, not cached
130 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
131 $conds = $this->getConditions( $table );
132
133 // Use the from field in the condition rather than the joined page_id,
134 // because databases are stupid and don't necessarily propagate indexes.
135 if ( $startId ) {
136 $conds[] = "$fromField >= " . intval( $startId );
137 }
138
139 if ( $endId ) {
140 $conds[] = "$fromField <= " . intval( $endId );
141 }
142
143 $res = $this->getDB()->select(
144 array( $table, 'page' ),
145 array( 'page_namespace', 'page_title', 'page_id' ),
146 $conds,
147 __METHOD__,
148 array(
149 'STRAIGHT_JOIN',
150 'ORDER BY' => $fromField
151 ) );
152 $ta = TitleArray::newFromResult( $res );
153
154 wfProfileOut( __METHOD__ );
155 return $ta;
156 }
157
158 // @todo FIXME: Make this a function?
159 if ( !isset( $this->fullResultCache[$table] ) ) {
160 wfDebug( __METHOD__ . ": from DB\n" );
161 $res = $this->getDB()->select(
162 array( $table, 'page' ),
163 array( 'page_namespace', 'page_title', 'page_id' ),
164 $this->getConditions( $table ),
165 __METHOD__,
166 array(
167 'STRAIGHT_JOIN',
168 'ORDER BY' => $fromField,
169 ) );
170 $this->fullResultCache[$table] = $res;
171 }
172
173 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
174
175 wfProfileOut( __METHOD__ );
176 return $ta;
177 }
178
179 /**
180 * Get the field name prefix for a given table
181 * @param $table String
182 */
183 protected function getPrefix( $table ) {
184 static $prefixes = array(
185 'pagelinks' => 'pl',
186 'imagelinks' => 'il',
187 'categorylinks' => 'cl',
188 'templatelinks' => 'tl',
189 'redirect' => 'rd',
190 );
191
192 if ( isset( $prefixes[$table] ) ) {
193 return $prefixes[$table];
194 } else {
195 $prefix = null;
196 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
197 if( $prefix ) {
198 return $prefix;
199 } else {
200 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
201 }
202 }
203 }
204
205 /**
206 * Get the SQL condition array for selecting backlinks, with a join
207 * on the page table.
208 * @param $table String
209 */
210 protected function getConditions( $table ) {
211 $prefix = $this->getPrefix( $table );
212
213 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
214 // they could be moved up for nicer case statements
215 switch ( $table ) {
216 case 'pagelinks':
217 case 'templatelinks':
218 $conds = array(
219 "{$prefix}_namespace" => $this->title->getNamespace(),
220 "{$prefix}_title" => $this->title->getDBkey(),
221 "page_id={$prefix}_from"
222 );
223 break;
224 case 'redirect':
225 $conds = array(
226 "{$prefix}_namespace" => $this->title->getNamespace(),
227 "{$prefix}_title" => $this->title->getDBkey(),
228 $this->getDb()->makeList( array(
229 "{$prefix}_interwiki = ''",
230 "{$prefix}_interwiki is null",
231 ), LIST_OR ),
232 "page_id={$prefix}_from"
233 );
234 break;
235 case 'imagelinks':
236 $conds = array(
237 'il_to' => $this->title->getDBkey(),
238 'page_id=il_from'
239 );
240 break;
241 case 'categorylinks':
242 $conds = array(
243 'cl_to' => $this->title->getDBkey(),
244 'page_id=cl_from',
245 );
246 break;
247 default:
248 $conds = null;
249 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
250 if( !$conds )
251 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
252 }
253
254 return $conds;
255 }
256
257 /**
258 * Get the approximate number of backlinks
259 * @param $table String
260 * @return integer
261 */
262 public function getNumLinks( $table ) {
263 if ( isset( $this->fullResultCache[$table] ) ) {
264 return $this->fullResultCache[$table]->numRows();
265 }
266
267 if ( isset( $this->partitionCache[$table] ) ) {
268 $entry = reset( $this->partitionCache[$table] );
269 return $entry['numRows'];
270 }
271
272 $titleArray = $this->getLinks( $table );
273
274 return $titleArray->count();
275 }
276
277 /**
278 * Partition the backlinks into batches.
279 * Returns an array giving the start and end of each range. The first
280 * batch has a start of false, and the last batch has an end of false.
281 *
282 * @param $table String: the links table name
283 * @param $batchSize Integer
284 * @return Array
285 */
286 public function partition( $table, $batchSize ) {
287
288 // 1) try partition cache ...
289
290 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
291 wfDebug( __METHOD__ . ": got from partition cache\n" );
292 return $this->partitionCache[$table][$batchSize]['batches'];
293 }
294
295 $this->partitionCache[$table][$batchSize] = false;
296 $cacheEntry =& $this->partitionCache[$table][$batchSize];
297
298 // 2) ... then try full result cache ...
299
300 if ( isset( $this->fullResultCache[$table] ) ) {
301 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
302 wfDebug( __METHOD__ . ": got from full result cache\n" );
303
304 return $cacheEntry['batches'];
305 }
306
307 // 3) ... fallback to memcached ...
308
309 global $wgMemc;
310
311 $memcKey = wfMemcKey(
312 'backlinks',
313 md5( $this->title->getPrefixedDBkey() ),
314 $table,
315 $batchSize
316 );
317
318 $memcValue = $wgMemc->get( $memcKey );
319
320 if ( is_array( $memcValue ) ) {
321 $cacheEntry = $memcValue;
322 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
323
324 return $cacheEntry['batches'];
325 }
326
327
328 // 4) ... finally fetch from the slow database :(
329
330 $this->getLinks( $table );
331 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
332 // Save to memcached
333 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
334
335 wfDebug( __METHOD__ . ": got from database\n" );
336 return $cacheEntry['batches'];
337 }
338
339 /**
340 * Partition a DB result with backlinks in it into batches
341 * @param $res ResultWrapper database result
342 * @param $batchSize integer
343 * @return array @see
344 */
345 protected function partitionResult( $res, $batchSize ) {
346 $batches = array();
347 $numRows = $res->numRows();
348 $numBatches = ceil( $numRows / $batchSize );
349
350 for ( $i = 0; $i < $numBatches; $i++ ) {
351 if ( $i == 0 ) {
352 $start = false;
353 } else {
354 $rowNum = intval( $numRows * $i / $numBatches );
355 $res->seek( $rowNum );
356 $row = $res->fetchObject();
357 $start = $row->page_id;
358 }
359
360 if ( $i == $numBatches - 1 ) {
361 $end = false;
362 } else {
363 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
364 $res->seek( $rowNum );
365 $row = $res->fetchObject();
366 $end = $row->page_id - 1;
367 }
368
369 # Sanity check order
370 if ( $start && $end && $start > $end ) {
371 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
372 }
373
374 $batches[] = array( $start, $end );
375 }
376
377 return array( 'numRows' => $numRows, 'batches' => $batches );
378 }
379 }