Use LogFormatter to format log entries.
[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 * @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 Database 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 distant backtemplatelinks for the table globaltemplatelinks. Cached in process memory only.
181 * @return ResultWrapper list of distant pages that use the local title
182 */
183 public function getDistantTemplateLinks( ) {
184 global $wgGlobalDatabase, $wgLocalInterwiki;
185
186 $dbr = wfGetDB( DB_SLAVE, array(), $wgGlobalDatabase );
187 $res = $dbr->select(
188 array( 'globaltemplatelinks', 'globalinterwiki' ),
189 array( 'gtl_from_wiki', 'gtl_from_page', 'gtl_from_title', 'giw_prefix' ),
190 array( 'gtl_to_prefix' => $wgLocalInterwiki, 'gtl_to_title' => $this->title->getDBkey( ) ),
191 __METHOD__,
192 null,
193 array( 'gtl_from_wiki = giw_wikiid' )
194 );
195 return $res;
196 }
197
198 /**
199 * Get the field name prefix for a given table
200 * @param $table String
201 */
202 protected function getPrefix( $table ) {
203 static $prefixes = array(
204 'pagelinks' => 'pl',
205 'imagelinks' => 'il',
206 'categorylinks' => 'cl',
207 'templatelinks' => 'tl',
208 'redirect' => 'rd',
209 'globaltemplatelinks' => 'gtl',
210 );
211
212 if ( isset( $prefixes[$table] ) ) {
213 return $prefixes[$table];
214 } else {
215 $prefix = null;
216 wfRunHooks( 'BacklinkCacheGetPrefix', array( $table, &$prefix ) );
217 if( $prefix ) {
218 return $prefix;
219 } else {
220 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
221 }
222 }
223 }
224
225 /**
226 * Get the SQL condition array for selecting backlinks, with a join
227 * on the page table.
228 * @param $table String
229 */
230 protected function getConditions( $table ) {
231 $prefix = $this->getPrefix( $table );
232
233 // @todo FIXME: imagelinks and categorylinks do not rely on getNamespace,
234 // they could be moved up for nicer case statements
235 switch ( $table ) {
236 case 'pagelinks':
237 case 'templatelinks':
238 $conds = array(
239 "{$prefix}_namespace" => $this->title->getNamespace(),
240 "{$prefix}_title" => $this->title->getDBkey(),
241 "page_id={$prefix}_from"
242 );
243 break;
244 case 'redirect':
245 $conds = array(
246 "{$prefix}_namespace" => $this->title->getNamespace(),
247 "{$prefix}_title" => $this->title->getDBkey(),
248 $this->getDb()->makeList( array(
249 "{$prefix}_interwiki = ''",
250 "{$prefix}_interwiki is null",
251 ), LIST_OR ),
252 "page_id={$prefix}_from"
253 );
254 break;
255 case 'imagelinks':
256 $conds = array(
257 'il_to' => $this->title->getDBkey(),
258 'page_id=il_from'
259 );
260 break;
261 case 'categorylinks':
262 $conds = array(
263 'cl_to' => $this->title->getDBkey(),
264 'page_id=cl_from',
265 );
266 break;
267 default:
268 $conds = null;
269 wfRunHooks( 'BacklinkCacheGetConditions', array( $table, $this->title, &$conds ) );
270 if( !$conds )
271 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
272 }
273
274 return $conds;
275 }
276
277 /**
278 * Get the approximate number of backlinks
279 * @param $table String
280 * @return integer
281 */
282 public function getNumLinks( $table ) {
283 if ( isset( $this->fullResultCache[$table] ) ) {
284 return $this->fullResultCache[$table]->numRows();
285 }
286
287 if ( isset( $this->partitionCache[$table] ) ) {
288 $entry = reset( $this->partitionCache[$table] );
289 return $entry['numRows'];
290 }
291
292 $titleArray = $this->getLinks( $table );
293
294 return $titleArray->count();
295 }
296
297 /**
298 * Partition the backlinks into batches.
299 * Returns an array giving the start and end of each range. The first
300 * batch has a start of false, and the last batch has an end of false.
301 *
302 * @param $table String: the links table name
303 * @param $batchSize Integer
304 * @return Array
305 */
306 public function partition( $table, $batchSize ) {
307
308 // 1) try partition cache ...
309
310 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
311 wfDebug( __METHOD__ . ": got from partition cache\n" );
312 return $this->partitionCache[$table][$batchSize]['batches'];
313 }
314
315 $this->partitionCache[$table][$batchSize] = false;
316 $cacheEntry =& $this->partitionCache[$table][$batchSize];
317
318 // 2) ... then try full result cache ...
319
320 if ( isset( $this->fullResultCache[$table] ) ) {
321 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
322 wfDebug( __METHOD__ . ": got from full result cache\n" );
323
324 return $cacheEntry['batches'];
325 }
326
327 // 3) ... fallback to memcached ...
328
329 global $wgMemc;
330
331 $memcKey = wfMemcKey(
332 'backlinks',
333 md5( $this->title->getPrefixedDBkey() ),
334 $table,
335 $batchSize
336 );
337
338 $memcValue = $wgMemc->get( $memcKey );
339
340 if ( is_array( $memcValue ) ) {
341 $cacheEntry = $memcValue;
342 wfDebug( __METHOD__ . ": got from memcached $memcKey\n" );
343
344 return $cacheEntry['batches'];
345 }
346
347
348 // 4) ... finally fetch from the slow database :(
349
350 $this->getLinks( $table );
351 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
352 // Save to memcached
353 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
354
355 wfDebug( __METHOD__ . ": got from database\n" );
356 return $cacheEntry['batches'];
357 }
358
359 /**
360 * Partition a DB result with backlinks in it into batches
361 * @param $res ResultWrapper database result
362 * @param $batchSize integer
363 * @return array @see
364 */
365 protected function partitionResult( $res, $batchSize ) {
366 $batches = array();
367 $numRows = $res->numRows();
368 $numBatches = ceil( $numRows / $batchSize );
369
370 for ( $i = 0; $i < $numBatches; $i++ ) {
371 if ( $i == 0 ) {
372 $start = false;
373 } else {
374 $rowNum = intval( $numRows * $i / $numBatches );
375 $res->seek( $rowNum );
376 $row = $res->fetchObject();
377 $start = $row->page_id;
378 }
379
380 if ( $i == $numBatches - 1 ) {
381 $end = false;
382 } else {
383 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
384 $res->seek( $rowNum );
385 $row = $res->fetchObject();
386 $end = $row->page_id - 1;
387 }
388
389 # Sanity check order
390 if ( $start && $end && $start > $end ) {
391 throw new MWException( __METHOD__ . ': Internal error: query result out of order' );
392 }
393
394 $batches[] = array( $start, $end );
395 }
396
397 return array( 'numRows' => $numRows, 'batches' => $batches );
398 }
399 }