Fix bug in BacklinkCache: the lack of an ORDER BY clause in getLinks(), combined...
[lhc/web/wiklou.git] / includes / BacklinkCache.php
1 <?php
2
3 /**
4 * Class for fetching backlink lists, approximate backlink counts and partitions.
5 * Instances of this class should typically be fetched with $title->getBacklinkCache().
6 *
7 * Ideally you should only get your backlinks from here when you think there is some
8 * advantage in caching them. Otherwise it's just a waste of memory.
9 */
10 class BacklinkCache {
11 var $partitionCache = array();
12 var $fullResultCache = array();
13 var $title;
14 var $db;
15
16 const CACHE_EXPIRY = 3600;
17
18 /**
19 * Create a new BacklinkCache
20 */
21 function __construct( $title ) {
22 $this->title = $title;
23 }
24
25 /**
26 * Clear locally stored data
27 */
28 function clear() {
29 $this->partitionCache = array();
30 $this->fullResultCache = array();
31 unset( $this->db );
32 }
33
34 /**
35 * Set the Database object to use
36 */
37 public function setDB( $db ) {
38 $this->db = $db;
39 }
40
41 protected function getDB() {
42 if ( !isset( $this->db ) ) {
43 $this->db = wfGetDB( DB_SLAVE );
44 }
45 return $this->db;
46 }
47
48 /**
49 * Get the backlinks for a given table. Cached in process memory only.
50 * @param string $table
51 * @return TitleArray
52 */
53 public function getLinks( $table, $startId = false, $endId = false ) {
54 wfProfileIn( __METHOD__ );
55
56 $fromField = $this->getPrefix( $table ) . '_from';
57 if ( $startId || $endId ) {
58 // Partial range, not cached
59 wfDebug( __METHOD__.": from DB (uncacheable range)\n" );
60 $conds = $this->getConditions( $table );
61 // Use the from field in the condition rather than the joined page_id,
62 // because databases are stupid and don't necessarily propagate indexes.
63 if ( $startId ) {
64 $conds[] = "$fromField >= " . intval( $startId );
65 }
66 if ( $endId ) {
67 $conds[] = "$fromField <= " . intval( $endId );
68 }
69 $res = $this->getDB()->select(
70 array( $table, 'page' ),
71 array( 'page_namespace', 'page_title', 'page_id'),
72 $conds,
73 __METHOD__,
74 array(
75 'STRAIGHT_JOIN',
76 'ORDER BY' => $fromField
77 ) );
78 $ta = TitleArray::newFromResult( $res );
79 wfProfileOut( __METHOD__ );
80 return $ta;
81 }
82
83 if ( !isset( $this->fullResultCache[$table] ) ) {
84 wfDebug( __METHOD__.": from DB\n" );
85 $res = $this->getDB()->select(
86 array( $table, 'page' ),
87 array( 'page_namespace', 'page_title', 'page_id' ),
88 $this->getConditions( $table ),
89 __METHOD__,
90 array(
91 'STRAIGHT_JOIN',
92 'ORDER BY' => $fromField,
93 ) );
94 $this->fullResultCache[$table] = $res;
95 }
96 $ta = TitleArray::newFromResult( $this->fullResultCache[$table] );
97 wfProfileOut( __METHOD__ );
98 return $ta;
99 }
100
101 /**
102 * Get the field name prefix for a given table
103 */
104 protected function getPrefix( $table ) {
105 static $prefixes = array(
106 'pagelinks' => 'pl',
107 'imagelinks' => 'il',
108 'categorylinks' => 'cl',
109 'templatelinks' => 'tl',
110 'redirect' => 'rd',
111 );
112 if ( isset( $prefixes[$table] ) ) {
113 return $prefixes[$table];
114 } else {
115 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
116 }
117 }
118
119 /**
120 * Get the SQL condition array for selecting backlinks, with a join on the page table
121 */
122 protected function getConditions( $table ) {
123 $prefix = $this->getPrefix( $table );
124 switch ( $table ) {
125 case 'pagelinks':
126 case 'templatelinks':
127 case 'redirect':
128 $conds = array(
129 "{$prefix}_namespace" => $this->title->getNamespace(),
130 "{$prefix}_title" => $this->title->getDBkey(),
131 "page_id={$prefix}_from"
132 );
133 break;
134 case 'imagelinks':
135 $conds = array(
136 'il_to' => $this->title->getDBkey(),
137 'page_id=il_from'
138 );
139 break;
140 case 'categorylinks':
141 $conds = array(
142 'cl_to' => $this->title->getDBkey(),
143 'page_id=cl_from',
144 );
145 break;
146 default:
147 throw new MWException( "Invalid table \"$table\" in " . __CLASS__ );
148 }
149 return $conds;
150 }
151
152 /**
153 * Get the approximate number of backlinks
154 */
155 public function getNumLinks( $table ) {
156 if ( isset( $this->fullResultCache[$table] ) ) {
157 return $this->fullResultCache[$table]->numRows();
158 }
159 if ( isset( $this->partitionCache[$table] ) ) {
160 $entry = reset( $this->partitionCache[$table] );
161 return $entry['numRows'];
162 }
163 $titleArray = $this->getLinks( $table );
164 return $titleArray->count();
165 }
166
167 /**
168 * Partition the backlinks into batches.
169 * Returns an array giving the start and end of each range. The first batch has
170 * a start of false, and the last batch has an end of false.
171 *
172 * @param string $table The links table name
173 * @param integer $batchSize
174 * @return array
175 */
176 public function partition( $table, $batchSize ) {
177 // Try cache
178 if ( isset( $this->partitionCache[$table][$batchSize] ) ) {
179 wfDebug( __METHOD__.": got from partition cache\n" );
180 return $this->partitionCache[$table][$batchSize]['batches'];
181 }
182 $this->partitionCache[$table][$batchSize] = false;
183 $cacheEntry =& $this->partitionCache[$table][$batchSize];
184
185 // Try full result cache
186 if ( isset( $this->fullResultCache[$table] ) ) {
187 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
188 wfDebug( __METHOD__.": got from full result cache\n" );
189 return $cacheEntry['batches'];
190 }
191 // Try memcached
192 global $wgMemc;
193 $memcKey = wfMemcKey( 'backlinks', md5( $this->title->getPrefixedDBkey() ),
194 $table, $batchSize );
195 $memcValue = $wgMemc->get( $memcKey );
196 if ( is_array( $memcValue ) ) {
197 $cacheEntry = $memcValue;
198 wfDebug( __METHOD__.": got from memcached $memcKey\n" );
199 return $cacheEntry['batches'];
200 }
201 // Fetch from database
202 $this->getLinks( $table );
203 $cacheEntry = $this->partitionResult( $this->fullResultCache[$table], $batchSize );
204 // Save to memcached
205 $wgMemc->set( $memcKey, $cacheEntry, self::CACHE_EXPIRY );
206 wfDebug( __METHOD__.": got from database\n" );
207 return $cacheEntry['batches'];
208 }
209
210 /**
211 * Partition a DB result with backlinks in it into batches
212 */
213 protected function partitionResult( $res, $batchSize ) {
214 $batches = array();
215 $numRows = $res->numRows();
216 $numBatches = ceil( $numRows / $batchSize );
217 for ( $i = 0; $i < $numBatches; $i++ ) {
218 if ( $i == 0 ) {
219 $start = false;
220 } else {
221 $rowNum = intval( $numRows * $i / $numBatches );
222 $res->seek( $rowNum );
223 $row = $res->fetchObject();
224 $start = $row->page_id;
225 }
226 if ( $i == $numBatches - 1 ) {
227 $end = false;
228 } else {
229 $rowNum = intval( $numRows * ( $i + 1 ) / $numBatches );
230 $res->seek( $rowNum );
231 $row = $res->fetchObject();
232 $end = $row->page_id - 1;
233 }
234
235 # Sanity check order
236 if ( $start && $end && $start > $end ) {
237 throw new MWException( __METHOD__.': Internal error: query result out of order' );
238 }
239
240 $batches[] = array( $start, $end );
241 }
242 return array( 'numRows' => $numRows, 'batches' => $batches );
243 }
244 }