Mark userLink, userTalkLink, blockLink() and emailLink() as public static per CR...
[mediawiki.git] / includes / BacklinkCache.php
bloba6ad0039869737c234a6ce88f8a380705bc30c59
1 <?php
2 /**
3 * File for BacklinkCache class
4 * @file
5 */
7 /**
8 * Class for fetching backlink lists, approximate backlink counts and
9 * partitions. This is a shared cache.
11 * Instances of this class should typically be fetched with the method
12 * $title->getBacklinkCache().
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.
18 * Introduced by r47317
20 * @internal documentation reviewed on 18 Mar 2011 by hashar
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Ashar Voultoiz
27 class BacklinkCache {
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 )
35 * @see BacklinkCache::partitionResult()
37 * Cleared with BacklinkCache::clear()
39 protected $partitionCache = array();
41 /**
42 * Contains the whole links from a database result.
43 * This is raw data that will be partitioned in $partitionCache
45 * Initialized with BacklinkCache::getLinks()
46 * Cleared with BacklinkCache::clear()
48 protected $fullResultCache = array();
50 /**
51 * Local copy of a database object.
53 * Accessor: BacklinkCache::getDB()
54 * Mutator : BacklinkCache::setDB()
55 * Cleared with BacklinkCache::clear()
57 protected $db;
59 /**
60 * Local copy of a Title object
62 protected $title;
64 const CACHE_EXPIRY = 3600;
66 /**
67 * Create a new BacklinkCache
68 * @param Title $title : Title object to create a backlink cache for.
70 function __construct( $title ) {
71 $this->title = $title;
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.
79 * @return array
81 function __sleep() {
82 return array( 'partitionCache', 'fullResultCache', 'title' );
85 /**
86 * Clear locally stored data and database object.
88 public function clear() {
89 $this->partitionCache = array();
90 $this->fullResultCache = array();
91 unset( $this->db );
94 /**
95 * Set the Database object to use
97 * @param $db DatabaseBase
99 public function setDB( $db ) {
100 $this->db = $db;
104 * Get the slave connection to the database
105 * When non existing, will initialize the connection.
106 * @return Database object
108 protected function getDB() {
109 if ( !isset( $this->db ) ) {
110 $this->db = wfGetDB( DB_SLAVE );
113 return $this->db;
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
123 public function getLinks( $table, $startId = false, $endId = false ) {
124 wfProfileIn( __METHOD__ );
126 $fromField = $this->getPrefix( $table ) . '_from';
128 if ( $startId || $endId ) {
129 // Partial range, not cached
130 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
131 $conds = $this->getConditions( $table );
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 );
139 if ( $endId ) {
140 $conds[] = "$fromField <= " . intval( $endId );
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 );
154 wfProfileOut( __METHOD__ );
155 return $ta;
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;
173 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
175 wfProfileOut( __METHOD__ );
176 return $ta;
180 * Get the distant backtemplatelinks for the table globaltemplatelinks. Cached in process memory only.
181 * @return ResultWrapper list of distant pages that use the local title
183 public function getDistantTemplateLinks( ) {
184 global $wgGlobalDatabase, $wgLocalInterwiki;
186 $dbr = wfGetDB( DB_SLAVE, array(), $wgGlobalDatabase );
187 $res = $dbr->select(
188 array( 'globaltemplatelinks', 'globalinterwiki' ),
189 array( 'gtl_from_wiki', 'gtl_from_page', 'gtl_from_title', 'giw_prefix' ),
190 array( 'gtl_to_prefix' => $wgLocalInterwiki, 'gtl_to_title' => $this->title->getDBkey( ) ),
191 __METHOD__,
192 null,
193 array( 'gtl_from_wiki = giw_wikiid' )
195 return $res;
199 * Get the field name prefix for a given table
200 * @param $table String
202 protected function getPrefix( $table ) {
203 static $prefixes = array(
204 'pagelinks' => 'pl',
205 'imagelinks' => 'il',
206 'categorylinks' => 'cl',
207 'templatelinks' => 'tl',
208 'redirect' => 'rd',
209 'globaltemplatelinks' => 'gtl',
212 if ( isset( $prefixes[$table] ) ) {
213 return $prefixes[$table];
214 } else {
215 $prefix = null;
216 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
217 if( $prefix ) {
218 return $prefix;
219 } else {
220 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
226 * Get the SQL condition array for selecting backlinks, with a join
227 * on the page table.
228 * @param $table String
230 protected function getConditions( $table ) {
231 $prefix = $this->getPrefix( $table );
233 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
234 // they could be moved up for nicer case statements
235 switch ( $table ) {
236 case 'pagelinks':
237 case 'templatelinks':
238 $conds = array(
239 "{$prefix}_namespace" => $this->title->getNamespace(),
240 "{$prefix}_title" => $this->title->getDBkey(),
241 "page_id={$prefix}_from"
243 break;
244 case 'redirect':
245 $conds = array(
246 "{$prefix}_namespace" => $this->title->getNamespace(),
247 "{$prefix}_title" => $this->title->getDBkey(),
248 $this->getDb()->makeList( array(
249 "{$prefix}_interwiki = ''",
250 "{$prefix}_interwiki is null",
251 ), LIST_OR ),
252 "page_id={$prefix}_from"
254 break;
255 case 'imagelinks':
256 $conds = array(
257 'il_to' => $this->title->getDBkey(),
258 'page_id=il_from'
260 break;
261 case 'categorylinks':
262 $conds = array(
263 'cl_to' => $this->title->getDBkey(),
264 'page_id=cl_from',
266 break;
267 default:
268 $conds = null;
269 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
270 if( !$conds )
271 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
274 return $conds;
278 * Get the approximate number of backlinks
279 * @param $table String
280 * @return integer
282 public function getNumLinks( $table ) {
283 if ( isset( $this->fullResultCache[$table] ) ) {
284 return $this->fullResultCache[$table]->numRows();
287 if ( isset( $this->partitionCache[$table] ) ) {
288 $entry = reset( $this->partitionCache[$table] );
289 return $entry['numRows'];
292 $titleArray = $this->getLinks( $table );
294 return $titleArray->count();
298 * Partition the backlinks into batches.
299 * Returns an array giving the start and end of each range. The first
300 * batch has a start of false, and the last batch has an end of false.
302 * @param $table String: the links table name
303 * @param $batchSize Integer
304 * @return Array
306 public function partition( $table, $batchSize ) {
308 // 1) try partition cache ...
310 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
311 wfDebug( __METHOD__ . ": got from partition cache\n" );
312 return $this->partitionCache[$table][$batchSize]['batches'];
315 $this->partitionCache[$table][$batchSize] = false;
316 $cacheEntry =& $this->partitionCache[$table][$batchSize];
318 // 2) ... then try full result cache ...
320 if ( isset( $this->fullResultCache[$table] ) ) {
321 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
322 wfDebug( __METHOD__ . ": got from full result cache\n" );
324 return $cacheEntry['batches'];
327 // 3) ... fallback to memcached ...
329 global $wgMemc;
331 $memcKey = wfMemcKey(
332 'backlinks',
333 md5( $this->title->getPrefixedDBkey() ),
334 $table,
335 $batchSize
338 $memcValue = $wgMemc->get( $memcKey );
340 if ( is_array( $memcValue ) ) {
341 $cacheEntry = $memcValue;
342 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
344 return $cacheEntry['batches'];
348 // 4) ... finally fetch from the slow database :(
350 $this->getLinks( $table );
351 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
352 // Save to memcached
353 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
355 wfDebug( __METHOD__ . ": got from database\n" );
356 return $cacheEntry['batches'];
360 * Partition a DB result with backlinks in it into batches
361 * @param $res ResultWrapper database result
362 * @param $batchSize integer
363 * @return array @see
365 protected function partitionResult( $res, $batchSize ) {
366 $batches = array();
367 $numRows = $res->numRows();
368 $numBatches = ceil( $numRows / $batchSize );
370 for ( $i = 0; $i < $numBatches; $i++ ) {
371 if ( $i == 0 ) {
372 $start = false;
373 } else {
374 $rowNum = intval( $numRows * $i / $numBatches );
375 $res->seek( $rowNum );
376 $row = $res->fetchObject();
377 $start = $row->page_id;
380 if ( $i == $numBatches - 1 ) {
381 $end = false;
382 } else {
383 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
384 $res->seek( $rowNum );
385 $row = $res->fetchObject();
386 $end = $row->page_id - 1;
389 # Sanity check order
390 if ( $start && $end && $start > $end ) {
391 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
394 $batches[] = array( $start, $end );
397 return array( 'numRows' => $numRows, 'batches' => $batches );