| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\User\TempUser; |
| 4 |
|
| 5 |
use LogicException; |
| 6 |
use OutOfBoundsException; |
| 7 |
use RuntimeException; |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
class ScrambleMapping implements SerialMapping { |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
private const GENERATORS = [ |
| 50 |
[ 56, 97 ], |
| 51 |
[ 511, 887 ], |
| 52 |
[ 5203, 9013 ], |
| 53 |
[ 51947, 90001 ], |
| 54 |
[ 519612, 900001 ], |
| 55 |
[ 5196144, 8999993 ], |
| 56 |
[ 51961523, 89999999 ], |
| 57 |
[ 519615218, 899999963 ], |
| 58 |
[ 5196152444, 9000000043 ], |
| 59 |
]; |
| 60 |
|
| 61 |
|
| 62 |
private $offset; |
| 63 |
|
| 64 |
|
| 65 |
private $hasGmp; |
| 66 |
|
| 67 |
private $hasBcm; |
| 68 |
|
| 69 |
public function __construct( $config ) { |
| 70 |
$this->offset = $config['offset'] ?? 0; |
| 71 |
$this->hasGmp = extension_loaded( 'gmp' ); |
| 72 |
$this->hasBcm = extension_loaded( 'bcmath' ); |
| 73 |
if ( !$this->hasGmp && !$this->hasBcm ) { |
| 74 |
throw new RuntimeException( __CLASS__ . ' requires the bcmath or gmp extension' ); |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
public function getSerialIdForIndex( int $index ): string { |
| 79 |
if ( $index <= 0 ) { |
| 80 |
return (string)$index; |
| 81 |
} |
| 82 |
$offset = $this->offset; |
| 83 |
if ( $index - $offset < 0 ) { |
| 84 |
throw new OutOfBoundsException( __METHOD__ . ": The configured offset $offset is too large." ); |
| 85 |
} |
| 86 |
foreach ( self::GENERATORS as [ $g, $p ] ) { |
| 87 |
if ( $index - $offset < $p ) { |
| 88 |
return (string)( $offset + $this->powmod( $g, $index - $offset, $p ) ); |
| 89 |
} |
| 90 |
$offset += $p - 1; |
| 91 |
} |
| 92 |
throw new RuntimeException( __METHOD__ . ": The index $index is too large" ); |
| 93 |
} |
| 94 |
|
| 95 |
private function powmod( $num, $exponent, $modulus ) { |
| 96 |
if ( $this->hasGmp ) { |
| 97 |
return \gmp_intval( \gmp_powm( $num, $exponent, $modulus ) ); |
| 98 |
} elseif ( $this->hasBcm ) { |
| 99 |
return (int)\bcpowmod( (string)$num, (string)$exponent, (string)$modulus ); |
| 100 |
} else { |
| 101 |
throw new LogicException( __CLASS__ . ' requires the bcmath or gmp extension' ); |
| 102 |
} |
| 103 |
} |
| 104 |
} |