Merge "Use interwiki cache directly to resolve transwiki import sources"
[lhc/web/wiklou.git] / includes / cache / BacklinkCache.php
1 <?php
2 /**
3 * Class for fetching backlink lists, approximate backlink counts and
4 * partitions.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @author Tim Starling
23 * @author Aaron Schulz
24 * @copyright © 2009, Tim Starling, Domas Mituzas
25 * @copyright © 2010, Max Sem
26 * @copyright © 2011, Antoine Musso
27 */
28
29 /**
30 * Class for fetching backlink lists, approximate backlink counts and
31 * partitions. This is a shared cache.
32 *
33 * Instances of this class should typically be fetched with the method
34 * $title->getBacklinkCache().
35 *
36 * Ideally you should only get your backlinks from here when you think
37 * there is some advantage in caching them. Otherwise it's just a waste
38 * of memory.
39 *
40 * Introduced by r47317
41 */
42 class BacklinkCache {
43 /** @var ProcessCacheLRU */
44 protected static $cache;
45
46 /**
47 * Multi dimensions array representing batches. Keys are:
48 * > (string) links table name
49 * > (int) batch size
50 * > 'numRows' : Number of rows for this link table
51 * > 'batches' : array( $start, $end )
52 *
53 * @see BacklinkCache::partitionResult()
54 *
55 * Cleared with BacklinkCache::clear()
56 * @var array[]
57 */
58 protected $partitionCache = array();
59
60 /**
61 * Contains the whole links from a database result.
62 * This is raw data that will be partitioned in $partitionCache
63 *
64 * Initialized with BacklinkCache::getLinks()
65 * Cleared with BacklinkCache::clear()
66 * @var ResultWrapper[]
67 */
68 protected $fullResultCache = array();
69
70 /**
71 * Local copy of a database object.
72 *
73 * Accessor: BacklinkCache::getDB()
74 * Mutator : BacklinkCache::setDB()
75 * Cleared with BacklinkCache::clear()
76 */
77 protected $db;
78
79 /**
80 * Local copy of a Title object
81 */
82 protected $title;
83
84 const CACHE_EXPIRY = 3600;
85
86 /**
87 * Create a new BacklinkCache
88 *
89 * @param Title $title : Title object to create a backlink cache for
90 */
91 public function __construct( Title $title ) {
92 $this->title = $title;
93 }
94
95 /**
96 * Create a new BacklinkCache or reuse any existing one.
97 * Currently, only one cache instance can exist; callers that
98 * need multiple backlink cache objects should keep them in scope.
99 *
100 * @param Title $title Title object to get a backlink cache for
101 * @return BacklinkCache
102 */
103 public static function get( Title $title ) {
104 if ( !self::$cache ) { // init cache
105 self::$cache = new ProcessCacheLRU( 1 );
106 }
107 $dbKey = $title->getPrefixedDBkey();
108 if ( !self::$cache->has( $dbKey, 'obj', 3600 ) ) {
109 self::$cache->set( $dbKey, 'obj', new self( $title ) );
110 }
111
112 return self::$cache->get( $dbKey, 'obj' );
113 }
114
115 /**
116 * Serialization handler, diasallows to serialize the database to prevent
117 * failures after this class is deserialized from cache with dead DB
118 * connection.
119 *
120 * @return array
121 */
122 function __sleep() {
123 return array( 'partitionCache', 'fullResultCache', 'title' );
124 }
125
126 /**
127 * Clear locally stored data and database object.
128 */
129 public function clear() {
130 $this->partitionCache = array();
131 $this->fullResultCache = array();
132 unset( $this->db );
133 }
134
135 /**
136 * Set the Database object to use
137 *
138 * @param IDatabase $db
139 */
140 public function setDB( $db ) {
141 $this->db = $db;
142 }
143
144 /**
145 * Get the slave connection to the database
146 * When non existing, will initialize the connection.
147 * @return DatabaseBase
148 */
149 protected function getDB() {
150 if ( !isset( $this->db ) ) {
151 $this->db = wfGetDB( DB_SLAVE );
152 }
153
154 return $this->db;
155 }
156
157 /**
158 * Get the backlinks for a given table. Cached in process memory only.
159 * @param string $table
160 * @param int|bool $startId
161 * @param int|bool $endId
162 * @param int $max
163 * @return TitleArrayFromResult
164 */
165 public function getLinks( $table, $startId = false, $endId = false, $max = INF ) {
166 return TitleArray::newFromResult( $this->queryLinks( $table, $startId, $endId, $max ) );
167 }
168
169 /**
170 * Get the backlinks for a given table. Cached in process memory only.
171 * @param string $table
172 * @param int|bool $startId
173 * @param int|bool $endId
174 * @param int $max
175 * @param string $select 'all' or 'ids'
176 * @return ResultWrapper
177 */
178 protected function queryLinks( $table, $startId, $endId, $max, $select = 'all' ) {
179
180 $fromField = $this->getPrefix( $table ) . '_from';
181
182 if ( !$startId && !$endId && is_infinite( $max )
183 && isset( $this->fullResultCache[$table] )
184 ) {
185 wfDebug( __METHOD__ . ": got results from cache\n" );
186 $res = $this->fullResultCache[$table];
187 } else {
188 wfDebug( __METHOD__ . ": got results from DB\n" );
189 $conds = $this->getConditions( $table );
190 // Use the from field in the condition rather than the joined page_id,
191 // because databases are stupid and don't necessarily propagate indexes.
192 if ( $startId ) {
193 $conds[] = "$fromField >= " . intval( $startId );
194 }
195 if ( $endId ) {
196 $conds[] = "$fromField <= " . intval( $endId );
197 }
198 $options = array( 'ORDER BY' => $fromField );
199 if ( is_finite( $max ) && $max > 0 ) {
200 $options['LIMIT'] = $max;
201 }
202
203 if ( $select === 'ids' ) {
204 // Just select from the backlink table and ignore the page JOIN
205 $res = $this->getDB()->select(
206 $table,
207 array( $this->getPrefix( $table ) . '_from AS page_id' ),
208 array_filter( $conds, function ( $clause ) { // kind of janky
209 return !preg_match( '/(\b|=)page_id(\b|=)/', $clause );
210 } ),
211 __METHOD__,
212 $options
213 );
214 } else {
215 // Select from the backlink table and JOIN with page title information
216 $res = $this->getDB()->select(
217 array( $table, 'page' ),
218 array( 'page_namespace', 'page_title', 'page_id' ),
219 $conds,
220 __METHOD__,
221 array_merge( array( 'STRAIGHT_JOIN' ), $options )
222 );
223 }
224
225 if ( $select === 'all' && !$startId && !$endId && $res->numRows() < $max ) {
226 // The full results fit within the limit, so cache them
227 $this->fullResultCache[$table] = $res;
228 } else {
229 wfDebug( __METHOD__ . ": results from DB were uncacheable\n" );
230 }
231 }
232
233 return $res;
234 }
235
236 /**
237 * Get the field name prefix for a given table
238 * @param string $table
239 * @throws MWException
240 * @return null|string
241 */
242 protected function getPrefix( $table ) {
243 static $prefixes = array(
244 'pagelinks' => 'pl',
245 'imagelinks' => 'il',
246 'categorylinks' => 'cl',
247 'templatelinks' => 'tl',
248 'redirect' => 'rd',
249 );
250
251 if ( isset( $prefixes[$table] ) ) {
252 return $prefixes[$table];
253 } else {
254 $prefix = null;
255 Hooks::run( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
256 if ( $prefix ) {
257 return $prefix;
258 } else {
259 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
260 }
261 }
262 }
263
264 /**
265 * Get the SQL condition array for selecting backlinks, with a join
266 * on the page table.
267 * @param string $table
268 * @throws MWException
269 * @return array|null
270 */
271 protected function getConditions( $table ) {
272 $prefix = $this->getPrefix( $table );
273
274 switch ( $table ) {
275 case 'pagelinks':
276 case 'templatelinks':
277 $conds = array(
278 "{$prefix}_namespace" => $this->title->getNamespace(),
279 "{$prefix}_title" => $this->title->getDBkey(),
280 "page_id={$prefix}_from"
281 );
282 break;
283 case 'redirect':
284 $conds = array(
285 "{$prefix}_namespace" => $this->title->getNamespace(),
286 "{$prefix}_title" => $this->title->getDBkey(),
287 $this->getDb()->makeList( array(
288 "{$prefix}_interwiki" => '',
289 "{$prefix}_interwiki IS NULL",
290 ), LIST_OR ),
291 "page_id={$prefix}_from"
292 );
293 break;
294 case 'imagelinks':
295 case 'categorylinks':
296 $conds = array(
297 "{$prefix}_to" => $this->title->getDBkey(),
298 "page_id={$prefix}_from"
299 );
300 break;
301 default:
302 $conds = null;
303 Hooks::run( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
304 if ( !$conds ) {
305 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
306 }
307 }
308
309 return $conds;
310 }
311
312 /**
313 * Check if there are any backlinks
314 * @param string $table
315 * @return bool
316 */
317 public function hasLinks( $table ) {
318 return ( $this->getNumLinks( $table, 1 ) > 0 );
319 }
320
321 /**
322 * Get the approximate number of backlinks
323 * @param string $table
324 * @param int $max Only count up to this many backlinks
325 * @return int
326 */
327 public function getNumLinks( $table, $max = INF ) {
328 global $wgUpdateRowsPerJob;
329
330 $cache = ObjectCache::getMainWANInstance();
331 // 1) try partition cache ...
332 if ( isset( $this->partitionCache[$table] ) ) {
333 $entry = reset( $this->partitionCache[$table] );
334
335 return min( $max, $entry['numRows'] );
336 }
337
338 // 2) ... then try full result cache ...
339 if ( isset( $this->fullResultCache[$table] ) ) {
340 return min( $max, $this->fullResultCache[$table]->numRows() );
341 }
342
343 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
344
345 // 3) ... fallback to memcached ...
346 $count = $cache->get( $memcKey );
347 if ( $count ) {
348 return min( $max, $count );
349 }
350
351 // 4) fetch from the database ...
352 if ( is_infinite( $max ) ) { // no limit at all
353 // Use partition() since it will batch the query and skip the JOIN.
354 // Use $wgUpdateRowsPerJob just to encourage cache reuse for jobs.
355 $this->partition( $table, $wgUpdateRowsPerJob ); // updates $this->partitionCache
356 return $this->partitionCache[$table][$wgUpdateRowsPerJob]['numRows'];
357 } else { // probably some sane limit
358 // Fetch the full title info, since the caller will likely need it next
359 $count = $this->getLinks( $table, false, false, $max )->count();
360 if ( $count < $max ) { // full count
361 $cache->set( $memcKey, $count, self::CACHE_EXPIRY );
362 }
363 }
364
365 return min( $max, $count );
366 }
367
368 /**
369 * Partition the backlinks into batches.
370 * Returns an array giving the start and end of each range. The first
371 * batch has a start of false, and the last batch has an end of false.
372 *
373 * @param string $table The links table name
374 * @param int $batchSize
375 * @return array
376 */
377 public function partition( $table, $batchSize ) {
378 // 1) try partition cache ...
379 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
380 wfDebug( __METHOD__ . ": got from partition cache\n" );
381
382 return $this->partitionCache[$table][$batchSize]['batches'];
383 }
384
385 $cache = ObjectCache::getMainWANInstance();
386 $this->partitionCache[$table][$batchSize] = false;
387 $cacheEntry =& $this->partitionCache[$table][$batchSize];
388
389 // 2) ... then try full result cache ...
390 if ( isset( $this->fullResultCache[$table] ) ) {
391 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
392 wfDebug( __METHOD__ . ": got from full result cache\n" );
393
394 return $cacheEntry['batches'];
395 }
396
397 $memcKey = wfMemcKey(
398 'backlinks',
399 md5( $this->title->getPrefixedDBkey() ),
400 $table,
401 $batchSize
402 );
403
404 // 3) ... fallback to memcached ...
405 $memcValue = $cache->get( $memcKey );
406 if ( is_array( $memcValue ) ) {
407 $cacheEntry = $memcValue;
408 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
409
410 return $cacheEntry['batches'];
411 }
412
413 // 4) ... finally fetch from the slow database :(
414 $cacheEntry = array( 'numRows' => 0, 'batches' => array() ); // final result
415 // Do the selects in batches to avoid client-side OOMs (bug 43452).
416 // Use a LIMIT that plays well with $batchSize to keep equal sized partitions.
417 $selectSize = max( $batchSize, 200000 - ( 200000 % $batchSize ) );
418 $start = false;
419 do {
420 $res = $this->queryLinks( $table, $start, false, $selectSize, 'ids' );
421 $partitions = $this->partitionResult( $res, $batchSize, false );
422 // Merge the link count and range partitions for this chunk
423 $cacheEntry['numRows'] += $partitions['numRows'];
424 $cacheEntry['batches'] = array_merge( $cacheEntry['batches'], $partitions['batches'] );
425 if ( count( $partitions['batches'] ) ) {
426 list( , $lEnd ) = end( $partitions['batches'] );
427 $start = $lEnd + 1; // pick up after this inclusive range
428 }
429 } while ( $partitions['numRows'] >= $selectSize );
430 // Make sure the first range has start=false and the last one has end=false
431 if ( count( $cacheEntry['batches'] ) ) {
432 $cacheEntry['batches'][0][0] = false;
433 $cacheEntry['batches'][count( $cacheEntry['batches'] ) - 1][1] = false;
434 }
435
436 // Save partitions to memcached
437 $cache->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
438
439 // Save backlink count to memcached
440 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
441 $cache->set( $memcKey, $cacheEntry['numRows'], self::CACHE_EXPIRY );
442
443 wfDebug( __METHOD__ . ": got from database\n" );
444
445 return $cacheEntry['batches'];
446 }
447
448 /**
449 * Partition a DB result with backlinks in it into batches
450 * @param ResultWrapper $res Database result
451 * @param int $batchSize
452 * @param bool $isComplete Whether $res includes all the backlinks
453 * @throws MWException
454 * @return array
455 */
456 protected function partitionResult( $res, $batchSize, $isComplete = true ) {
457 $batches = array();
458 $numRows = $res->numRows();
459 $numBatches = ceil( $numRows / $batchSize );
460
461 for ( $i = 0; $i < $numBatches; $i++ ) {
462 if ( $i == 0 && $isComplete ) {
463 $start = false;
464 } else {
465 $rowNum = $i * $batchSize;
466 $res->seek( $rowNum );
467 $row = $res->fetchObject();
468 $start = (int)$row->page_id;
469 }
470
471 if ( $i == ( $numBatches - 1 ) && $isComplete ) {
472 $end = false;
473 } else {
474 $rowNum = min( $numRows - 1, ( $i + 1 ) * $batchSize - 1 );
475 $res->seek( $rowNum );
476 $row = $res->fetchObject();
477 $end = (int)$row->page_id;
478 }
479
480 # Sanity check order
481 if ( $start && $end && $start > $end ) {
482 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
483 }
484
485 $batches[] = array( $start, $end );
486 }
487
488 return array( 'numRows' => $numRows, 'batches' => $batches );
489 }
490
491 /**
492 * Get a Title iterator for cascade-protected template/file use backlinks
493 *
494 * @return TitleArray
495 * @since 1.25
496 */
497 public function getCascadeProtectedLinks() {
498 $dbr = $this->getDB();
499
500 // @todo: use UNION without breaking tests that use temp tables
501 $resSets = array();
502 $resSets[] = $dbr->select(
503 array( 'templatelinks', 'page_restrictions', 'page' ),
504 array( 'page_namespace', 'page_title', 'page_id' ),
505 array(
506 'tl_namespace' => $this->title->getNamespace(),
507 'tl_title' => $this->title->getDBkey(),
508 'tl_from = pr_page',
509 'pr_cascade' => 1,
510 'page_id = tl_from'
511 ),
512 __METHOD__,
513 array( 'DISTINCT' )
514 );
515 if ( $this->title->getNamespace() == NS_FILE ) {
516 $resSets[] = $dbr->select(
517 array( 'imagelinks', 'page_restrictions', 'page' ),
518 array( 'page_namespace', 'page_title', 'page_id' ),
519 array(
520 'il_to' => $this->title->getDBkey(),
521 'il_from = pr_page',
522 'pr_cascade' => 1,
523 'page_id = il_from'
524 ),
525 __METHOD__,
526 array( 'DISTINCT' )
527 );
528 }
529
530 // Combine and de-duplicate the results
531 $mergedRes = array();
532 foreach ( $resSets as $res ) {
533 foreach ( $res as $row ) {
534 $mergedRes[$row->page_id] = $row;
535 }
536 }
537
538 return TitleArray::newFromResult(
539 new FakeResultWrapper( array_values( $mergedRes ) ) );
540 }
541 }