3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Specials
;
23 use BadMethodCallException
;
24 use MediaWiki\HTMLForm\HTMLForm
;
25 use MediaWiki\SpecialPage\FormSpecialPage
;
26 use MediaWiki\Status\Status
;
27 use MediaWiki\Title\Title
;
29 use Wikimedia\Rdbms\IConnectionProvider
;
30 use Wikimedia\Rdbms\SelectQueryBuilder
;
33 * Redirect to a random page in a category
35 * @note The method used here is rather biased. It is assumed that
36 * the use of this page will be people wanting to get a random page
37 * out of a maintenance category, to fix it up. The method used by
38 * this page should return different pages in an unpredictable fashion
39 * which is hoped to be sufficient, even if some pages are selected
40 * more often than others.
42 * A more unbiased method could be achieved by adding a cl_random field
43 * to the categorylinks table.
45 * The method used here is as follows:
46 * * Find the smallest and largest timestamp in the category
47 * * Pick a random timestamp in between
48 * * Pick an offset between 0 and 30
49 * * Get the offset'ed page that is newer than the timestamp selected
50 * The offset is meant to counter the fact the timestamps aren't usually
51 * uniformly distributed, so if things are very non-uniform at least we
52 * won't have the same page selected 99% of the time.
54 * @ingroup SpecialPage
57 class SpecialRandomInCategory
extends FormSpecialPage
{
58 /** @var string[] Extra SQL statements */
59 protected $extra = [];
60 /** @var Title|false Title object of category */
61 protected $category = false;
62 /** @var int Max amount to fudge randomness by */
63 protected $maxOffset = 30;
65 private $maxTimestamp = null;
67 private $minTimestamp = null;
69 private IConnectionProvider
$dbProvider;
72 * @param IConnectionProvider $dbProvider
74 public function __construct( IConnectionProvider
$dbProvider ) {
75 parent
::__construct( 'RandomInCategory' );
76 $this->dbProvider
= $dbProvider;
80 * Set which category to use.
83 public function setCategory( Title
$cat ) {
84 $this->category
= $cat;
85 $this->maxTimestamp
= null;
86 $this->minTimestamp
= null;
89 protected function getFormFields() {
90 $this->addHelpLink( 'Help:RandomInCategory' );
95 'namespace' => NS_CATEGORY
,
97 'label-message' => 'randomincategory-category',
103 public function requiresPost() {
107 protected function getDisplayFormat() {
111 protected function alterForm( HTMLForm
$form ) {
112 $form->setSubmitTextMsg( 'randomincategory-submit' );
115 protected function getSubpageField() {
119 public function onSubmit( array $data ) {
122 $categoryStr = $data['category'];
124 if ( $categoryStr ) {
125 $cat = Title
::newFromText( $categoryStr, NS_CATEGORY
);
128 if ( $cat && $cat->getNamespace() !== NS_CATEGORY
) {
129 // Someone searching for something like "Wikipedia:Foo"
130 $cat = Title
::makeTitleSafe( NS_CATEGORY
, $categoryStr );
134 $this->setCategory( $cat );
137 if ( !$this->category
&& $categoryStr ) {
138 $msg = $this->msg( 'randomincategory-invalidcategory',
139 wfEscapeWikiText( $categoryStr ) );
141 return Status
::newFatal( $msg );
143 } elseif ( !$this->category
) {
144 return false; // no data sent
147 $title = $this->getRandomTitle();
149 if ( $title === null ) {
150 $msg = $this->msg( 'randomincategory-nopages',
151 $this->category
->getText() );
153 return Status
::newFatal( $msg );
156 $query = $this->getRequest()->getQueryValues();
157 unset( $query['title'] );
158 $this->getOutput()->redirect( $title->getFullURL( $query ) );
162 * Choose a random title.
163 * @return Title|null Title object or null if nothing to choose from
165 public function getRandomTitle() {
166 // Convert to float, since we do math with the random number.
167 $rand = (float)wfRandom();
169 // Given that timestamps are rather unevenly distributed, we also
170 // use an offset between 0 and 30 to make any biases less noticeable.
171 $offset = mt_rand( 0, $this->maxOffset
);
173 if ( mt_rand( 0, 1 ) ) {
179 $row = $this->selectRandomPageFromDB( $rand, $offset, $up, __METHOD__
);
181 // Try again without the timestamp offset (wrap around the end)
183 $row = $this->selectRandomPageFromDB( false, $offset, $up, __METHOD__
);
186 // Maybe the category is really small and offset too high
188 $row = $this->selectRandomPageFromDB( $rand, 0, $up, __METHOD__
);
191 // Just get the first entry.
193 $row = $this->selectRandomPageFromDB( false, 0, true, __METHOD__
);
197 return Title
::makeTitle( $row->page_namespace
, $row->page_title
);
204 * @note The $up parameter is supposed to counteract what would happen if there
205 * was a large gap in the distribution of cl_timestamp values. This way instead
206 * of things to the right of the gap being favoured, both sides of the gap
209 * @param float|false $rand Random number between 0 and 1
210 * @param int $offset Extra offset to fudge randomness
211 * @param bool $up True to get the result above the random number, false for below
212 * @return SelectQueryBuilder
214 protected function getQueryBuilder( $rand, $offset, $up ) {
215 if ( !$this->category
instanceof Title
) {
216 throw new BadMethodCallException( 'No category set' );
218 $dbr = $this->dbProvider
->getReplicaDatabase();
219 $queryBuilder = $dbr->newSelectQueryBuilder()
220 ->select( [ 'page_title', 'page_namespace' ] )
221 ->from( 'categorylinks' )
222 ->join( 'page', null, 'cl_from = page_id' )
223 ->where( [ 'cl_to' => $this->category
->getDBkey() ] )
224 ->andWhere( $this->extra
)
225 ->orderBy( 'cl_timestamp', $up ? SelectQueryBuilder
::SORT_ASC
: SelectQueryBuilder
::SORT_DESC
)
229 $minClTime = $this->getTimestampOffset( $rand );
231 $op = $up ?
'>=' : '<=';
232 $queryBuilder->andWhere(
233 $dbr->expr( 'cl_timestamp', $op, $dbr->timestamp( $minClTime ) )
237 return $queryBuilder;
241 * @param float|false $rand Random number between 0 and 1
242 * @return int|false A random (unix) timestamp from the range of the category or false on failure
244 protected function getTimestampOffset( $rand ) {
245 if ( $rand === false ) {
248 if ( !$this->minTimestamp ||
!$this->maxTimestamp
) {
249 $minAndMax = $this->getMinAndMaxForCat();
250 if ( $minAndMax === null ) {
251 // No entries in this category.
254 [ $this->minTimestamp
, $this->maxTimestamp
] = $minAndMax;
257 $ts = ( $this->maxTimestamp
- $this->minTimestamp
) * $rand +
$this->minTimestamp
;
259 return intval( $ts );
263 * Get the lowest and highest timestamp for a category.
265 * @return array|null The lowest and highest timestamp, or null if the category has no entries.
267 protected function getMinAndMaxForCat() {
268 $dbr = $this->dbProvider
->getReplicaDatabase();
269 $res = $dbr->newSelectQueryBuilder()
270 ->select( [ 'low' => 'MIN( cl_timestamp )', 'high' => 'MAX( cl_timestamp )' ] )
271 ->from( 'categorylinks' )
272 ->where( [ 'cl_to' => $this->category
->getDBkey(), ] )
273 ->caller( __METHOD__
)->fetchRow();
278 return [ (int)wfTimestamp( TS_UNIX
, $res->low
), (int)wfTimestamp( TS_UNIX
, $res->high
) ];
282 * @param float|false $rand A random number that is converted to a random timestamp
283 * @param int $offset A small offset to make the result seem more "random"
284 * @param bool $up Get the result above the random value
285 * @param string $fname The name of the calling method
286 * @return stdClass|false Info for the title selected.
288 private function selectRandomPageFromDB( $rand, $offset, $up, $fname ) {
289 return $this->getQueryBuilder( $rand, $offset, $up )->caller( $fname )->fetchRow();
292 protected function getGroupName() {
298 * Retain the old class name for backwards compatibility.
299 * @deprecated since 1.41
301 class_alias( SpecialRandomInCategory
::class, 'SpecialRandomInCategory' );