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