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