Merge "Prevent space before ellipsis when truncating"
[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 * @internal documentation reviewed on 18 Mar 2011 by hashar
43 */
44 class BacklinkCache {
45 /** @var ProcessCacheLRU */
46 protected static $cache;
47
48 /**
49 * Multi dimensions array representing batches. Keys are:
50 * > (string) links table name
51 * > (int) batch size
52 * > 'numRows' : Number of rows for this link table
53 * > 'batches' : array( $start, $end )
54 *
55 * @see BacklinkCache::partitionResult()
56 *
57 * Cleared with BacklinkCache::clear()
58 */
59 protected $partitionCache = array();
60
61 /**
62 * Contains the whole links from a database result.
63 * This is raw data that will be partitioned in $partitionCache
64 *
65 * Initialized with BacklinkCache::getLinks()
66 * Cleared with BacklinkCache::clear()
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 return self::$cache->get( $dbKey, 'obj' );
112 }
113
114 /**
115 * Serialization handler, diasallows to serialize the database to prevent
116 * failures after this class is deserialized from cache with dead DB
117 * connection.
118 *
119 * @return array
120 */
121 function __sleep() {
122 return array( 'partitionCache', 'fullResultCache', 'title' );
123 }
124
125 /**
126 * Clear locally stored data and database object.
127 */
128 public function clear() {
129 $this->partitionCache = array();
130 $this->fullResultCache = array();
131 unset( $this->db );
132 }
133
134 /**
135 * Set the Database object to use
136 *
137 * @param $db DatabaseBase
138 */
139 public function setDB( $db ) {
140 $this->db = $db;
141 }
142
143 /**
144 * Get the slave connection to the database
145 * When non existing, will initialize the connection.
146 * @return DatabaseBase object
147 */
148 protected function getDB() {
149 if ( !isset( $this->db ) ) {
150 $this->db = wfGetDB( DB_SLAVE );
151 }
152 return $this->db;
153 }
154
155 /**
156 * Get the backlinks for a given table. Cached in process memory only.
157 * @param $table String
158 * @param $startId Integer|false
159 * @param $endId Integer|false
160 * @param $max Integer|INF
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 $table String
170 * @param $startId Integer|false
171 * @param $endId Integer|false
172 * @param $max Integer|INF
173 * @param $select string 'all' or 'ids'
174 * @return ResultWrapper
175 */
176 protected function queryLinks( $table, $startId, $endId, $max, $select = 'all' ) {
177 wfProfileIn( __METHOD__ );
178
179 $fromField = $this->getPrefix( $table ) . '_from';
180
181 if ( !$startId && !$endId && is_infinite( $max )
182 && isset( $this->fullResultCache[$table] ) )
183 {
184 wfDebug( __METHOD__ . ": got results from cache\n" );
185 $res = $this->fullResultCache[$table];
186 } else {
187 wfDebug( __METHOD__ . ": got results from DB\n" );
188 $conds = $this->getConditions( $table );
189 // Use the from field in the condition rather than the joined page_id,
190 // because databases are stupid and don't necessarily propagate indexes.
191 if ( $startId ) {
192 $conds[] = "$fromField >= " . intval( $startId );
193 }
194 if ( $endId ) {
195 $conds[] = "$fromField <= " . intval( $endId );
196 }
197 $options = array( 'ORDER BY' => $fromField );
198 if ( is_finite( $max ) && $max > 0 ) {
199 $options['LIMIT'] = $max;
200 }
201
202 if ( $select === 'ids' ) {
203 // Just select from the backlink table and ignore the page JOIN
204 $res = $this->getDB()->select(
205 $table,
206 array( $this->getPrefix( $table ) . '_from AS page_id' ),
207 array_filter( $conds, function( $clause ) { // kind of janky
208 return !preg_match( '/(\b|=)page_id(\b|=)/', $clause );
209 } ),
210 __METHOD__,
211 $options
212 );
213 } else {
214 // Select from the backlink table and JOIN with page title information
215 $res = $this->getDB()->select(
216 array( $table, 'page' ),
217 array( 'page_namespace', 'page_title', 'page_id' ),
218 $conds,
219 __METHOD__,
220 array_merge( array( 'STRAIGHT_JOIN' ), $options )
221 );
222 }
223
224 if ( !$startId && !$endId && $res->numRows() < $max ) {
225 // The full results fit within the limit, so cache them
226 $this->fullResultCache[$table] = $res;
227 } else {
228 wfDebug( __METHOD__ . ": results from DB were uncacheable\n" );
229 }
230 }
231
232 wfProfileOut( __METHOD__ );
233 return $res;
234 }
235
236 /**
237 * Get the field name prefix for a given table
238 * @param $table String
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 wfRunHooks( '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 $table String
268 * @throws MWException
269 * @return array|null
270 */
271 protected function getConditions( $table ) {
272 $prefix = $this->getPrefix( $table );
273
274 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
275 // they could be moved up for nicer case statements
276 switch ( $table ) {
277 case 'pagelinks':
278 case 'templatelinks':
279 $conds = array(
280 "{$prefix}_namespace" => $this->title->getNamespace(),
281 "{$prefix}_title" => $this->title->getDBkey(),
282 "page_id={$prefix}_from"
283 );
284 break;
285 case 'redirect':
286 $conds = array(
287 "{$prefix}_namespace" => $this->title->getNamespace(),
288 "{$prefix}_title" => $this->title->getDBkey(),
289 $this->getDb()->makeList( array(
290 "{$prefix}_interwiki" => '',
291 "{$prefix}_interwiki IS NULL",
292 ), LIST_OR ),
293 "page_id={$prefix}_from"
294 );
295 break;
296 case 'imagelinks':
297 $conds = array(
298 'il_to' => $this->title->getDBkey(),
299 "page_id={$prefix}_from"
300 );
301 break;
302 case 'categorylinks':
303 $conds = array(
304 'cl_to' => $this->title->getDBkey(),
305 "page_id={$prefix}_from"
306 );
307 break;
308 default:
309 $conds = null;
310 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
311 if ( !$conds ) {
312 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
313 }
314 }
315
316 return $conds;
317 }
318
319 /**
320 * Check if there are any backlinks
321 * @param $table String
322 * @return bool
323 */
324 public function hasLinks( $table ) {
325 return ( $this->getNumLinks( $table, 1 ) > 0 );
326 }
327
328 /**
329 * Get the approximate number of backlinks
330 * @param $table String
331 * @param $max integer|INF Only count up to this many backlinks
332 * @return integer
333 */
334 public function getNumLinks( $table, $max = INF ) {
335 global $wgMemc, $wgUpdateRowsPerJob;
336
337 // 1) try partition cache ...
338 if ( isset( $this->partitionCache[$table] ) ) {
339 $entry = reset( $this->partitionCache[$table] );
340 return min( $max, $entry['numRows'] );
341 }
342
343 // 2) ... then try full result cache ...
344 if ( isset( $this->fullResultCache[$table] ) ) {
345 return min( $max, $this->fullResultCache[$table]->numRows() );
346 }
347
348 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
349
350 // 3) ... fallback to memcached ...
351 $count = $wgMemc->get( $memcKey );
352 if ( $count ) {
353 return min( $max, $count );
354 }
355
356 // 4) fetch from the database ...
357 if ( is_infinite( $max ) ) { // no limit at all
358 // Use partition() since it will batch the query and skip the JOIN.
359 // Use $wgUpdateRowsPerJob just to encourage cache reuse for jobs.
360 $this->partition( $table, $wgUpdateRowsPerJob ); // updates $this->partitionCache
361 return $this->partitionCache[$table][$wgUpdateRowsPerJob]['numRows'];
362 } else { // probably some sane limit
363 // Fetch the full title info, since the caller will likely need it next
364 $count = $this->getLinks( $table, false, false, $max )->count();
365 if ( $count < $max ) { // full count
366 $wgMemc->set( $memcKey, $count, self::CACHE_EXPIRY );
367 }
368 }
369
370 return min( $max, $count );
371 }
372
373 /**
374 * Partition the backlinks into batches.
375 * Returns an array giving the start and end of each range. The first
376 * batch has a start of false, and the last batch has an end of false.
377 *
378 * @param string $table the links table name
379 * @param $batchSize Integer
380 * @return Array
381 */
382 public function partition( $table, $batchSize ) {
383 global $wgMemc;
384
385 // 1) try partition cache ...
386 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
387 wfDebug( __METHOD__ . ": got from partition cache\n" );
388 return $this->partitionCache[$table][$batchSize]['batches'];
389 }
390
391 $this->partitionCache[$table][$batchSize] = false;
392 $cacheEntry =& $this->partitionCache[$table][$batchSize];
393
394 // 2) ... then try full result cache ...
395 if ( isset( $this->fullResultCache[$table] ) ) {
396 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
397 wfDebug( __METHOD__ . ": got from full result cache\n" );
398 return $cacheEntry['batches'];
399 }
400
401 $memcKey = wfMemcKey(
402 'backlinks',
403 md5( $this->title->getPrefixedDBkey() ),
404 $table,
405 $batchSize
406 );
407
408 // 3) ... fallback to memcached ...
409 $memcValue = $wgMemc->get( $memcKey );
410 if ( is_array( $memcValue ) ) {
411 $cacheEntry = $memcValue;
412 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
413 return $cacheEntry['batches'];
414 }
415
416 // 4) ... finally fetch from the slow database :(
417 $cacheEntry = array( 'numRows' => 0, 'batches' => array() ); // final result
418 // Do the selects in batches to avoid client-side OOMs (bug 43452).
419 // Use a LIMIT that plays well with $batchSize to keep equal sized partitions.
420 $selectSize = max( $batchSize, 200000 - ( 200000 % $batchSize ) );
421 $start = false;
422 do {
423 $res = $this->queryLinks( $table, $start, false, $selectSize, 'ids' );
424 $partitions = $this->partitionResult( $res, $batchSize, false );
425 // Merge the link count and range partitions for this chunk
426 $cacheEntry['numRows'] += $partitions['numRows'];
427 $cacheEntry['batches'] = array_merge( $cacheEntry['batches'], $partitions['batches'] );
428 if ( count( $partitions['batches'] ) ) {
429 list( $lStart, $lEnd ) = end( $partitions['batches'] );
430 $start = $lEnd + 1; // pick up after this inclusive range
431 }
432 } while ( $partitions['numRows'] >= $selectSize );
433 // Make sure the first range has start=false and the last one has end=false
434 if ( count( $cacheEntry['batches'] ) ) {
435 $cacheEntry['batches'][0][0] = false;
436 $cacheEntry['batches'][count( $cacheEntry['batches'] ) - 1][1] = false;
437 }
438
439 // Save partitions to memcached
440 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
441
442 // Save backlink count to memcached
443 $memcKey = wfMemcKey( 'numbacklinks', md5( $this->title->getPrefixedDBkey() ), $table );
444 $wgMemc->set( $memcKey, $cacheEntry['numRows'], self::CACHE_EXPIRY );
445
446 wfDebug( __METHOD__ . ": got from database\n" );
447 return $cacheEntry['batches'];
448 }
449
450 /**
451 * Partition a DB result with backlinks in it into batches
452 * @param $res ResultWrapper database result
453 * @param $batchSize integer
454 * @param $isComplete bool Whether $res includes all the backlinks
455 * @throws MWException
456 * @return array
457 */
458 protected function partitionResult( $res, $batchSize, $isComplete = true ) {
459 $batches = array();
460 $numRows = $res->numRows();
461 $numBatches = ceil( $numRows / $batchSize );
462
463 for ( $i = 0; $i < $numBatches; $i++ ) {
464 if ( $i == 0 && $isComplete ) {
465 $start = false;
466 } else {
467 $rowNum = $i * $batchSize;
468 $res->seek( $rowNum );
469 $row = $res->fetchObject();
470 $start = (int)$row->page_id;
471 }
472
473 if ( $i == ( $numBatches - 1 ) && $isComplete ) {
474 $end = false;
475 } else {
476 $rowNum = min( $numRows - 1, ( $i + 1 ) * $batchSize - 1 );
477 $res->seek( $rowNum );
478 $row = $res->fetchObject();
479 $end = (int)$row->page_id;
480 }
481
482 # Sanity check order
483 if ( $start && $end && $start > $end ) {
484 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
485 }
486
487 $batches[] = array( $start, $end );
488 }
489
490 return array( 'numRows' => $numRows, 'batches' => $batches );
491 }
492 }