MediaWiki  master
SpecialRandomInCategory.php
Go to the documentation of this file.
1 <?php
51  protected $extra = []; // Extra SQL statements
53  protected $category = false; // Title object of category
55  protected $maxOffset = 30; // Max amount to fudge randomness by.
57  private $maxTimestamp = null;
59  private $minTimestamp = null;
60 
61  public function __construct( $name = 'RandomInCategory' ) {
62  parent::__construct( $name );
63  }
64 
69  public function setCategory( Title $cat ) {
70  $this->category = $cat;
71  $this->maxTimestamp = null;
72  $this->minTimestamp = null;
73  }
74 
75  protected function getFormFields() {
76  $this->addHelpLink( 'Help:RandomInCategory' );
77 
78  return [
79  'category' => [
80  'type' => 'title',
81  'namespace' => NS_CATEGORY,
82  'relative' => true,
83  'label-message' => 'randomincategory-category',
84  'required' => true,
85  ]
86  ];
87  }
88 
89  public function requiresWrite() {
90  return false;
91  }
92 
93  public function requiresUnblock() {
94  return false;
95  }
96 
97  protected function getDisplayFormat() {
98  return 'ooui';
99  }
100 
101  protected function alterForm( HTMLForm $form ) {
102  $form->setSubmitTextMsg( 'randomincategory-submit' );
103  }
104 
105  protected function setParameter( $par ) {
106  // if subpage present, fake form submission
107  $this->onSubmit( [ 'category' => $par ] );
108  }
109 
110  public function onSubmit( array $data ) {
111  $cat = false;
112 
113  $categoryStr = $data['category'];
114 
115  if ( $categoryStr ) {
116  $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
117  }
118 
119  if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
120  // Someone searching for something like "Wikipedia:Foo"
121  $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
122  }
123 
124  if ( $cat ) {
125  $this->setCategory( $cat );
126  }
127 
128  if ( !$this->category && $categoryStr ) {
129  $msg = $this->msg( 'randomincategory-invalidcategory',
130  wfEscapeWikiText( $categoryStr ) );
131 
132  return Status::newFatal( $msg );
133 
134  } elseif ( !$this->category ) {
135  return false; // no data sent
136  }
137 
138  $title = $this->getRandomTitle();
139 
140  if ( $title === null ) {
141  $msg = $this->msg( 'randomincategory-nopages',
142  $this->category->getText() );
143 
144  return Status::newFatal( $msg );
145  }
146 
147  $query = $this->getRequest()->getValues();
148  unset( $query['title'] );
149  $this->getOutput()->redirect( $title->getFullURL( $query ) );
150  }
151 
156  public function getRandomTitle() {
157  // Convert to float, since we do math with the random number.
158  $rand = (float)wfRandom();
159  $title = null;
160 
161  // Given that timestamps are rather unevenly distributed, we also
162  // use an offset between 0 and 30 to make any biases less noticeable.
163  $offset = mt_rand( 0, $this->maxOffset );
164 
165  if ( mt_rand( 0, 1 ) ) {
166  $up = true;
167  } else {
168  $up = false;
169  }
170 
171  $row = $this->selectRandomPageFromDB( $rand, $offset, $up, __METHOD__ );
172 
173  // Try again without the timestamp offset (wrap around the end)
174  if ( !$row ) {
175  $row = $this->selectRandomPageFromDB( false, $offset, $up, __METHOD__ );
176  }
177 
178  // Maybe the category is really small and offset too high
179  if ( !$row ) {
180  $row = $this->selectRandomPageFromDB( $rand, 0, $up, __METHOD__ );
181  }
182 
183  // Just get the first entry.
184  if ( !$row ) {
185  $row = $this->selectRandomPageFromDB( false, 0, true, __METHOD__ );
186  }
187 
188  if ( $row ) {
189  return Title::makeTitle( $row->page_namespace, $row->page_title );
190  }
191 
192  return null;
193  }
194 
206  protected function getQueryInfo( $rand, $offset, $up ) {
207  $op = $up ? '>=' : '<=';
208  $dir = $up ? 'ASC' : 'DESC';
209  if ( !$this->category instanceof Title ) {
210  throw new MWException( 'No category set' );
211  }
212  $qi = [
213  'tables' => [ 'categorylinks', 'page' ],
214  'fields' => [ 'page_title', 'page_namespace' ],
215  'conds' => array_merge( [
216  'cl_to' => $this->category->getDBkey(),
217  ], $this->extra ),
218  'options' => [
219  'ORDER BY' => 'cl_timestamp ' . $dir,
220  'LIMIT' => 1,
221  'OFFSET' => $offset
222  ],
223  'join_conds' => [
224  'page' => [ 'JOIN', 'cl_from = page_id' ]
225  ]
226  ];
227 
228  $dbr = wfGetDB( DB_REPLICA );
229  $minClTime = $this->getTimestampOffset( $rand );
230  if ( $minClTime ) {
231  $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
232  $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
233  }
234 
235  return $qi;
236  }
237 
243  protected function getTimestampOffset( $rand ) {
244  if ( $rand === false ) {
245  return false;
246  }
247  if ( !$this->minTimestamp || !$this->maxTimestamp ) {
248  try {
249  list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
250  } catch ( Exception $e ) {
251  // Possibly no entries in category.
252  return false;
253  }
254  }
255 
256  $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
257 
258  return intval( $ts );
259  }
260 
268  protected function getMinAndMaxForCat( Title $category ) {
269  $dbr = wfGetDB( DB_REPLICA );
270  $res = $dbr->selectRow(
271  'categorylinks',
272  [
273  'low' => 'MIN( cl_timestamp )',
274  'high' => 'MAX( cl_timestamp )'
275  ],
276  [
277  'cl_to' => $this->category->getDBkey(),
278  ],
279  __METHOD__,
280  [
281  'LIMIT' => 1
282  ]
283  );
284  if ( !$res ) {
285  throw new MWException( 'No entries in category' );
286  }
287 
288  return [ wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) ];
289  }
290 
298  private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
299  $dbr = wfGetDB( DB_REPLICA );
300 
301  $query = $this->getQueryInfo( $rand, $offset, $up );
302  $res = $dbr->select(
303  $query['tables'],
304  $query['fields'],
305  $query['conds'],
306  $fname,
307  $query['options'],
308  $query['join_conds']
309  );
310 
311  return $res->fetchObject();
312  }
313 
314  protected function getGroupName() {
315  return 'redirects';
316  }
317 }
SpecialRandomInCategory\$extra
string[] $extra
Definition: SpecialRandomInCategory.php:51
SpecialPage\msg
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:831
SpecialRandomInCategory\$minTimestamp
int null $minTimestamp
Definition: SpecialRandomInCategory.php:59
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:328
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
SpecialRandomInCategory\requiresUnblock
requiresUnblock()
Whether this action cannot be executed by a blocked user.
Definition: SpecialRandomInCategory.php:93
SpecialRandomInCategory\getRandomTitle
getRandomTitle()
Choose a random title.
Definition: SpecialRandomInCategory.php:156
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:747
SpecialRandomInCategory\getTimestampOffset
getTimestampOffset( $rand)
Definition: SpecialRandomInCategory.php:243
SpecialRandomInCategory\getMinAndMaxForCat
getMinAndMaxForCat(Title $category)
Get the lowest and highest timestamp for a category.
Definition: SpecialRandomInCategory.php:268
SpecialRandomInCategory\requiresWrite
requiresWrite()
Whether this action requires the wiki not to be locked.
Definition: SpecialRandomInCategory.php:89
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
SpecialRandomInCategory\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialRandomInCategory.php:101
SpecialRandomInCategory\__construct
__construct( $name='RandomInCategory')
Definition: SpecialRandomInCategory.php:61
FormSpecialPage
Special page which uses an HTMLForm to handle processing.
Definition: FormSpecialPage.php:31
$res
$res
Definition: testCompression.php:57
$dbr
$dbr
Definition: testCompression.php:54
SpecialRandomInCategory\onSubmit
onSubmit(array $data)
Process the form on POST submission.
Definition: SpecialRandomInCategory.php:110
SpecialRandomInCategory\setParameter
setParameter( $par)
Maybe do something interesting with the subpage parameter.
Definition: SpecialRandomInCategory.php:105
SpecialPage\addHelpLink
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: SpecialPage.php:867
MWException
MediaWiki exception.
Definition: MWException.php:29
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2459
SpecialRandomInCategory\setCategory
setCategory(Title $cat)
Set which category to use.
Definition: SpecialRandomInCategory.php:69
$title
$title
Definition: testCompression.php:38
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:591
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:83
FormSpecialPage\$par
string null $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
SpecialRandomInCategory\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialRandomInCategory.php:97
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:737
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1494
SpecialRandomInCategory\$category
Title false $category
Definition: SpecialRandomInCategory.php:53
SpecialRandomInCategory\getFormFields
getFormFields()
Get an HTMLForm descriptor array.
Definition: SpecialRandomInCategory.php:75
SpecialRandomInCategory
Special page to direct the user to a random page.
Definition: SpecialRandomInCategory.php:49
HTMLForm\setSubmitTextMsg
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1413
Title
Represents a title within MediaWiki.
Definition: Title.php:41
wfRandom
wfRandom()
Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for ...
Definition: GlobalFunctions.php:255
SpecialRandomInCategory\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialRandomInCategory.php:314
SpecialRandomInCategory\$maxOffset
int $maxOffset
Definition: SpecialRandomInCategory.php:55
SpecialRandomInCategory\getQueryInfo
getQueryInfo( $rand, $offset, $up)
Definition: SpecialRandomInCategory.php:206
SpecialRandomInCategory\$maxTimestamp
int null $maxTimestamp
Definition: SpecialRandomInCategory.php:57
SpecialRandomInCategory\selectRandomPageFromDB
selectRandomPageFromDB( $rand, $offset, $up, $fname=__METHOD__)
Definition: SpecialRandomInCategory.php:298
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:135