Skip to content

Commit

Permalink
Bug 589: make random selection slightly more random. PHP's
Browse files Browse the repository at this point in the history
mt_rand() function has a maximum value of 2^31-1, which
is small enough that duplicate values can occur due to the
Birthday paradox, e.g. on the English Wikipedia. To fix
this, add a wfRandom() function that calls mt_rand()
twice to get the desired amount of randomness.
  • Loading branch information
Wil Mahan committed Oct 11, 2004
1 parent a2f8c15 commit 2a03980
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
16 changes: 16 additions & 0 deletions includes/GlobalFunctions.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,22 @@ function wfSeedRandom() {
}
}

/**
* Get a random decimal value between 0 and 1, in a way
* not likely to give duplicate values for any realistic
* number of articles.
*
* @return string
*/
function wfRandom() {
# The maximum random value is "only" 2^31-1, so get two random
# values to reduce the chance of dupes
$max = mt_getrandmax();
$rand = number_format( mt_rand() * mt_rand()
/ $max / $max, 12, '.', '' );
return $rand;
}

/**
* We want / and : to be included as literal characters in our title URLs.
* %2F in the page titles seems to fatally break for some reason.
Expand Down
3 changes: 1 addition & 2 deletions includes/SpecialRandompage.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ function wfSpecialRandompage() {
#
# Using a literal constant means the whole thing gets optimized on
# the index, and the comparison is both fast and fair.
$rand = mt_rand() / mt_getrandmax();

# interpolation and sprintf() can muck up with locale-specific decimal separator
$randstr = number_format( $rand, 12, ".", "" );
$randstr = wfRandom();

$db =& wfGetDB( DB_SLAVE );
$use_index = $db->useIndexClause( 'cur_random' );
Expand Down
2 changes: 1 addition & 1 deletion includes/SpecialUndelete.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ function undelete( $timestamps ) {
$redirect = MagicWord::get( MAG_REDIRECT );
$redir = $redirect->matchStart( $text ) ? 1 : 0;

$rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
$rand = wfRandom();
$dbw->insertArray( 'cur', array(
'cur_id' => $dbw->nextSequenceValue( 'cur_cur_id_seq' ),
'cur_namespace' => $namespace,
Expand Down
2 changes: 1 addition & 1 deletion includes/Title.php
Original file line number Diff line number Diff line change
Expand Up @@ -1441,7 +1441,7 @@ function moveTo( &$nt, $auth = true ) {
$now = $dbw->timestamp();
$won = wfInvertTimestamp( wfTimestamp(TS_MW,$now) );
wfSeedRandom();
$rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
$rand = wfRandom();

# Rename cur entry
$dbw->updateArray( 'cur',
Expand Down

0 comments on commit 2a03980

Please sign in to comment.