Introduce a new hook that allows extensions to add to My Contributions
[mediawiki.git] / includes / BacklinkCache.php
blob2aba29f65bed897b9835d0c998c0cae20e984ec9
1 <?php
2 /**
3 * Class for fetching backlink lists, approximate backlink counts and
4 * partitions.
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.
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.
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
21 * @file
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Antoine Musso
28 /**
29 * Class for fetching backlink lists, approximate backlink counts and
30 * partitions. This is a shared cache.
32 * Instances of this class should typically be fetched with the method
33 * $title->getBacklinkCache().
35 * Ideally you should only get your backlinks from here when you think
36 * there is some advantage in caching them. Otherwise it's just a waste
37 * of memory.
39 * Introduced by r47317
41 * @internal documentation reviewed on 18 Mar 2011 by hashar
43 class BacklinkCache {
45 /**
46 * Multi dimensions array representing batches. Keys are:
47 * > (string) links table name
48 * > 'numRows' : Number of rows for this link table
49 * > 'batches' : array( $start, $end )
51 * @see BacklinkCache::partitionResult()
53 * Cleared with BacklinkCache::clear()
55 protected $partitionCache = array();
57 /**
58 * Contains the whole links from a database result.
59 * This is raw data that will be partitioned in $partitionCache
61 * Initialized with BacklinkCache::getLinks()
62 * Cleared with BacklinkCache::clear()
64 protected $fullResultCache = array();
66 /**
67 * Local copy of a database object.
69 * Accessor: BacklinkCache::getDB()
70 * Mutator : BacklinkCache::setDB()
71 * Cleared with BacklinkCache::clear()
73 protected $db;
75 /**
76 * Local copy of a Title object
78 protected $title;
80 const CACHE_EXPIRY = 3600;
82 /**
83 * Create a new BacklinkCache
84 * @param Title $title : Title object to create a backlink cache for.
86 function __construct( $title ) {
87 $this->title = $title;
90 /**
91 * Serialization handler, diasallows to serialize the database to prevent
92 * failures after this class is deserialized from cache with dead DB
93 * connection.
95 * @return array
97 function __sleep() {
98 return array( 'partitionCache', 'fullResultCache', 'title' );
102 * Clear locally stored data and database object.
104 public function clear() {
105 $this->partitionCache = array();
106 $this->fullResultCache = array();
107 unset( $this->db );
111 * Set the Database object to use
113 * @param $db DatabaseBase
115 public function setDB( $db ) {
116 $this->db = $db;
120 * Get the slave connection to the database
121 * When non existing, will initialize the connection.
122 * @return DatabaseBase object
124 protected function getDB() {
125 if ( !isset( $this->db ) ) {
126 $this->db = wfGetDB( DB_SLAVE );
129 return $this->db;
133 * Get the backlinks for a given table. Cached in process memory only.
134 * @param $table String
135 * @param $startId Integer or false
136 * @param $endId Integer or false
137 * @return TitleArrayFromResult
139 public function getLinks( $table, $startId = false, $endId = false ) {
140 wfProfileIn( __METHOD__ );
142 $fromField = $this->getPrefix( $table ) . '_from';
144 if ( $startId || $endId ) {
145 // Partial range, not cached
146 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
147 $conds = $this->getConditions( $table );
149 // Use the from field in the condition rather than the joined page_id,
150 // because databases are stupid and don't necessarily propagate indexes.
151 if ( $startId ) {
152 $conds[] = "$fromField >= " . intval( $startId );
155 if ( $endId ) {
156 $conds[] = "$fromField <= " . intval( $endId );
159 $res = $this->getDB()->select(
160 array( $table, 'page' ),
161 array( 'page_namespace', 'page_title', 'page_id' ),
162 $conds,
163 __METHOD__,
164 array(
165 'STRAIGHT_JOIN',
166 'ORDER BY' => $fromField
167 ) );
168 $ta = TitleArray::newFromResult( $res );
170 wfProfileOut( __METHOD__ );
171 return $ta;
174 // @todo FIXME: Make this a function?
175 if ( !isset( $this->fullResultCache[$table] ) ) {
176 wfDebug( __METHOD__ . ": from DB\n" );
177 $res = $this->getDB()->select(
178 array( $table, 'page' ),
179 array( 'page_namespace', 'page_title', 'page_id' ),
180 $this->getConditions( $table ),
181 __METHOD__,
182 array(
183 'STRAIGHT_JOIN',
184 'ORDER BY' => $fromField,
185 ) );
186 $this->fullResultCache[$table] = $res;
189 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
191 wfProfileOut( __METHOD__ );
192 return $ta;
196 * Get the field name prefix for a given table
197 * @param $table String
198 * @return null|string
200 protected function getPrefix( $table ) {
201 static $prefixes = array(
202 'pagelinks' => 'pl',
203 'imagelinks' => 'il',
204 'categorylinks' => 'cl',
205 'templatelinks' => 'tl',
206 'redirect' => 'rd',
209 if ( isset( $prefixes[$table] ) ) {
210 return $prefixes[$table];
211 } else {
212 $prefix = null;
213 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
214 if( $prefix ) {
215 return $prefix;
216 } else {
217 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
223 * Get the SQL condition array for selecting backlinks, with a join
224 * on the page table.
225 * @param $table String
226 * @return array|null
228 protected function getConditions( $table ) {
229 $prefix = $this->getPrefix( $table );
231 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
232 // they could be moved up for nicer case statements
233 switch ( $table ) {
234 case 'pagelinks':
235 case 'templatelinks':
236 $conds = array(
237 "{$prefix}_namespace" => $this->title->getNamespace(),
238 "{$prefix}_title" => $this->title->getDBkey(),
239 "page_id={$prefix}_from"
241 break;
242 case 'redirect':
243 $conds = array(
244 "{$prefix}_namespace" => $this->title->getNamespace(),
245 "{$prefix}_title" => $this->title->getDBkey(),
246 $this->getDb()->makeList( array(
247 "{$prefix}_interwiki = ''",
248 "{$prefix}_interwiki is null",
249 ), LIST_OR ),
250 "page_id={$prefix}_from"
252 break;
253 case 'imagelinks':
254 $conds = array(
255 'il_to' => $this->title->getDBkey(),
256 'page_id=il_from'
258 break;
259 case 'categorylinks':
260 $conds = array(
261 'cl_to' => $this->title->getDBkey(),
262 'page_id=cl_from',
264 break;
265 default:
266 $conds = null;
267 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
268 if( !$conds )
269 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
272 return $conds;
276 * Get the approximate number of backlinks
277 * @param $table String
278 * @return integer
280 public function getNumLinks( $table ) {
281 if ( isset( $this->fullResultCache[$table] ) ) {
282 return $this->fullResultCache[$table]->numRows();
285 if ( isset( $this->partitionCache[$table] ) ) {
286 $entry = reset( $this->partitionCache[$table] );
287 return $entry['numRows'];
290 $titleArray = $this->getLinks( $table );
292 return $titleArray->count();
296 * Partition the backlinks into batches.
297 * Returns an array giving the start and end of each range. The first
298 * batch has a start of false, and the last batch has an end of false.
300 * @param $table String: the links table name
301 * @param $batchSize Integer
302 * @return Array
304 public function partition( $table, $batchSize ) {
306 // 1) try partition cache ...
308 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
309 wfDebug( __METHOD__ . ": got from partition cache\n" );
310 return $this->partitionCache[$table][$batchSize]['batches'];
313 $this->partitionCache[$table][$batchSize] = false;
314 $cacheEntry =& $this->partitionCache[$table][$batchSize];
316 // 2) ... then try full result cache ...
318 if ( isset( $this->fullResultCache[$table] ) ) {
319 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
320 wfDebug( __METHOD__ . ": got from full result cache\n" );
322 return $cacheEntry['batches'];
325 // 3) ... fallback to memcached ...
327 global $wgMemc;
329 $memcKey = wfMemcKey(
330 'backlinks',
331 md5( $this->title->getPrefixedDBkey() ),
332 $table,
333 $batchSize
336 $memcValue = $wgMemc->get( $memcKey );
338 if ( is_array( $memcValue ) ) {
339 $cacheEntry = $memcValue;
340 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
342 return $cacheEntry['batches'];
346 // 4) ... finally fetch from the slow database :(
348 $this->getLinks( $table );
349 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
350 // Save to memcached
351 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
353 wfDebug( __METHOD__ . ": got from database\n" );
354 return $cacheEntry['batches'];
358 * Partition a DB result with backlinks in it into batches
359 * @param $res ResultWrapper database result
360 * @param $batchSize integer
361 * @return array @see
363 protected function partitionResult( $res, $batchSize ) {
364 $batches = array();
365 $numRows = $res->numRows();
366 $numBatches = ceil( $numRows / $batchSize );
368 for ( $i = 0; $i < $numBatches; $i++ ) {
369 if ( $i == 0 ) {
370 $start = false;
371 } else {
372 $rowNum = intval( $numRows * $i / $numBatches );
373 $res->seek( $rowNum );
374 $row = $res->fetchObject();
375 $start = $row->page_id;
378 if ( $i == $numBatches - 1 ) {
379 $end = false;
380 } else {
381 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
382 $res->seek( $rowNum );
383 $row = $res->fetchObject();
384 $end = $row->page_id - 1;
387 # Sanity check order
388 if ( $start && $end && $start > $end ) {
389 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
392 $batches[] = array( $start, $end );
395 return array( 'numRows' => $numRows, 'batches' => $batches );