BacklinkCache: explicit properties visibility
[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, Ashar Voultoiz
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 function __sleep() {
80 return array( 'partitionCache', 'fullResultCache', 'title' );
81 }
82
83 /**
84 * Clear locally stored data and database object.
85 */
86 public function clear() {
87 $this->partitionCache = array();
88 $this->fullResultCache = array();
89 unset( $this->db );
90 }
91
92 /**
93 * Set the Database object to use
94 */
95 public function setDB( $db ) {
96 $this->db = $db;
97 }
98
99 /**
100 * Get the slave connection to the database
101 * When non existing, will initialize the connection.
102 * @return Database object
103 */
104 protected function getDB() {
105 if ( !isset( $this->db ) ) {
106 $this->db = wfGetDB( DB_SLAVE );
107 }
108
109 return $this->db;
110 }
111
112 /**
113 * Get the backlinks for a given table. Cached in process memory only.
114 * @param $table String
115 * @param $startId Integer or false
116 * @param $endId Integer or false
117 * @return TitleArray
118 */
119 public function getLinks( $table, $startId = false, $endId = false ) {
120 wfProfileIn( __METHOD__ );
121
122 $fromField = $this->getPrefix( $table ) . '_from';
123
124 if ( $startId || $endId ) {
125 // Partial range, not cached
126 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
127 $conds = $this->getConditions( $table );
128
129 // Use the from field in the condition rather than the joined page_id,
130 // because databases are stupid and don't necessarily propagate indexes.
131 if ( $startId ) {
132 $conds[] = "$fromField >= " . intval( $startId );
133 }
134
135 if ( $endId ) {
136 $conds[] = "$fromField <= " . intval( $endId );
137 }
138
139 $res = $this->getDB()->select(
140 array( $table, 'page' ),
141 array( 'page_namespace', 'page_title', 'page_id' ),
142 $conds,
143 __METHOD__,
144 array(
145 'STRAIGHT_JOIN',
146 'ORDER BY' => $fromField
147 ) );
148 $ta = TitleArray::newFromResult( $res );
149
150 wfProfileOut( __METHOD__ );
151 return $ta;
152 }
153
154 // FIXME : make this a function?
155 if ( !isset( $this->fullResultCache[$table] ) ) {
156 wfDebug( __METHOD__ . ": from DB\n" );
157 $res = $this->getDB()->select(
158 array( $table, 'page' ),
159 array( 'page_namespace', 'page_title', 'page_id' ),
160 $this->getConditions( $table ),
161 __METHOD__,
162 array(
163 'STRAIGHT_JOIN',
164 'ORDER BY' => $fromField,
165 ) );
166 $this->fullResultCache[$table] = $res;
167 }
168
169 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
170
171 wfProfileOut( __METHOD__ );
172 return $ta;
173 }
174
175 /**
176 * Get the field name prefix for a given table
177 * @param $table String
178 */
179 protected function getPrefix( $table ) {
180 static $prefixes = array(
181 'pagelinks' => 'pl',
182 'imagelinks' => 'il',
183 'categorylinks' => 'cl',
184 'templatelinks' => 'tl',
185 'redirect' => 'rd',
186 );
187
188 if ( isset( $prefixes[$table] ) ) {
189 return $prefixes[$table];
190 } else {
191 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
192 }
193 }
194
195 /**
196 * Get the SQL condition array for selecting backlinks, with a join
197 * on the page table.
198 * @param $table String
199 */
200 protected function getConditions( $table ) {
201 $prefix = $this->getPrefix( $table );
202
203 // FIXME imagelinks and categorylinks do not rely on getNamespace,
204 // they could be moved up for nicer case statements
205 switch ( $table ) {
206 case 'pagelinks':
207 case 'templatelinks':
208 case 'redirect':
209 $conds = array(
210 "{$prefix}_namespace" => $this->title->getNamespace(),
211 "{$prefix}_title" => $this->title->getDBkey(),
212 "page_id={$prefix}_from"
213 );
214 break;
215 case 'imagelinks':
216 $conds = array(
217 'il_to' => $this->title->getDBkey(),
218 'page_id=il_from'
219 );
220 break;
221 case 'categorylinks':
222 $conds = array(
223 'cl_to' => $this->title->getDBkey(),
224 'page_id=cl_from',
225 );
226 break;
227 default:
228 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
229 }
230
231 return $conds;
232 }
233
234 /**
235 * Get the approximate number of backlinks
236 * @param $table String
237 * @return integer
238 */
239 public function getNumLinks( $table ) {
240 if ( isset( $this->fullResultCache[$table] ) ) {
241 return $this->fullResultCache[$table]->numRows();
242 }
243
244 if ( isset( $this->partitionCache[$table] ) ) {
245 $entry = reset( $this->partitionCache[$table] );
246 return $entry['numRows'];
247 }
248
249 $titleArray = $this->getLinks( $table );
250
251 return $titleArray->count();
252 }
253
254 /**
255 * Partition the backlinks into batches.
256 * Returns an array giving the start and end of each range. The firsti
257 * batch has a start of false, and the last batch has an end of false.
258 *
259 * @param $table String: the links table name
260 * @param $batchSize Integer
261 * @return Array
262 */
263 public function partition( $table, $batchSize ) {
264
265 // 1) try this per process cache first
266
267 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
268 wfDebug( __METHOD__ . ": got from partition cache\n" );
269 return $this->partitionCache[$table][$batchSize]['batches'];
270 }
271
272 $this->partitionCache[$table][$batchSize] = false;
273 $cacheEntry =& $this->partitionCache[$table][$batchSize];
274
275
276 // 2) try full result cache
277
278 if ( isset( $this->fullResultCache[$table] ) ) {
279 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
280 wfDebug( __METHOD__ . ": got from full result cache\n" );
281
282 return $cacheEntry['batches'];
283 }
284
285
286 // 3) ... fallback to memcached ...
287
288 global $wgMemc;
289
290 $memcKey = wfMemcKey(
291 'backlinks',
292 md5( $this->title->getPrefixedDBkey() ),
293 $table,
294 $batchSize
295 );
296
297 $memcValue = $wgMemc->get( $memcKey );
298
299 if ( is_array( $memcValue ) ) {
300 $cacheEntry = $memcValue;
301 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
302
303 return $cacheEntry['batches'];
304 }
305
306
307 // 4) ... finally fetch from the slow database :(
308
309 $this->getLinks( $table );
310 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
311 // Save to memcached
312 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
313
314 wfDebug( __METHOD__ . ": got from database\n" );
315 return $cacheEntry['batches'];
316 }
317
318 /**
319 * Partition a DB result with backlinks in it into batches
320 * @param $res database result
321 * @param $batchSize integer
322 * @return array @see
323 */
324 protected function partitionResult( $res, $batchSize ) {
325 $batches = array();
326 $numRows = $res->numRows();
327 $numBatches = ceil( $numRows / $batchSize );
328
329 for ( $i = 0; $i < $numBatches; $i++ ) {
330 if ( $i == 0 ) {
331 $start = false;
332 } else {
333 $rowNum = intval( $numRows * $i / $numBatches );
334 $res->seek( $rowNum );
335 $row = $res->fetchObject();
336 $start = $row->page_id;
337 }
338
339 if ( $i == $numBatches - 1 ) {
340 $end = false;
341 } else {
342 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
343 $res->seek( $rowNum );
344 $row = $res->fetchObject();
345 $end = $row->page_id - 1;
346 }
347
348 # Sanity check order
349 if ( $start && $end && $start > $end ) {
350 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
351 }
352
353 $batches[] = array( $start, $end );
354 }
355
356 return array( 'numRows' => $numRows, 'batches' => $batches );
357 }
358 }