More return documentation
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * File for BacklinkCache class
4 * @file
5 */
6
7 /**
8 * Class for fetching backlink lists, approximate backlink counts and
9 * partitions. This is a shared cache.
10 *
11 * Instances of this class should typically be fetched with the method
12 * $title->getBacklinkCache().
13 *
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.
17 *
18 * Introduced by r47317
19 *
20 * @internal documentation reviewed on 18 Mar 2011 by hashar
21 *
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Antoine Musso
26 */
27 class BacklinkCache {
28
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 )
34 *
35 * @see BacklinkCache::partitionResult()
36 *
37 * Cleared with BacklinkCache::clear()
38 */
39 protected $partitionCache = array();
40
41 /**
42 * Contains the whole links from a database result.
43 * This is raw data that will be partitioned in $partitionCache
44 *
45 * Initialized with BacklinkCache::getLinks()
46 * Cleared with BacklinkCache::clear()
47 */
48 protected $fullResultCache = array();
49
50 /**
51 * Local copy of a database object.
52 *
53 * Accessor: BacklinkCache::getDB()
54 * Mutator : BacklinkCache::setDB()
55 * Cleared with BacklinkCache::clear()
56 */
57 protected $db;
58
59 /**
60 * Local copy of a Title object
61 */
62 protected $title;
63
64 const CACHE_EXPIRY = 3600;
65
66 /**
67 * Create a new BacklinkCache
68 * @param Title $title : Title object to create a backlink cache for.
69 */
70 function __construct( $title ) {
71 $this->title = $title;
72 }
73
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.
78 *
79 * @return array
80 */
81 function __sleep() {
82 return array( 'partitionCache', 'fullResultCache', 'title' );
83 }
84
85 /**
86 * Clear locally stored data and database object.
87 */
88 public function clear() {
89 $this->partitionCache = array();
90 $this->fullResultCache = array();
91 unset( $this->db );
92 }
93
94 /**
95 * Set the Database object to use
96 *
97 * @param $db DatabaseBase
98 */
99 public function setDB( $db ) {
100 $this->db = $db;
101 }
102
103 /**
104 * Get the slave connection to the database
105 * When non existing, will initialize the connection.
106 * @return DatabaseBase object
107 */
108 protected function getDB() {
109 if ( !isset( $this->db ) ) {
110 $this->db = wfGetDB( DB_SLAVE );
111 }
112
113 return $this->db;
114 }
115
116 /**
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
122 */
123 public function getLinks( $table, $startId = false, $endId = false ) {
124 wfProfileIn( __METHOD__ );
125
126 $fromField = $this->getPrefix( $table ) . '_from';
127
128 if ( $startId || $endId ) {
129 // Partial range, not cached
130 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
131 $conds = $this->getConditions( $table );
132
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 );
137 }
138
139 if ( $endId ) {
140 $conds[] = "$fromField <= " . intval( $endId );
141 }
142
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 );
153
154 wfProfileOut( __METHOD__ );
155 return $ta;
156 }
157
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;
171 }
172
173 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
174
175 wfProfileOut( __METHOD__ );
176 return $ta;
177 }
178
179 /**
180 * Get the field name prefix for a given table
181 * @param $table String
182 * @return null|string
183 */
184 protected function getPrefix( $table ) {
185 static $prefixes = array(
186 'pagelinks' => 'pl',
187 'imagelinks' => 'il',
188 'categorylinks' => 'cl',
189 'templatelinks' => 'tl',
190 'redirect' => 'rd',
191 );
192
193 if ( isset( $prefixes[$table] ) ) {
194 return $prefixes[$table];
195 } else {
196 $prefix = null;
197 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
198 if( $prefix ) {
199 return $prefix;
200 } else {
201 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
202 }
203 }
204 }
205
206 /**
207 * Get the SQL condition array for selecting backlinks, with a join
208 * on the page table.
209 * @param $table String
210 * @return array|null
211 */
212 protected function getConditions( $table ) {
213 $prefix = $this->getPrefix( $table );
214
215 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
216 // they could be moved up for nicer case statements
217 switch ( $table ) {
218 case 'pagelinks':
219 case 'templatelinks':
220 $conds = array(
221 "{$prefix}_namespace" => $this->title->getNamespace(),
222 "{$prefix}_title" => $this->title->getDBkey(),
223 "page_id={$prefix}_from"
224 );
225 break;
226 case 'redirect':
227 $conds = array(
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",
233 ), LIST_OR ),
234 "page_id={$prefix}_from"
235 );
236 break;
237 case 'imagelinks':
238 $conds = array(
239 'il_to' => $this->title->getDBkey(),
240 'page_id=il_from'
241 );
242 break;
243 case 'categorylinks':
244 $conds = array(
245 'cl_to' => $this->title->getDBkey(),
246 'page_id=cl_from',
247 );
248 break;
249 default:
250 $conds = null;
251 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
252 if( !$conds )
253 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
254 }
255
256 return $conds;
257 }
258
259 /**
260 * Get the approximate number of backlinks
261 * @param $table String
262 * @return integer
263 */
264 public function getNumLinks( $table ) {
265 if ( isset( $this->fullResultCache[$table] ) ) {
266 return $this->fullResultCache[$table]->numRows();
267 }
268
269 if ( isset( $this->partitionCache[$table] ) ) {
270 $entry = reset( $this->partitionCache[$table] );
271 return $entry['numRows'];
272 }
273
274 $titleArray = $this->getLinks( $table );
275
276 return $titleArray->count();
277 }
278
279 /**
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.
283 *
284 * @param $table String: the links table name
285 * @param $batchSize Integer
286 * @return Array
287 */
288 public function partition( $table, $batchSize ) {
289
290 // 1) try partition cache ...
291
292 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
293 wfDebug( __METHOD__ . ": got from partition cache\n" );
294 return $this->partitionCache[$table][$batchSize]['batches'];
295 }
296
297 $this->partitionCache[$table][$batchSize] = false;
298 $cacheEntry =& $this->partitionCache[$table][$batchSize];
299
300 // 2) ... then try full result cache ...
301
302 if ( isset( $this->fullResultCache[$table] ) ) {
303 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
304 wfDebug( __METHOD__ . ": got from full result cache\n" );
305
306 return $cacheEntry['batches'];
307 }
308
309 // 3) ... fallback to memcached ...
310
311 global $wgMemc;
312
313 $memcKey = wfMemcKey(
314 'backlinks',
315 md5( $this->title->getPrefixedDBkey() ),
316 $table,
317 $batchSize
318 );
319
320 $memcValue = $wgMemc->get( $memcKey );
321
322 if ( is_array( $memcValue ) ) {
323 $cacheEntry = $memcValue;
324 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
325
326 return $cacheEntry['batches'];
327 }
328
329
330 // 4) ... finally fetch from the slow database :(
331
332 $this->getLinks( $table );
333 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
334 // Save to memcached
335 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
336
337 wfDebug( __METHOD__ . ": got from database\n" );
338 return $cacheEntry['batches'];
339 }
340
341 /**
342 * Partition a DB result with backlinks in it into batches
343 * @param $res ResultWrapper database result
344 * @param $batchSize integer
345 * @return array @see
346 */
347 protected function partitionResult( $res, $batchSize ) {
348 $batches = array();
349 $numRows = $res->numRows();
350 $numBatches = ceil( $numRows / $batchSize );
351
352 for ( $i = 0; $i < $numBatches; $i++ ) {
353 if ( $i == 0 ) {
354 $start = false;
355 } else {
356 $rowNum = intval( $numRows * $i / $numBatches );
357 $res->seek( $rowNum );
358 $row = $res->fetchObject();
359 $start = $row->page_id;
360 }
361
362 if ( $i == $numBatches - 1 ) {
363 $end = false;
364 } else {
365 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
366 $res->seek( $rowNum );
367 $row = $res->fetchObject();
368 $end = $row->page_id - 1;
369 }
370
371 # Sanity check order
372 if ( $start && $end && $start > $end ) {
373 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
374 }
375
376 $batches[] = array( $start, $end );
377 }
378
379 return array( 'numRows' => $numRows, 'batches' => $batches );
380 }
381 }