MediaWiki  1.27.2
SpecialRandomInCategory.php
Go to the documentation of this file.
1 <?php
50  protected $extra = []; // 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 
64  public function setCategory( Title $cat ) {
65  $this->category = $cat;
66  $this->maxTimestamp = null;
67  $this->minTimestamp = null;
68  }
69 
70  protected function getFormFields() {
71  $this->addHelpLink( 'Help:RandomInCategory' );
72 
73  return [
74  'category' => [
75  'type' => 'title',
76  'namespace' => NS_CATEGORY,
77  'relative' => true,
78  'label-message' => 'randomincategory-category',
79  'required' => true,
80  ]
81  ];
82  }
83 
84  public function requiresWrite() {
85  return false;
86  }
87 
88  public function requiresUnblock() {
89  return false;
90  }
91 
92  protected function getDisplayFormat() {
93  return 'ooui';
94  }
95 
96  protected function alterForm( HTMLForm $form ) {
97  $form->setSubmitTextMsg( 'randomincategory-submit' );
98  }
99 
100  protected function setParameter( $par ) {
101  // if subpage present, fake form submission
102  $this->onSubmit( [ 'category' => $par ] );
103  }
104 
105  public function onSubmit( array $data ) {
106  $cat = false;
107 
108  $categoryStr = $data['category'];
109 
110  if ( $categoryStr ) {
111  $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
112  }
113 
114  if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
115  // Someone searching for something like "Wikipedia:Foo"
116  $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
117  }
118 
119  if ( $cat ) {
120  $this->setCategory( $cat );
121  }
122 
123  if ( !$this->category && $categoryStr ) {
124  $msg = $this->msg( 'randomincategory-invalidcategory',
125  wfEscapeWikiText( $categoryStr ) );
126 
127  return Status::newFatal( $msg );
128 
129  } elseif ( !$this->category ) {
130  return false; // no data sent
131  }
132 
133  $title = $this->getRandomTitle();
134 
135  if ( is_null( $title ) ) {
136  $msg = $this->msg( 'randomincategory-nopages',
137  $this->category->getText() );
138 
139  return Status::newFatal( $msg );
140  }
141 
142  $this->getOutput()->redirect( $title->getFullURL() );
143  }
144 
149  public function getRandomTitle() {
150  // Convert to float, since we do math with the random number.
151  $rand = (float)wfRandom();
152  $title = null;
153 
154  // Given that timestamps are rather unevenly distributed, we also
155  // use an offset between 0 and 30 to make any biases less noticeable.
156  $offset = mt_rand( 0, $this->maxOffset );
157 
158  if ( mt_rand( 0, 1 ) ) {
159  $up = true;
160  } else {
161  $up = false;
162  }
163 
164  $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
165 
166  // Try again without the timestamp offset (wrap around the end)
167  if ( !$row ) {
168  $row = $this->selectRandomPageFromDB( false, $offset, $up );
169  }
170 
171  // Maybe the category is really small and offset too high
172  if ( !$row ) {
173  $row = $this->selectRandomPageFromDB( $rand, 0, $up );
174  }
175 
176  // Just get the first entry.
177  if ( !$row ) {
178  $row = $this->selectRandomPageFromDB( false, 0, true );
179  }
180 
181  if ( $row ) {
182  return Title::makeTitle( $row->page_namespace, $row->page_title );
183  }
184 
185  return null;
186  }
187 
199  protected function getQueryInfo( $rand, $offset, $up ) {
200  $op = $up ? '>=' : '<=';
201  $dir = $up ? 'ASC' : 'DESC';
202  if ( !$this->category instanceof Title ) {
203  throw new MWException( 'No category set' );
204  }
205  $qi = [
206  'tables' => [ 'categorylinks', 'page' ],
207  'fields' => [ 'page_title', 'page_namespace' ],
208  'conds' => array_merge( [
209  'cl_to' => $this->category->getDBkey(),
210  ], $this->extra ),
211  'options' => [
212  'ORDER BY' => 'cl_timestamp ' . $dir,
213  'LIMIT' => 1,
214  'OFFSET' => $offset
215  ],
216  'join_conds' => [
217  'page' => [ 'INNER JOIN', 'cl_from = page_id' ]
218  ]
219  ];
220 
221  $dbr = wfGetDB( DB_SLAVE );
222  $minClTime = $this->getTimestampOffset( $rand );
223  if ( $minClTime ) {
224  $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
225  $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
226  }
227 
228  return $qi;
229  }
230 
236  protected function getTimestampOffset( $rand ) {
237  if ( $rand === false ) {
238  return false;
239  }
240  if ( !$this->minTimestamp || !$this->maxTimestamp ) {
241  try {
242  list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
243  } catch ( Exception $e ) {
244  // Possibly no entries in category.
245  return false;
246  }
247  }
248 
249  $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
250 
251  return intval( $ts );
252  }
253 
261  protected function getMinAndMaxForCat( Title $category ) {
262  $dbr = wfGetDB( DB_SLAVE );
263  $res = $dbr->selectRow(
264  'categorylinks',
265  [
266  'low' => 'MIN( cl_timestamp )',
267  'high' => 'MAX( cl_timestamp )'
268  ],
269  [
270  'cl_to' => $this->category->getDBKey(),
271  ],
272  __METHOD__,
273  [
274  'LIMIT' => 1
275  ]
276  );
277  if ( !$res ) {
278  throw new MWException( 'No entries in category' );
279  }
280 
281  return [ wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) ];
282  }
283 
291  private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
292  $dbr = wfGetDB( DB_SLAVE );
293 
294  $query = $this->getQueryInfo( $rand, $offset, $up );
295  $res = $dbr->select(
296  $query['tables'],
297  $query['fields'],
298  $query['conds'],
299  $fname,
300  $query['options'],
301  $query['join_conds']
302  );
303 
304  return $res->fetchObject();
305  }
306 
307  protected function getGroupName() {
308  return 'redirects';
309  }
310 }
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1418
if(count($args)==0) $dir
setCategory(Title $cat)
Set which category to use.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
msg()
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
Special page which uses an HTMLForm to handle processing.
getQueryInfo($rand, $offset, $up)
addHelpLink($to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getMinAndMaxForCat(Title $category)
Get the lowest and highest timestamp for a category.
wfEscapeWikiText($text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
$res
Definition: database.txt:21
const NS_CATEGORY
Definition: Defines.php:83
setSubmitTextMsg($msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1250
Object handling generic submission, CSRF protection, layout and other logic for UI forms...
Definition: HTMLForm.php:123
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:548
const DB_SLAVE
Definition: Defines.php:46
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
__construct($name= 'RandomInCategory')
Special page to direct the user to a random page.
selectRandomPageFromDB($rand, $offset, $up, $fname=__METHOD__)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
wfRandom()
Get a random decimal value between 0 and 1, in a way not likely to give duplicate values for any real...
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
getRandomTitle()
Choose a random title.
string $par
The sub-page of the special page.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:524
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310