Merge "Clarify userrights-conflict"
[lhc/web/wiklou.git] / includes / specials / SpecialRandomInCategory.php
1 <?php
2 /**
3 * Implements Special:RandomInCategory
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @author Brian Wolff
23 */
24
25 /**
26 * Special page to direct the user to a random page
27 *
28 * @note The method used here is rather biased. It is assumed that
29 * the use of this page will be people wanting to get a random page
30 * out of a maintenance category, to fix it up. The method used by
31 * this page should return different pages in an unpredictable fashion
32 * which is hoped to be sufficient, even if some pages are selected
33 * more often than others.
34 *
35 * A more unbiased method could be achieved by adding a cl_random field
36 * to the categorylinks table.
37 *
38 * The method used here is as follows:
39 * * Find the smallest and largest timestamp in the category
40 * * Pick a random timestamp in between
41 * * Pick an offset between 0 and 30
42 * * Get the offset'ed page that is newer than the timestamp selected
43 * The offset is meant to counter the fact the timestamps aren't usually
44 * uniformly distributed, so if things are very non-uniform at least we
45 * won't have the same page selected 99% of the time.
46 *
47 * @ingroup SpecialPage
48 */
49 class SpecialRandomInCategory extends SpecialPage {
50 protected $extra = array(); // Extra SQL statements
51 protected $category = false; // Title object of category
52 protected $maxOffset = 30; // Max amount to fudge randomness by.
53 private $maxTimestamp = null;
54 private $minTimestamp = null;
55
56 public function __construct( $name = 'RandomInCategory' ) {
57 parent::__construct( $name );
58 }
59
60 /**
61 * Set which category to use.
62 * @param Title $cat
63 */
64 public function setCategory( Title $cat ) {
65 $this->category = $cat;
66 $this->maxTimestamp = null;
67 $this->minTimestamp = null;
68 }
69
70 public function execute( $par ) {
71 $cat = false;
72
73 $categoryStr = $this->getRequest()->getText( 'category', $par );
74
75 if ( $categoryStr ) {
76 $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
77 }
78
79 if ( $cat ) {
80 $this->setCategory( $cat );
81 }
82
83
84 if ( !$this->category && $categoryStr ) {
85 $this->setHeaders();
86 $this->getOutput()->addWikiMsg( 'randomincategory-invalidcategory',
87 wfEscapeWikiText( $categoryStr ) );
88
89 return;
90 } elseif ( !$this->category ) {
91 $this->setHeaders();
92 $input = Html::input( 'category' );
93 $submitText = $this->msg( 'randomincategory-selectcategory-submit' )->text();
94 $submit = Html::input( '', $submitText, 'submit' );
95
96 $msg = $this->msg( 'randomincategory-selectcategory' );
97 $form = Html::rawElement( 'form', array( 'action' => $this->getTitle()->getLocalUrl() ),
98 $msg->rawParams( $input, $submit )->parse()
99 );
100 $this->getOutput()->addHtml( $form );
101
102 return;
103 }
104
105 $title = $this->getRandomTitle();
106
107 if ( is_null( $title ) ) {
108 $this->setHeaders();
109 $this->getOutput()->addWikiMsg( 'randomincategory-nopages',
110 $this->category->getText() );
111
112 return;
113 }
114
115 $query = $this->getRequest()->getValues();
116 unset( $query['title'] );
117 unset( $query['category'] );
118 $this->getOutput()->redirect( $title->getFullURL( $query ) );
119 }
120
121 /**
122 * Choose a random title.
123 * @return Title object (or null if nothing to choose from)
124 */
125 public function getRandomTitle() {
126 // Convert to float, since we do math with the random number.
127 $rand = (float) wfRandom();
128 $title = null;
129
130 // Given that timestamps are rather unevenly distributed, we also
131 // use an offset between 0 and 30 to make any biases less noticeable.
132 $offset = mt_rand( 0, $this->maxOffset );
133
134 if ( mt_rand( 0, 1 ) ) {
135 $up = true;
136 } else {
137 $up = false;
138 }
139
140 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
141
142 // Try again without the timestamp offset (wrap around the end)
143 if ( !$row ) {
144 $row = $this->selectRandomPageFromDB( false, $offset, $up );
145 }
146
147 // Maybe the category is really small and offset too high
148 if ( !$row ) {
149 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
150 }
151
152 // Just get the first entry.
153 if ( !$row ) {
154 $row = $this->selectRandomPageFromDB( false, 0, true );
155 }
156
157 if ( $row ) {
158 return Title::makeTitle( $row->page_namespace, $row->page_title );
159 }
160
161 return null;
162 }
163
164 /**
165 * @param float $rand Random number between 0 and 1
166 * @param int $offset Extra offset to fudge randomness
167 * @param bool $up True to get the result above the random number, false for below
168 *
169 * @note The $up parameter is supposed to counteract what would happen if there
170 * was a large gap in the distribution of cl_timestamp values. This way instead
171 * of things to the right of the gap being favoured, both sides of the gap
172 * are favoured.
173 * @return Array Query information.
174 */
175 protected function getQueryInfo( $rand, $offset, $up ) {
176 $op = $up ? '>=' : '<=';
177 $dir = $up ? 'ASC' : 'DESC';
178 if ( !$this->category instanceof Title ) {
179 throw new MWException( 'No category set' );
180 }
181 $qi = array(
182 'tables' => array( 'categorylinks', 'page' ),
183 'fields' => array( 'page_title', 'page_namespace' ),
184 'conds' => array_merge( array(
185 'cl_to' => $this->category->getDBKey(),
186 ), $this->extra ),
187 'options' => array(
188 'ORDER BY' => 'cl_timestamp ' . $dir,
189 'LIMIT' => 1,
190 'OFFSET' => $offset
191 ),
192 'join_conds' => array(
193 'page' => array( 'INNER JOIN', 'cl_from = page_id' )
194 )
195 );
196
197 $dbr = wfGetDB( DB_SLAVE );
198 $minClTime = $this->getTimestampOffset( $rand );
199 if ( $minClTime ) {
200 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
201 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
202 }
203 return $qi;
204 }
205
206 /**
207 * @param float $rand Random number between 0 and 1
208 *
209 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
210 */
211 protected function getTimestampOffset( $rand ) {
212 if ( $rand === false ) {
213 return false;
214 }
215 if ( !$this->minTimestamp || !$this->maxTimestamp ) {
216 try {
217 list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
218 } catch( MWException $e ) {
219 // Possibly no entries in category.
220 return false;
221 }
222 }
223
224 $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
225 return intval( $ts );
226 }
227
228 /**
229 * Get the lowest and highest timestamp for a category.
230 *
231 * @param Title $category
232 * @return Array The lowest and highest timestamp
233 * @throws MWException if category has no entries.
234 */
235 protected function getMinAndMaxForCat( Title $category ) {
236 $dbr = wfGetDB( DB_SLAVE );
237 $res = $dbr->selectRow(
238 'categorylinks',
239 array(
240 'low' => 'MIN( cl_timestamp )',
241 'high' => 'MAX( cl_timestamp )'
242 ),
243 array(
244 'cl_to' => $this->category->getDBKey(),
245 ),
246 __METHOD__,
247 array(
248 'LIMIT' => 1
249 )
250 );
251 if ( !$res ) {
252 throw new MWException( 'No entries in category' );
253 }
254 return array( wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) );
255 }
256
257 /**
258 * @param float $rand A random number that is converted to a random timestamp
259 * @param int $offset A small offset to make the result seem more "random"
260 * @param bool $up Get the result above the random value
261 * @param String $fname The name of the calling method
262 * @return Array Info for the title selected.
263 */
264 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
265 $dbr = wfGetDB( DB_SLAVE );
266
267 $query = $this->getQueryInfo( $rand, $offset, $up );
268 $res = $dbr->select(
269 $query['tables'],
270 $query['fields'],
271 $query['conds'],
272 $fname,
273 $query['options'],
274 $query['join_conds']
275 );
276
277 return $res->fetchObject();
278 }
279
280 protected function getGroupName() {
281 return 'redirects';
282 }
283 }