Merge "CologneBlue rewrite: adjust the quickbar contents to 2012"
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2 /**
3 * Class for fetching backlink lists, approximate backlink counts and
4 * partitions.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @author Tim Starling
23 * @copyright © 2009, Tim Starling, Domas Mituzas
24 * @copyright © 2010, Max Sem
25 * @copyright © 2011, Antoine Musso
26 */
27
28 /**
29 * Class for fetching backlink lists, approximate backlink counts and
30 * partitions. This is a shared cache.
31 *
32 * Instances of this class should typically be fetched with the method
33 * $title->getBacklinkCache().
34 *
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.
38 *
39 * Introduced by r47317
40 *
41 * @internal documentation reviewed on 18 Mar 2011 by hashar
42 */
43 class BacklinkCache {
44 /** @var ProcessCacheLRU */
45 protected static $cache;
46
47 /**
48 * Multi dimensions array representing batches. Keys are:
49 * > (string) links table name
50 * > 'numRows' : Number of rows for this link table
51 * > 'batches' : array( $start, $end )
52 *
53 * @see BacklinkCache::partitionResult()
54 *
55 * Cleared with BacklinkCache::clear()
56 */
57 protected $partitionCache = array();
58
59 /**
60 * Contains the whole links from a database result.
61 * This is raw data that will be partitioned in $partitionCache
62 *
63 * Initialized with BacklinkCache::getLinks()
64 * Cleared with BacklinkCache::clear()
65 */
66 protected $fullResultCache = array();
67
68 /**
69 * Local copy of a database object.
70 *
71 * Accessor: BacklinkCache::getDB()
72 * Mutator : BacklinkCache::setDB()
73 * Cleared with BacklinkCache::clear()
74 */
75 protected $db;
76
77 /**
78 * Local copy of a Title object
79 */
80 protected $title;
81
82 const CACHE_EXPIRY = 3600;
83
84 /**
85 * Create a new BacklinkCache
86 *
87 * @param Title $title : Title object to create a backlink cache for
88 */
89 public function __construct( Title $title ) {
90 $this->title = $title;
91 }
92
93 /**
94 * Create a new BacklinkCache or reuse any existing one.
95 * Currently, only one cache instance can exist; callers that
96 * need multiple backlink cache objects should keep them in scope.
97 *
98 * @param Title $title : Title object to get a backlink cache for
99 * @return BacklinkCache
100 */
101 public static function get( Title $title ) {
102 if ( !self::$cache ) { // init cache
103 self::$cache = new ProcessCacheLRU( 1 );
104 }
105 $dbKey = $title->getPrefixedDBkey();
106 if ( !self::$cache->has( $dbKey, 'obj' ) ) {
107 self::$cache->set( $dbKey, 'obj', new self( $title ) );
108 }
109 return self::$cache->get( $dbKey, 'obj' );
110 }
111
112 /**
113 * Serialization handler, diasallows to serialize the database to prevent
114 * failures after this class is deserialized from cache with dead DB
115 * connection.
116 *
117 * @return array
118 */
119 function __sleep() {
120 return array( 'partitionCache', 'fullResultCache', 'title' );
121 }
122
123 /**
124 * Clear locally stored data and database object.
125 */
126 public function clear() {
127 $this->partitionCache = array();
128 $this->fullResultCache = array();
129 unset( $this->db );
130 }
131
132 /**
133 * Set the Database object to use
134 *
135 * @param $db DatabaseBase
136 */
137 public function setDB( $db ) {
138 $this->db = $db;
139 }
140
141 /**
142 * Get the slave connection to the database
143 * When non existing, will initialize the connection.
144 * @return DatabaseBase object
145 */
146 protected function getDB() {
147 if ( !isset( $this->db ) ) {
148 $this->db = wfGetDB( DB_SLAVE );
149 }
150
151 return $this->db;
152 }
153
154 /**
155 * Get the backlinks for a given table. Cached in process memory only.
156 * @param $table String
157 * @param $startId Integer or false
158 * @param $endId Integer or false
159 * @return TitleArrayFromResult
160 */
161 public function getLinks( $table, $startId = false, $endId = false ) {
162 wfProfileIn( __METHOD__ );
163
164 $fromField = $this->getPrefix( $table ) . '_from';
165
166 if ( $startId || $endId ) {
167 // Partial range, not cached
168 wfDebug( __METHOD__ . ": from DB (uncacheable range)\n" );
169 $conds = $this->getConditions( $table );
170
171 // Use the from field in the condition rather than the joined page_id,
172 // because databases are stupid and don't necessarily propagate indexes.
173 if ( $startId ) {
174 $conds[] = "$fromField >= " . intval( $startId );
175 }
176
177 if ( $endId ) {
178 $conds[] = "$fromField <= " . intval( $endId );
179 }
180
181 $res = $this->getDB()->select(
182 array( $table, 'page' ),
183 array( 'page_namespace', 'page_title', 'page_id' ),
184 $conds,
185 __METHOD__,
186 array(
187 'STRAIGHT_JOIN',
188 'ORDER BY' => $fromField
189 ) );
190 $ta = TitleArray::newFromResult( $res );
191
192 wfProfileOut( __METHOD__ );
193 return $ta;
194 }
195
196 // @todo FIXME: Make this a function?
197 if ( !isset( $this->fullResultCache[$table] ) ) {
198 wfDebug( __METHOD__ . ": from DB\n" );
199 $res = $this->getDB()->select(
200 array( $table, 'page' ),
201 array( 'page_namespace', 'page_title', 'page_id' ),
202 $this->getConditions( $table ),
203 __METHOD__,
204 array(
205 'STRAIGHT_JOIN',
206 'ORDER BY' => $fromField,
207 ) );
208 $this->fullResultCache[$table] = $res;
209 }
210
211 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
212
213 wfProfileOut( __METHOD__ );
214 return $ta;
215 }
216
217 /**
218 * Get the field name prefix for a given table
219 * @param $table String
220 * @return null|string
221 */
222 protected function getPrefix( $table ) {
223 static $prefixes = array(
224 'pagelinks' => 'pl',
225 'imagelinks' => 'il',
226 'categorylinks' => 'cl',
227 'templatelinks' => 'tl',
228 'redirect' => 'rd',
229 );
230
231 if ( isset( $prefixes[$table] ) ) {
232 return $prefixes[$table];
233 } else {
234 $prefix = null;
235 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
236 if( $prefix ) {
237 return $prefix;
238 } else {
239 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
240 }
241 }
242 }
243
244 /**
245 * Get the SQL condition array for selecting backlinks, with a join
246 * on the page table.
247 * @param $table String
248 * @return array|null
249 */
250 protected function getConditions( $table ) {
251 $prefix = $this->getPrefix( $table );
252
253 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
254 // they could be moved up for nicer case statements
255 switch ( $table ) {
256 case 'pagelinks':
257 case 'templatelinks':
258 $conds = array(
259 "{$prefix}_namespace" => $this->title->getNamespace(),
260 "{$prefix}_title" => $this->title->getDBkey(),
261 "page_id={$prefix}_from"
262 );
263 break;
264 case 'redirect':
265 $conds = array(
266 "{$prefix}_namespace" => $this->title->getNamespace(),
267 "{$prefix}_title" => $this->title->getDBkey(),
268 $this->getDb()->makeList( array(
269 "{$prefix}_interwiki = ''",
270 "{$prefix}_interwiki is null",
271 ), LIST_OR ),
272 "page_id={$prefix}_from"
273 );
274 break;
275 case 'imagelinks':
276 $conds = array(
277 'il_to' => $this->title->getDBkey(),
278 'page_id=il_from'
279 );
280 break;
281 case 'categorylinks':
282 $conds = array(
283 'cl_to' => $this->title->getDBkey(),
284 'page_id=cl_from',
285 );
286 break;
287 default:
288 $conds = null;
289 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
290 if( !$conds ) {
291 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
292 }
293 }
294
295 return $conds;
296 }
297
298 /**
299 * Get the approximate number of backlinks
300 * @param $table String
301 * @return integer
302 */
303 public function getNumLinks( $table ) {
304 if ( isset( $this->fullResultCache[$table] ) ) {
305 return $this->fullResultCache[$table]->numRows();
306 }
307
308 if ( isset( $this->partitionCache[$table] ) ) {
309 $entry = reset( $this->partitionCache[$table] );
310 return $entry['numRows'];
311 }
312
313 $titleArray = $this->getLinks( $table );
314
315 return $titleArray->count();
316 }
317
318 /**
319 * Partition the backlinks into batches.
320 * Returns an array giving the start and end of each range. The first
321 * batch has a start of false, and the last batch has an end of false.
322 *
323 * @param $table String: the links table name
324 * @param $batchSize Integer
325 * @return Array
326 */
327 public function partition( $table, $batchSize ) {
328
329 // 1) try partition cache ...
330
331 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
332 wfDebug( __METHOD__ . ": got from partition cache\n" );
333 return $this->partitionCache[$table][$batchSize]['batches'];
334 }
335
336 $this->partitionCache[$table][$batchSize] = false;
337 $cacheEntry =& $this->partitionCache[$table][$batchSize];
338
339 // 2) ... then try full result cache ...
340
341 if ( isset( $this->fullResultCache[$table] ) ) {
342 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
343 wfDebug( __METHOD__ . ": got from full result cache\n" );
344
345 return $cacheEntry['batches'];
346 }
347
348 // 3) ... fallback to memcached ...
349
350 global $wgMemc;
351
352 $memcKey = wfMemcKey(
353 'backlinks',
354 md5( $this->title->getPrefixedDBkey() ),
355 $table,
356 $batchSize
357 );
358
359 $memcValue = $wgMemc->get( $memcKey );
360
361 if ( is_array( $memcValue ) ) {
362 $cacheEntry = $memcValue;
363 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
364
365 return $cacheEntry['batches'];
366 }
367
368
369 // 4) ... finally fetch from the slow database :(
370
371 $this->getLinks( $table );
372 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
373 // Save to memcached
374 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
375
376 wfDebug( __METHOD__ . ": got from database\n" );
377 return $cacheEntry['batches'];
378 }
379
380 /**
381 * Partition a DB result with backlinks in it into batches
382 * @param $res ResultWrapper database result
383 * @param $batchSize integer
384 * @return array @see
385 */
386 protected function partitionResult( $res, $batchSize ) {
387 $batches = array();
388 $numRows = $res->numRows();
389 $numBatches = ceil( $numRows / $batchSize );
390
391 for ( $i = 0; $i < $numBatches; $i++ ) {
392 if ( $i == 0 ) {
393 $start = false;
394 } else {
395 $rowNum = intval( $numRows * $i / $numBatches );
396 $res->seek( $rowNum );
397 $row = $res->fetchObject();
398 $start = $row->page_id;
399 }
400
401 if ( $i == $numBatches - 1 ) {
402 $end = false;
403 } else {
404 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
405 $res->seek( $rowNum );
406 $row = $res->fetchObject();
407 $end = $row->page_id - 1;
408 }
409
410 # Sanity check order
411 if ( $start && $end && $start > $end ) {
412 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
413 }
414
415 $batches[] = array( $start, $end );
416 }
417
418 return array( 'numRows' => $numRows, 'batches' => $batches );
419 }
420 }