EditPage::newSectionSummary should return a value in all code paths
[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 global $wgScript;
72
73 $cat = false;
74
75 $categoryStr = $this->getRequest()->getText( 'category', $par );
76
77 if ( $categoryStr ) {
78 $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
79 }
80
81 if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
82 // Someone searching for something like "Wikipedia:Foo"
83 $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
84 }
85
86 if ( $cat ) {
87 $this->setCategory( $cat );
88 }
89
90 if ( !$this->category && $categoryStr ) {
91 $this->setHeaders();
92 $this->getOutput()->addWikiMsg( 'randomincategory-invalidcategory',
93 wfEscapeWikiText( $categoryStr ) );
94
95 return;
96 } elseif ( !$this->category ) {
97 $this->setHeaders();
98 $input = Html::input( 'category' );
99 $submitText = $this->msg( 'randomincategory-selectcategory-submit' )->text();
100 $submit = Html::input( '', $submitText, 'submit' );
101
102 $msg = $this->msg( 'randomincategory-selectcategory' );
103 $form = Html::rawElement( 'form', array( 'action' => $wgScript ),
104 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
105 $msg->rawParams( $input, $submit )->parse()
106 );
107 $this->getOutput()->addHtml( $form );
108
109 return;
110 }
111
112 $title = $this->getRandomTitle();
113
114 if ( is_null( $title ) ) {
115 $this->setHeaders();
116 $this->getOutput()->addWikiMsg( 'randomincategory-nopages',
117 $this->category->getText() );
118
119 return;
120 }
121
122 $query = $this->getRequest()->getValues();
123 unset( $query['title'] );
124 unset( $query['category'] );
125 $this->getOutput()->redirect( $title->getFullURL( $query ) );
126 }
127
128 /**
129 * Choose a random title.
130 * @return Title|null Title object (or null if nothing to choose from)
131 */
132 public function getRandomTitle() {
133 // Convert to float, since we do math with the random number.
134 $rand = (float)wfRandom();
135 $title = null;
136
137 // Given that timestamps are rather unevenly distributed, we also
138 // use an offset between 0 and 30 to make any biases less noticeable.
139 $offset = mt_rand( 0, $this->maxOffset );
140
141 if ( mt_rand( 0, 1 ) ) {
142 $up = true;
143 } else {
144 $up = false;
145 }
146
147 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
148
149 // Try again without the timestamp offset (wrap around the end)
150 if ( !$row ) {
151 $row = $this->selectRandomPageFromDB( false, $offset, $up );
152 }
153
154 // Maybe the category is really small and offset too high
155 if ( !$row ) {
156 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
157 }
158
159 // Just get the first entry.
160 if ( !$row ) {
161 $row = $this->selectRandomPageFromDB( false, 0, true );
162 }
163
164 if ( $row ) {
165 return Title::makeTitle( $row->page_namespace, $row->page_title );
166 }
167
168 return null;
169 }
170
171 /**
172 * @param float $rand Random number between 0 and 1
173 * @param int $offset Extra offset to fudge randomness
174 * @param bool $up True to get the result above the random number, false for below
175 *
176 * @note The $up parameter is supposed to counteract what would happen if there
177 * was a large gap in the distribution of cl_timestamp values. This way instead
178 * of things to the right of the gap being favoured, both sides of the gap
179 * are favoured.
180 * @return array Query information.
181 */
182 protected function getQueryInfo( $rand, $offset, $up ) {
183 $op = $up ? '>=' : '<=';
184 $dir = $up ? 'ASC' : 'DESC';
185 if ( !$this->category instanceof Title ) {
186 throw new MWException( 'No category set' );
187 }
188 $qi = array(
189 'tables' => array( 'categorylinks', 'page' ),
190 'fields' => array( 'page_title', 'page_namespace' ),
191 'conds' => array_merge( array(
192 'cl_to' => $this->category->getDBKey(),
193 ), $this->extra ),
194 'options' => array(
195 'ORDER BY' => 'cl_timestamp ' . $dir,
196 'LIMIT' => 1,
197 'OFFSET' => $offset
198 ),
199 'join_conds' => array(
200 'page' => array( 'INNER JOIN', 'cl_from = page_id' )
201 )
202 );
203
204 $dbr = wfGetDB( DB_SLAVE );
205 $minClTime = $this->getTimestampOffset( $rand );
206 if ( $minClTime ) {
207 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
208 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
209 }
210
211 return $qi;
212 }
213
214 /**
215 * @param float $rand Random number between 0 and 1
216 *
217 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
218 */
219 protected function getTimestampOffset( $rand ) {
220 if ( $rand === false ) {
221 return false;
222 }
223 if ( !$this->minTimestamp || !$this->maxTimestamp ) {
224 try {
225 list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
226 } catch ( MWException $e ) {
227 // Possibly no entries in category.
228 return false;
229 }
230 }
231
232 $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
233
234 return intval( $ts );
235 }
236
237 /**
238 * Get the lowest and highest timestamp for a category.
239 *
240 * @param Title $category
241 * @return array The lowest and highest timestamp
242 * @throws MWException If category has no entries.
243 */
244 protected function getMinAndMaxForCat( Title $category ) {
245 $dbr = wfGetDB( DB_SLAVE );
246 $res = $dbr->selectRow(
247 'categorylinks',
248 array(
249 'low' => 'MIN( cl_timestamp )',
250 'high' => 'MAX( cl_timestamp )'
251 ),
252 array(
253 'cl_to' => $this->category->getDBKey(),
254 ),
255 __METHOD__,
256 array(
257 'LIMIT' => 1
258 )
259 );
260 if ( !$res ) {
261 throw new MWException( 'No entries in category' );
262 }
263
264 return array( wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) );
265 }
266
267 /**
268 * @param float $rand A random number that is converted to a random timestamp
269 * @param int $offset A small offset to make the result seem more "random"
270 * @param bool $up Get the result above the random value
271 * @param string $fname The name of the calling method
272 * @return array Info for the title selected.
273 */
274 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
275 $dbr = wfGetDB( DB_SLAVE );
276
277 $query = $this->getQueryInfo( $rand, $offset, $up );
278 $res = $dbr->select(
279 $query['tables'],
280 $query['fields'],
281 $query['conds'],
282 $fname,
283 $query['options'],
284 $query['join_conds']
285 );
286
287 return $res->fetchObject();
288 }
289
290 protected function getGroupName() {
291 return 'redirects';
292 }
293 }