3 * File for BacklinkCache class
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
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, Antoine Musso
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();
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();
51 * Local copy of a database object.
53 * Accessor: BacklinkCache::getDB()
54 * Mutator : BacklinkCache::setDB()
55 * Cleared with BacklinkCache::clear()
60 * Local copy of a Title object
64 const CACHE_EXPIRY
= 3600;
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;
75 * Serialization handler, diasallows to serialize the database to prevent
76 * failures after this class is deserialized from cache with dead DB
82 return array( 'partitionCache', 'fullResultCache', 'title' );
86 * Clear locally stored data and database object.
88 public function clear() {
89 $this->partitionCache
= array();
90 $this->fullResultCache
= array();
95 * Set the Database object to use
97 * @param $db DatabaseBase
99 public function setDB( $db ) {
104 * Get the slave connection to the database
105 * When non existing, will initialize the connection.
106 * @return DatabaseBase object
108 protected function getDB() {
109 if ( !isset( $this->db
) ) {
110 $this->db
= wfGetDB( DB_SLAVE
);
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.
136 $conds[] = "$fromField >= " . intval( $startId );
140 $conds[] = "$fromField <= " . intval( $endId );
143 $res = $this->getDB()->select(
144 array( $table, 'page' ),
145 array( 'page_namespace', 'page_title', 'page_id' ),
150 'ORDER BY' => $fromField
152 $ta = TitleArray
::newFromResult( $res );
154 wfProfileOut( __METHOD__
);
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 ),
168 'ORDER BY' => $fromField,
170 $this->fullResultCache
[$table] = $res;
173 $ta = TitleArray
::newFromResult( $this->fullResultCache
[$table] );
175 wfProfileOut( __METHOD__
);
180 * Get the field name prefix for a given table
181 * @param $table String
182 * @return null|string
184 protected function getPrefix( $table ) {
185 static $prefixes = array(
187 'imagelinks' => 'il',
188 'categorylinks' => 'cl',
189 'templatelinks' => 'tl',
193 if ( isset( $prefixes[$table] ) ) {
194 return $prefixes[$table];
197 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
201 throw new MWException( "Invalid table \"$table\" in " . __CLASS__
);
207 * Get the SQL condition array for selecting backlinks, with a join
209 * @param $table String
212 protected function getConditions( $table ) {
213 $prefix = $this->getPrefix( $table );
215 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
216 // they could be moved up for nicer case statements
219 case 'templatelinks':
221 "{$prefix}_namespace" => $this->title
->getNamespace(),
222 "{$prefix}_title" => $this->title
->getDBkey(),
223 "page_id={$prefix}_from"
228 "{$prefix}_namespace" => $this->title
->getNamespace(),
229 "{$prefix}_title" => $this->title
->getDBkey(),
230 $this->getDb()->makeList( array(
231 "{$prefix}_interwiki = ''",
232 "{$prefix}_interwiki is null",
234 "page_id={$prefix}_from"
239 'il_to' => $this->title
->getDBkey(),
243 case 'categorylinks':
245 'cl_to' => $this->title
->getDBkey(),
251 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title
, &$conds ) );
253 throw new MWException( "Invalid table \"$table\" in " . __CLASS__
);
260 * Get the approximate number of backlinks
261 * @param $table String
264 public function getNumLinks( $table ) {
265 if ( isset( $this->fullResultCache
[$table] ) ) {
266 return $this->fullResultCache
[$table]->numRows();
269 if ( isset( $this->partitionCache
[$table] ) ) {
270 $entry = reset( $this->partitionCache
[$table] );
271 return $entry['numRows'];
274 $titleArray = $this->getLinks( $table );
276 return $titleArray->count();
280 * Partition the backlinks into batches.
281 * Returns an array giving the start and end of each range. The first
282 * batch has a start of false, and the last batch has an end of false.
284 * @param $table String: the links table name
285 * @param $batchSize Integer
288 public function partition( $table, $batchSize ) {
290 // 1) try partition cache ...
292 if ( isset( $this->partitionCache
[$table][$batchSize] ) ) {
293 wfDebug( __METHOD__
. ": got from partition cache\n" );
294 return $this->partitionCache
[$table][$batchSize]['batches'];
297 $this->partitionCache
[$table][$batchSize] = false;
298 $cacheEntry =& $this->partitionCache
[$table][$batchSize];
300 // 2) ... then try full result cache ...
302 if ( isset( $this->fullResultCache
[$table] ) ) {
303 $cacheEntry = $this->partitionResult( $this->fullResultCache
[$table], $batchSize );
304 wfDebug( __METHOD__
. ": got from full result cache\n" );
306 return $cacheEntry['batches'];
309 // 3) ... fallback to memcached ...
313 $memcKey = wfMemcKey(
315 md5( $this->title
->getPrefixedDBkey() ),
320 $memcValue = $wgMemc->get( $memcKey );
322 if ( is_array( $memcValue ) ) {
323 $cacheEntry = $memcValue;
324 wfDebug( __METHOD__
. ": got from memcached $memcKey\n" );
326 return $cacheEntry['batches'];
330 // 4) ... finally fetch from the slow database :(
332 $this->getLinks( $table );
333 $cacheEntry = $this->partitionResult( $this->fullResultCache
[$table], $batchSize );
335 $wgMemc->set( $memcKey, $cacheEntry, self
::CACHE_EXPIRY
);
337 wfDebug( __METHOD__
. ": got from database\n" );
338 return $cacheEntry['batches'];
342 * Partition a DB result with backlinks in it into batches
343 * @param $res ResultWrapper database result
344 * @param $batchSize integer
347 protected function partitionResult( $res, $batchSize ) {
349 $numRows = $res->numRows();
350 $numBatches = ceil( $numRows / $batchSize );
352 for ( $i = 0; $i < $numBatches; $i++
) {
356 $rowNum = intval( $numRows * $i / $numBatches );
357 $res->seek( $rowNum );
358 $row = $res->fetchObject();
359 $start = $row->page_id
;
362 if ( $i == $numBatches - 1 ) {
365 $rowNum = intval( $numRows * ( $i +
1 ) / $numBatches );
366 $res->seek( $rowNum );
367 $row = $res->fetchObject();
368 $end = $row->page_id
- 1;
372 if ( $start && $end && $start > $end ) {
373 throw new MWException( __METHOD__
. ': Internal error: query result out of order' );
376 $batches[] = array( $start, $end );
379 return array( 'numRows' => $numRows, 'batches' => $batches );