SpecialRandomInCategory.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. * Special page to direct the user to a random page
  26. *
  27. * @note The method used here is rather biased. It is assumed that
  28. * the use of this page will be people wanting to get a random page
  29. * out of a maintenance category, to fix it up. The method used by
  30. * this page should return different pages in an unpredictable fashion
  31. * which is hoped to be sufficient, even if some pages are selected
  32. * more often than others.
  33. *
  34. * A more unbiased method could be achieved by adding a cl_random field
  35. * to the categorylinks table.
  36. *
  37. * The method used here is as follows:
  38. * * Find the smallest and largest timestamp in the category
  39. * * Pick a random timestamp in between
  40. * * Pick an offset between 0 and 30
  41. * * Get the offset'ed page that is newer than the timestamp selected
  42. * The offset is meant to counter the fact the timestamps aren't usually
  43. * uniformly distributed, so if things are very non-uniform at least we
  44. * won't have the same page selected 99% of the time.
  45. *
  46. * @ingroup SpecialPage
  47. */
  48. class SpecialRandomInCategory extends FormSpecialPage {
  49. /** @var string[] */
  50. protected $extra = []; // Extra SQL statements
  51. /** @var Title|false */
  52. protected $category = false; // Title object of category
  53. /** @var int */
  54. protected $maxOffset = 30; // Max amount to fudge randomness by.
  55. /** @var int|null */
  56. private $maxTimestamp = null;
  57. /** @var int|null */
  58. private $minTimestamp = null;
  59. public function __construct( $name = 'RandomInCategory' ) {
  60. parent::__construct( $name );
  61. }
  62. /**
  63. * Set which category to use.
  64. * @param Title $cat
  65. */
  66. public function setCategory( Title $cat ) {
  67. $this->category = $cat;
  68. $this->maxTimestamp = null;
  69. $this->minTimestamp = null;
  70. }
  71. protected function getFormFields() {
  72. $this->addHelpLink( 'Help:RandomInCategory' );
  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. public function requiresWrite() {
  84. return false;
  85. }
  86. public function requiresUnblock() {
  87. return false;
  88. }
  89. protected function getDisplayFormat() {
  90. return 'ooui';
  91. }
  92. protected function alterForm( HTMLForm $form ) {
  93. $form->setSubmitTextMsg( 'randomincategory-submit' );
  94. }
  95. protected function setParameter( $par ) {
  96. // if subpage present, fake form submission
  97. $this->onSubmit( [ 'category' => $par ] );
  98. }
  99. public function onSubmit( array $data ) {
  100. $cat = false;
  101. $categoryStr = $data['category'];
  102. if ( $categoryStr ) {
  103. $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
  104. }
  105. if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
  106. // Someone searching for something like "Wikipedia:Foo"
  107. $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
  108. }
  109. if ( $cat ) {
  110. $this->setCategory( $cat );
  111. }
  112. if ( !$this->category && $categoryStr ) {
  113. $msg = $this->msg( 'randomincategory-invalidcategory',
  114. wfEscapeWikiText( $categoryStr ) );
  115. return Status::newFatal( $msg );
  116. } elseif ( !$this->category ) {
  117. return false; // no data sent
  118. }
  119. $title = $this->getRandomTitle();
  120. if ( is_null( $title ) ) {
  121. $msg = $this->msg( 'randomincategory-nopages',
  122. $this->category->getText() );
  123. return Status::newFatal( $msg );
  124. }
  125. $this->getOutput()->redirect( $title->getFullURL() );
  126. }
  127. /**
  128. * Choose a random title.
  129. * @return Title|null Title object (or null if nothing to choose from)
  130. */
  131. public function getRandomTitle() {
  132. // Convert to float, since we do math with the random number.
  133. $rand = (float)wfRandom();
  134. $title = null;
  135. // Given that timestamps are rather unevenly distributed, we also
  136. // use an offset between 0 and 30 to make any biases less noticeable.
  137. $offset = mt_rand( 0, $this->maxOffset );
  138. if ( mt_rand( 0, 1 ) ) {
  139. $up = true;
  140. } else {
  141. $up = false;
  142. }
  143. $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
  144. // Try again without the timestamp offset (wrap around the end)
  145. if ( !$row ) {
  146. $row = $this->selectRandomPageFromDB( false, $offset, $up );
  147. }
  148. // Maybe the category is really small and offset too high
  149. if ( !$row ) {
  150. $row = $this->selectRandomPageFromDB( $rand, 0, $up );
  151. }
  152. // Just get the first entry.
  153. if ( !$row ) {
  154. $row = $this->selectRandomPageFromDB( false, 0, true );
  155. }
  156. if ( $row ) {
  157. return Title::makeTitle( $row->page_namespace, $row->page_title );
  158. }
  159. return null;
  160. }
  161. /**
  162. * @param float $rand Random number between 0 and 1
  163. * @param int $offset Extra offset to fudge randomness
  164. * @param bool $up True to get the result above the random number, false for below
  165. * @return array Query information.
  166. * @throws MWException
  167. * @note The $up parameter is supposed to counteract what would happen if there
  168. * was a large gap in the distribution of cl_timestamp values. This way instead
  169. * of things to the right of the gap being favoured, both sides of the gap
  170. * are favoured.
  171. */
  172. protected function getQueryInfo( $rand, $offset, $up ) {
  173. $op = $up ? '>=' : '<=';
  174. $dir = $up ? 'ASC' : 'DESC';
  175. if ( !$this->category instanceof Title ) {
  176. throw new MWException( 'No category set' );
  177. }
  178. $qi = [
  179. 'tables' => [ 'categorylinks', 'page' ],
  180. 'fields' => [ 'page_title', 'page_namespace' ],
  181. 'conds' => array_merge( [
  182. 'cl_to' => $this->category->getDBkey(),
  183. ], $this->extra ),
  184. 'options' => [
  185. 'ORDER BY' => 'cl_timestamp ' . $dir,
  186. 'LIMIT' => 1,
  187. 'OFFSET' => $offset
  188. ],
  189. 'join_conds' => [
  190. 'page' => [ 'JOIN', 'cl_from = page_id' ]
  191. ]
  192. ];
  193. $dbr = wfGetDB( DB_REPLICA );
  194. $minClTime = $this->getTimestampOffset( $rand );
  195. if ( $minClTime ) {
  196. $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
  197. $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
  198. }
  199. return $qi;
  200. }
  201. /**
  202. * @param float $rand Random number between 0 and 1
  203. *
  204. * @return int|bool A random (unix) timestamp from the range of the category or false on failure
  205. */
  206. protected function getTimestampOffset( $rand ) {
  207. if ( $rand === false ) {
  208. return false;
  209. }
  210. if ( !$this->minTimestamp || !$this->maxTimestamp ) {
  211. try {
  212. list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
  213. } catch ( Exception $e ) {
  214. // Possibly no entries in category.
  215. return false;
  216. }
  217. }
  218. $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
  219. return intval( $ts );
  220. }
  221. /**
  222. * Get the lowest and highest timestamp for a category.
  223. *
  224. * @param Title $category
  225. * @return array The lowest and highest timestamp
  226. * @throws MWException If category has no entries.
  227. */
  228. protected function getMinAndMaxForCat( Title $category ) {
  229. $dbr = wfGetDB( DB_REPLICA );
  230. $res = $dbr->selectRow(
  231. 'categorylinks',
  232. [
  233. 'low' => 'MIN( cl_timestamp )',
  234. 'high' => 'MAX( cl_timestamp )'
  235. ],
  236. [
  237. 'cl_to' => $this->category->getDBkey(),
  238. ],
  239. __METHOD__,
  240. [
  241. 'LIMIT' => 1
  242. ]
  243. );
  244. if ( !$res ) {
  245. throw new MWException( 'No entries in category' );
  246. }
  247. return [ wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) ];
  248. }
  249. /**
  250. * @param float $rand A random number that is converted to a random timestamp
  251. * @param int $offset A small offset to make the result seem more "random"
  252. * @param bool $up Get the result above the random value
  253. * @param string $fname The name of the calling method
  254. * @return stdClass|false Info for the title selected.
  255. */
  256. private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
  257. $dbr = wfGetDB( DB_REPLICA );
  258. $query = $this->getQueryInfo( $rand, $offset, $up );
  259. $res = $dbr->select(
  260. $query['tables'],
  261. $query['fields'],
  262. $query['conds'],
  263. $fname,
  264. $query['options'],
  265. $query['join_conds']
  266. );
  267. return $res->fetchObject();
  268. }
  269. protected function getGroupName() {
  270. return 'redirects';
  271. }
  272. }