3 * Implements Special:RandomInCategory
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.
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.
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
21 * @ingroup SpecialPage
26 * Special page to direct the user to a random page
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.
35 * A more unbiased method could be achieved by adding a cl_random field
36 * to the categorylinks table.
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.
47 * @ingroup SpecialPage
49 class SpecialRandomInCategory
extends FormSpecialPage
{
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;
56 public function __construct( $name = 'RandomInCategory' ) {
57 parent
::__construct( $name );
61 * Set which category to use.
64 public function setCategory( Title
$cat ) {
65 $this->category
= $cat;
66 $this->maxTimestamp
= null;
67 $this->minTimestamp
= null;
70 protected function getFormFields() {
71 $this->addHelpLink( 'Help:RandomInCategory' );
76 'label-message' => 'randomincategory-category',
84 public function requiresWrite() {
88 public function requiresUnblock() {
92 protected function alterForm( HTMLForm
$form ) {
93 $form->setSubmitTextMsg( 'randomincategory-submit' );
96 protected function setParameter( $par ) {
97 // if subpage present, fake form submission
98 $this->onSubmit( array( 'category' => $par ) );
101 public function onSubmit( array $data ) {
104 $categoryStr = $data['category'];
106 if ( $categoryStr ) {
107 $cat = Title
::newFromText( $categoryStr, NS_CATEGORY
);
110 if ( $cat && $cat->getNamespace() !== NS_CATEGORY
) {
111 // Someone searching for something like "Wikipedia:Foo"
112 $cat = Title
::makeTitleSafe( NS_CATEGORY
, $categoryStr );
116 $this->setCategory( $cat );
119 if ( !$this->category
&& $categoryStr ) {
120 $msg = $this->msg( 'randomincategory-invalidcategory',
121 wfEscapeWikiText( $categoryStr ) );
123 return Status
::newFatal( $msg );
125 } elseif ( !$this->category
) {
126 return false; // no data sent
129 $title = $this->getRandomTitle();
131 if ( is_null( $title ) ) {
132 $msg = $this->msg( 'randomincategory-nopages',
133 $this->category
->getText() );
135 return Status
::newFatal( $msg );
138 $this->getOutput()->redirect( $title->getFullURL() );
142 * Choose a random title.
143 * @return Title|null Title object (or null if nothing to choose from)
145 public function getRandomTitle() {
146 // Convert to float, since we do math with the random number.
147 $rand = (float)wfRandom();
150 // Given that timestamps are rather unevenly distributed, we also
151 // use an offset between 0 and 30 to make any biases less noticeable.
152 $offset = mt_rand( 0, $this->maxOffset
);
154 if ( mt_rand( 0, 1 ) ) {
160 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
162 // Try again without the timestamp offset (wrap around the end)
164 $row = $this->selectRandomPageFromDB( false, $offset, $up );
167 // Maybe the category is really small and offset too high
169 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
172 // Just get the first entry.
174 $row = $this->selectRandomPageFromDB( false, 0, true );
178 return Title
::makeTitle( $row->page_namespace
, $row->page_title
);
185 * @param float $rand Random number between 0 and 1
186 * @param int $offset Extra offset to fudge randomness
187 * @param bool $up True to get the result above the random number, false for below
188 * @return array Query information.
189 * @throws MWException
190 * @note The $up parameter is supposed to counteract what would happen if there
191 * was a large gap in the distribution of cl_timestamp values. This way instead
192 * of things to the right of the gap being favoured, both sides of the gap
195 protected function getQueryInfo( $rand, $offset, $up ) {
196 $op = $up ?
'>=' : '<=';
197 $dir = $up ?
'ASC' : 'DESC';
198 if ( !$this->category
instanceof Title
) {
199 throw new MWException( 'No category set' );
202 'tables' => array( 'categorylinks', 'page' ),
203 'fields' => array( 'page_title', 'page_namespace' ),
204 'conds' => array_merge( array(
205 'cl_to' => $this->category
->getDBKey(),
208 'ORDER BY' => 'cl_timestamp ' . $dir,
212 'join_conds' => array(
213 'page' => array( 'INNER JOIN', 'cl_from = page_id' )
217 $dbr = wfGetDB( DB_SLAVE
);
218 $minClTime = $this->getTimestampOffset( $rand );
220 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
221 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
228 * @param float $rand Random number between 0 and 1
230 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
232 protected function getTimestampOffset( $rand ) {
233 if ( $rand === false ) {
236 if ( !$this->minTimestamp ||
!$this->maxTimestamp
) {
238 list( $this->minTimestamp
, $this->maxTimestamp
) = $this->getMinAndMaxForCat( $this->category
);
239 } catch ( Exception
$e ) {
240 // Possibly no entries in category.
245 $ts = ( $this->maxTimestamp
- $this->minTimestamp
) * $rand +
$this->minTimestamp
;
247 return intval( $ts );
251 * Get the lowest and highest timestamp for a category.
253 * @param Title $category
254 * @return array The lowest and highest timestamp
255 * @throws MWException If category has no entries.
257 protected function getMinAndMaxForCat( Title
$category ) {
258 $dbr = wfGetDB( DB_SLAVE
);
259 $res = $dbr->selectRow(
262 'low' => 'MIN( cl_timestamp )',
263 'high' => 'MAX( cl_timestamp )'
266 'cl_to' => $this->category
->getDBKey(),
274 throw new MWException( 'No entries in category' );
277 return array( wfTimestamp( TS_UNIX
, $res->low
), wfTimestamp( TS_UNIX
, $res->high
) );
281 * @param float $rand A random number that is converted to a random timestamp
282 * @param int $offset A small offset to make the result seem more "random"
283 * @param bool $up Get the result above the random value
284 * @param string $fname The name of the calling method
285 * @return array Info for the title selected.
287 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__
) {
288 $dbr = wfGetDB( DB_SLAVE
);
290 $query = $this->getQueryInfo( $rand, $offset, $up );
300 return $res->fetchObject();
303 protected function getGroupName() {