From f6d65e533c62f6deb21342d4901ece24497b433e Mon Sep 17 00:00:00 2001 From: Pierre Schmitz Date: Thu, 4 Jun 2015 07:31:04 +0200 Subject: Update to MediaWiki 1.25.1 --- includes/utils/ArrayUtils.php | 187 ----------- includes/utils/AutoloadGenerator.php | 296 ++++++++++++++++ includes/utils/Cdb.php | 163 --------- includes/utils/CdbDBA.php | 75 ----- includes/utils/CdbPHP.php | 494 --------------------------- includes/utils/IP.php | 23 +- includes/utils/MWCryptHKDF.php | 11 +- includes/utils/MWCryptRand.php | 11 - includes/utils/MWFunction.php | 37 +- includes/utils/StringUtils.php | 612 ---------------------------------- includes/utils/UIDGenerator.php | 6 +- includes/utils/ZipDirectoryReader.php | 1 + 12 files changed, 336 insertions(+), 1580 deletions(-) delete mode 100644 includes/utils/ArrayUtils.php create mode 100644 includes/utils/AutoloadGenerator.php delete mode 100644 includes/utils/Cdb.php delete mode 100644 includes/utils/CdbDBA.php delete mode 100644 includes/utils/CdbPHP.php delete mode 100644 includes/utils/StringUtils.php (limited to 'includes/utils') diff --git a/includes/utils/ArrayUtils.php b/includes/utils/ArrayUtils.php deleted file mode 100644 index 1e521cb8..00000000 --- a/includes/utils/ArrayUtils.php +++ /dev/null @@ -1,187 +0,0 @@ - $w ) { - $sum += $w; - # Do not return keys if they have 0 weight. - # Note that the "all 0 weight" case is handed above - if ( $w > 0 && $sum >= $rand ) { - break; - } - } - - return $i; - } - - /** - * Do a binary search, and return the index of the largest item that sorts - * less than or equal to the target value. - * - * @since 1.23 - * - * @param array $valueCallback A function to call to get the value with - * a given array index. - * @param int $valueCount The number of items accessible via $valueCallback, - * indexed from 0 to $valueCount - 1 - * @param array $comparisonCallback A callback to compare two values, returning - * -1, 0 or 1 in the style of strcmp(). - * @param string $target The target value to find. - * - * @return int|bool The item index of the lower bound, or false if the target value - * sorts before all items. - */ - public static function findLowerBound( $valueCallback, $valueCount, - $comparisonCallback, $target - ) { - if ( $valueCount === 0 ) { - return false; - } - - $min = 0; - $max = $valueCount; - do { - $mid = $min + ( ( $max - $min ) >> 1 ); - $item = call_user_func( $valueCallback, $mid ); - $comparison = call_user_func( $comparisonCallback, $target, $item ); - if ( $comparison > 0 ) { - $min = $mid; - } elseif ( $comparison == 0 ) { - $min = $mid; - break; - } else { - $max = $mid; - } - } while ( $min < $max - 1 ); - - if ( $min == 0 ) { - $item = call_user_func( $valueCallback, $min ); - $comparison = call_user_func( $comparisonCallback, $target, $item ); - if ( $comparison < 0 ) { - // Before the first item - return false; - } - } - return $min; - } - - /** - * Do array_diff_assoc() on multi-dimensional arrays. - * - * Note: empty arrays are removed. - * - * @since 1.23 - * - * @param array $array1 The array to compare from - * @param array $array2,... More arrays to compare against - * @return array An array containing all the values from array1 - * that are not present in any of the other arrays. - */ - public static function arrayDiffAssocRecursive( $array1 ) { - $arrays = func_get_args(); - array_shift( $arrays ); - $ret = array(); - - foreach ( $array1 as $key => $value ) { - if ( is_array( $value ) ) { - $args = array( $value ); - foreach ( $arrays as $array ) { - if ( isset( $array[$key] ) ) { - $args[] = $array[$key]; - } - } - $valueret = call_user_func_array( __METHOD__, $args ); - if ( count( $valueret ) ) { - $ret[$key] = $valueret; - } - } else { - foreach ( $arrays as $array ) { - if ( isset( $array[$key] ) && $array[$key] === $value ) { - continue 2; - } - } - $ret[$key] = $value; - } - } - - return $ret; - } -} diff --git a/includes/utils/AutoloadGenerator.php b/includes/utils/AutoloadGenerator.php new file mode 100644 index 00000000..9cf8cab5 --- /dev/null +++ b/includes/utils/AutoloadGenerator.php @@ -0,0 +1,296 @@ +readDir( __DIR__ . '/includes' ); + * $gen->readFile( __DIR__ . '/foo.php' ) + * $gen->generateAutoload(); + */ +class AutoloadGenerator { + /** + * @var string Root path of the project being scanned for classes + */ + protected $basepath; + + /** + * @var ClassCollector Helper class extracts class names from php files + */ + protected $collector; + + /** + * @var array Map of file shortpath to list of FQCN detected within file + */ + protected $classes = array(); + + /** + * @var string The global variable to write output to + */ + protected $variableName = 'wgAutoloadClasses'; + + /** + * @var array Map of FQCN to relative path(from self::$basepath) + */ + protected $overrides = array(); + + /** + * @param string $basepath Root path of the project being scanned for classes + * @param array|string $flags + * + * local - If this flag is set $wgAutoloadLocalClasses will be build instead + * of $wgAutoloadClasses + */ + public function __construct( $basepath, $flags = array() ) { + if ( !is_array( $flags ) ) { + $flags = array( $flags ); + } + $this->basepath = self::normalizePathSeparator( realpath( $basepath ) ); + $this->collector = new ClassCollector; + if ( in_array( 'local', $flags ) ) { + $this->variableName = 'wgAutoloadLocalClasses'; + } + } + + /** + * Force a class to be autoloaded from a specific path, regardless of where + * or if it was detected. + * + * @param string $fqcn FQCN to force the location of + * @param string $inputPath Full path to the file containing the class + * @throws Exception + */ + public function forceClassPath( $fqcn, $inputPath ) { + $path = self::normalizePathSeparator( realpath( $inputPath ) ); + if ( !$path ) { + throw new \Exception( "Invalid path: $inputPath" ); + } + $len = strlen( $this->basepath ); + if ( substr( $path, 0, $len ) !== $this->basepath ) { + throw new \Exception( "Path is not within basepath: $inputPath" ); + } + $shortpath = substr( $path, $len ); + $this->overrides[$fqcn] = $shortpath; + } + + /** + * @param string $inputPath Path to a php file to find classes within + * @throws Exception + */ + public function readFile( $inputPath ) { + // NOTE: do NOT expand $inputPath using realpath(). It is perfectly + // reasonable for LocalSettings.php and similiar files to be symlinks + // to files that are outside of $this->basepath. + $inputPath = self::normalizePathSeparator( $inputPath ); + $len = strlen( $this->basepath ); + if ( substr( $inputPath, 0, $len ) !== $this->basepath ) { + throw new \Exception( "Path is not within basepath: $inputPath" ); + } + $result = $this->collector->getClasses( + file_get_contents( $inputPath ) + ); + if ( $result ) { + $shortpath = substr( $inputPath, $len ); + $this->classes[$shortpath] = $result; + } + } + + /** + * @param string $dir Path to a directory to recursively search + * for php files with either .php or .inc extensions + */ + public function readDir( $dir ) { + $it = new RecursiveDirectoryIterator( + self::normalizePathSeparator( realpath( $dir ) ) ); + $it = new RecursiveIteratorIterator( $it ); + + foreach ( $it as $path => $file ) { + $ext = pathinfo( $path, PATHINFO_EXTENSION ); + // some older files in mw use .inc + if ( $ext === 'php' || $ext === 'inc' ) { + $this->readFile( $path ); + } + } + } + + /** + * Write out all known classes to autoload.php in + * the provided basedir + * + * @param string $commandName Value used in file comment to direct + * developers towards the appropriate way to update the autoload. + */ + public function generateAutoload( $commandName = 'AutoloadGenerator' ) { + $content = array(); + + // We need to generate a line each rather than exporting the + // full array so __DIR__ can be prepended to all the paths + $format = "%s => __DIR__ . %s,"; + foreach ( $this->classes as $path => $contained ) { + $exportedPath = var_export( $path, true ); + foreach ( $contained as $fqcn ) { + $content[$fqcn] = sprintf( + $format, + var_export( $fqcn, true ), + $exportedPath + ); + } + } + + foreach ( $this->overrides as $fqcn => $path ) { + $content[$fqcn] = sprintf( + $format, + var_export( $fqcn, true ), + var_export( $path, true ) + ); + } + + // sort for stable output + ksort( $content ); + + // extensions using this generator are appending to the existing + // autoload. + if ( $this->variableName === 'wgAutoloadClasses' ) { + $op = '+='; + } else { + $op = '='; + } + + $output = implode( "\n\t", $content ); + file_put_contents( + $this->basepath . '/autoload.php', + <<variableName}; + +\${$this->variableName} {$op} array( + {$output} +); + +EOD + ); + } + + /** + * Ensure that Unix-style path separators ("/") are used in the path. + * + * @param string $path + * @return string + */ + protected static function normalizePathSeparator( $path ) { + return str_replace( '\\', '/', $path ); + } +} + +/** + * Reads PHP code and returns the FQCN of every class defined within it. + */ +class ClassCollector { + + /** + * @var string Current namespace + */ + protected $namespace = ''; + + /** + * @var array List of FQCN detected in this pass + */ + protected $classes; + + /** + * @var array Token from token_get_all() that started an expect sequence + */ + protected $startToken; + + /** + * @var array List of tokens that are members of the current expect sequence + */ + protected $tokens; + + /** + * @var string $code PHP code (including namespace = ''; + $this->classes = array(); + $this->startToken = null; + $this->tokens = array(); + + foreach ( token_get_all( $code ) as $token ) { + if ( $this->startToken === null ) { + $this->tryBeginExpect( $token ); + } else { + $this->tryEndExpect( $token ); + } + } + + return $this->classes; + } + + /** + * Determine if $token begins the next expect sequence. + * + * @param array $token + */ + protected function tryBeginExpect( $token ) { + if ( is_string( $token ) ) { + return; + } + switch ( $token[0] ) { + case T_NAMESPACE: + case T_CLASS: + case T_INTERFACE: + $this->startToken = $token; + } + } + + /** + * Accepts the next token in an expect sequence + * + * @param array + */ + protected function tryEndExpect( $token ) { + switch ( $this->startToken[0] ) { + case T_NAMESPACE: + if ( $token === ';' || $token === '{' ) { + $this->namespace = $this->implodeTokens() . '\\'; + } else { + $this->tokens[] = $token; + } + break; + + case T_CLASS: + case T_INTERFACE: + $this->tokens[] = $token; + if ( is_array( $token ) && $token[0] === T_STRING ) { + $this->classes[] = $this->namespace . $this->implodeTokens(); + } + } + } + + /** + * Returns the string representation of the tokens within the + * current expect sequence and resets the sequence. + * + * @return string + */ + protected function implodeTokens() { + $content = array(); + foreach ( $this->tokens as $token ) { + $content[] = is_string( $token ) ? $token : $token[1]; + } + + $this->tokens = array(); + $this->startToken = null; + + return trim( implode( '', $content ), " \n\t" ); + } +} diff --git a/includes/utils/Cdb.php b/includes/utils/Cdb.php deleted file mode 100644 index 3ceb620f..00000000 --- a/includes/utils/Cdb.php +++ /dev/null @@ -1,163 +0,0 @@ -handle ) ) { - $this->close(); - } - } - - /** - * Are we running on Windows? - * @return bool - */ - protected function isWindows() { - return substr( php_uname(), 0, 7 ) == 'Windows'; - } -} - -/** - * Exception for Cdb errors. - * This explicitly doesn't subclass MWException to encourage reuse. - */ -class CdbException extends Exception { -} diff --git a/includes/utils/CdbDBA.php b/includes/utils/CdbDBA.php deleted file mode 100644 index efcaf21f..00000000 --- a/includes/utils/CdbDBA.php +++ /dev/null @@ -1,75 +0,0 @@ -handle = dba_open( $fileName, 'r-', 'cdb' ); - if ( !$this->handle ) { - throw new CdbException( 'Unable to open CDB file "' . $fileName . '"' ); - } - } - - public function close() { - if ( isset( $this->handle ) ) { - dba_close( $this->handle ); - } - unset( $this->handle ); - } - - public function get( $key ) { - return dba_fetch( $key, $this->handle ); - } -} - -/** - * Writer class which uses the DBA extension - */ -class CdbWriterDBA extends CdbWriter { - public function __construct( $fileName ) { - $this->realFileName = $fileName; - $this->tmpFileName = $fileName . '.tmp.' . mt_rand( 0, 0x7fffffff ); - $this->handle = dba_open( $this->tmpFileName, 'n', 'cdb_make' ); - if ( !$this->handle ) { - throw new CdbException( 'Unable to open CDB file for write "' . $fileName . '"' ); - } - } - - public function set( $key, $value ) { - return dba_insert( $key, $value, $this->handle ); - } - - public function close() { - if ( isset( $this->handle ) ) { - dba_close( $this->handle ); - } - if ( $this->isWindows() ) { - unlink( $this->realFileName ); - } - if ( !rename( $this->tmpFileName, $this->realFileName ) ) { - throw new CdbException( 'Unable to move the new CDB file into place.' ); - } - unset( $this->handle ); - } -} diff --git a/includes/utils/CdbPHP.php b/includes/utils/CdbPHP.php deleted file mode 100644 index 19d747a7..00000000 --- a/includes/utils/CdbPHP.php +++ /dev/null @@ -1,494 +0,0 @@ -> $b ) | ( 0x40000000 >> ( $b - 1 ) ); - } else { - return $a >> $b; - } - } - - /** - * The CDB hash function. - * - * @param string $s - * - * @return int - */ - public static function hash( $s ) { - $h = 5381; - $len = strlen( $s ); - for ( $i = 0; $i < $len; $i++ ) { - $h5 = ( $h << 5 ) & 0xffffffff; - // Do a 32-bit sum - // Inlined here for speed - $sum = ( $h & 0x3fffffff ) + ( $h5 & 0x3fffffff ); - $h = - ( - ( $sum & 0x40000000 ? 1 : 0 ) - + ( $h & 0x80000000 ? 2 : 0 ) - + ( $h & 0x40000000 ? 1 : 0 ) - + ( $h5 & 0x80000000 ? 2 : 0 ) - + ( $h5 & 0x40000000 ? 1 : 0 ) - ) << 30 - | ( $sum & 0x3fffffff ); - $h ^= ord( $s[$i] ); - $h &= 0xffffffff; - } - - return $h; - } -} - -/** - * CDB reader class - */ -class CdbReaderPHP extends CdbReader { - /** The filename */ - protected $fileName; - - /* number of hash slots searched under this key */ - protected $loop; - - /* initialized if loop is nonzero */ - protected $khash; - - /* initialized if loop is nonzero */ - protected $kpos; - - /* initialized if loop is nonzero */ - protected $hpos; - - /* initialized if loop is nonzero */ - protected $hslots; - - /* initialized if findNext() returns true */ - protected $dpos; - - /* initialized if cdb_findnext() returns 1 */ - protected $dlen; - - /** - * @param string $fileName - * @throws CdbException - */ - public function __construct( $fileName ) { - $this->fileName = $fileName; - $this->handle = fopen( $fileName, 'rb' ); - if ( !$this->handle ) { - throw new CdbException( 'Unable to open CDB file "' . $this->fileName . '".' ); - } - $this->findStart(); - } - - public function close() { - if ( isset( $this->handle ) ) { - fclose( $this->handle ); - } - unset( $this->handle ); - } - - /** - * @param mixed $key - * @return bool|string - */ - public function get( $key ) { - // strval is required - if ( $this->find( strval( $key ) ) ) { - return $this->read( $this->dlen, $this->dpos ); - } else { - return false; - } - } - - /** - * @param string $key - * @param int $pos - * @return bool - */ - protected function match( $key, $pos ) { - $buf = $this->read( strlen( $key ), $pos ); - - return $buf === $key; - } - - protected function findStart() { - $this->loop = 0; - } - - /** - * @throws CdbException - * @param int $length - * @param int $pos - * @return string - */ - protected function read( $length, $pos ) { - if ( fseek( $this->handle, $pos ) == -1 ) { - // This can easily happen if the internal pointers are incorrect - throw new CdbException( - 'Seek failed, file "' . $this->fileName . '" may be corrupted.' ); - } - - if ( $length == 0 ) { - return ''; - } - - $buf = fread( $this->handle, $length ); - if ( $buf === false || strlen( $buf ) !== $length ) { - throw new CdbException( - 'Read from CDB file failed, file "' . $this->fileName . '" may be corrupted.' ); - } - - return $buf; - } - - /** - * Unpack an unsigned integer and throw an exception if it needs more than 31 bits - * @param string $s - * @throws CdbException - * @return mixed - */ - protected function unpack31( $s ) { - $data = unpack( 'V', $s ); - if ( $data[1] > 0x7fffffff ) { - throw new CdbException( - 'Error in CDB file "' . $this->fileName . '", integer too big.' ); - } - - return $data[1]; - } - - /** - * Unpack a 32-bit signed integer - * @param string $s - * @return int - */ - protected function unpackSigned( $s ) { - $data = unpack( 'va/vb', $s ); - - return $data['a'] | ( $data['b'] << 16 ); - } - - /** - * @param string $key - * @return bool - */ - protected function findNext( $key ) { - if ( !$this->loop ) { - $u = CdbFunctions::hash( $key ); - $buf = $this->read( 8, ( $u << 3 ) & 2047 ); - $this->hslots = $this->unpack31( substr( $buf, 4 ) ); - if ( !$this->hslots ) { - return false; - } - $this->hpos = $this->unpack31( substr( $buf, 0, 4 ) ); - $this->khash = $u; - $u = CdbFunctions::unsignedShiftRight( $u, 8 ); - $u = CdbFunctions::unsignedMod( $u, $this->hslots ); - $u <<= 3; - $this->kpos = $this->hpos + $u; - } - - while ( $this->loop < $this->hslots ) { - $buf = $this->read( 8, $this->kpos ); - $pos = $this->unpack31( substr( $buf, 4 ) ); - if ( !$pos ) { - return false; - } - $this->loop += 1; - $this->kpos += 8; - if ( $this->kpos == $this->hpos + ( $this->hslots << 3 ) ) { - $this->kpos = $this->hpos; - } - $u = $this->unpackSigned( substr( $buf, 0, 4 ) ); - if ( $u === $this->khash ) { - $buf = $this->read( 8, $pos ); - $keyLen = $this->unpack31( substr( $buf, 0, 4 ) ); - if ( $keyLen == strlen( $key ) && $this->match( $key, $pos + 8 ) ) { - // Found - $this->dlen = $this->unpack31( substr( $buf, 4 ) ); - $this->dpos = $pos + 8 + $keyLen; - - return true; - } - } - } - - return false; - } - - /** - * @param mixed $key - * @return bool - */ - protected function find( $key ) { - $this->findStart(); - - return $this->findNext( $key ); - } -} - -/** - * CDB writer class - */ -class CdbWriterPHP extends CdbWriter { - protected $hplist; - - protected $numentries; - - protected $pos; - - /** - * @param string $fileName - */ - public function __construct( $fileName ) { - $this->realFileName = $fileName; - $this->tmpFileName = $fileName . '.tmp.' . mt_rand( 0, 0x7fffffff ); - $this->handle = fopen( $this->tmpFileName, 'wb' ); - if ( !$this->handle ) { - $this->throwException( - 'Unable to open CDB file "' . $this->tmpFileName . '" for write.' ); - } - $this->hplist = array(); - $this->numentries = 0; - $this->pos = 2048; // leaving space for the pointer array, 256 * 8 - if ( fseek( $this->handle, $this->pos ) == -1 ) { - $this->throwException( 'fseek failed in file "' . $this->tmpFileName . '".' ); - } - } - - /** - * @param string $key - * @param string $value - */ - public function set( $key, $value ) { - if ( strval( $key ) === '' ) { - // DBA cross-check hack - return; - } - $this->addbegin( strlen( $key ), strlen( $value ) ); - $this->write( $key ); - $this->write( $value ); - $this->addend( strlen( $key ), strlen( $value ), CdbFunctions::hash( $key ) ); - } - - /** - * @throws CdbException - */ - public function close() { - $this->finish(); - if ( isset( $this->handle ) ) { - fclose( $this->handle ); - } - if ( $this->isWindows() && file_exists( $this->realFileName ) ) { - unlink( $this->realFileName ); - } - if ( !rename( $this->tmpFileName, $this->realFileName ) ) { - $this->throwException( 'Unable to move the new CDB file into place.' ); - } - unset( $this->handle ); - } - - /** - * @throws CdbException - * @param string $buf - */ - protected function write( $buf ) { - $len = fwrite( $this->handle, $buf ); - if ( $len !== strlen( $buf ) ) { - $this->throwException( 'Error writing to CDB file "' . $this->tmpFileName . '".' ); - } - } - - /** - * @throws CdbException - * @param int $len - */ - protected function posplus( $len ) { - $newpos = $this->pos + $len; - if ( $newpos > 0x7fffffff ) { - $this->throwException( - 'A value in the CDB file "' . $this->tmpFileName . '" is too large.' ); - } - $this->pos = $newpos; - } - - /** - * @param int $keylen - * @param int $datalen - * @param int $h - */ - protected function addend( $keylen, $datalen, $h ) { - $this->hplist[] = array( - 'h' => $h, - 'p' => $this->pos - ); - - $this->numentries++; - $this->posplus( 8 ); - $this->posplus( $keylen ); - $this->posplus( $datalen ); - } - - /** - * @throws CdbException - * @param int $keylen - * @param int $datalen - */ - protected function addbegin( $keylen, $datalen ) { - if ( $keylen > 0x7fffffff ) { - $this->throwException( 'Key length too long in file "' . $this->tmpFileName . '".' ); - } - if ( $datalen > 0x7fffffff ) { - $this->throwException( 'Data length too long in file "' . $this->tmpFileName . '".' ); - } - $buf = pack( 'VV', $keylen, $datalen ); - $this->write( $buf ); - } - - /** - * @throws CdbException - */ - protected function finish() { - // Hack for DBA cross-check - $this->hplist = array_reverse( $this->hplist ); - - // Calculate the number of items that will be in each hashtable - $counts = array_fill( 0, 256, 0 ); - foreach ( $this->hplist as $item ) { - ++$counts[255 & $item['h']]; - } - - // Fill in $starts with the *end* indexes - $starts = array(); - $pos = 0; - for ( $i = 0; $i < 256; ++$i ) { - $pos += $counts[$i]; - $starts[$i] = $pos; - } - - // Excessively clever and indulgent code to simultaneously fill $packedTables - // with the packed hashtables, and adjust the elements of $starts - // to actually point to the starts instead of the ends. - $packedTables = array_fill( 0, $this->numentries, false ); - foreach ( $this->hplist as $item ) { - $packedTables[--$starts[255 & $item['h']]] = $item; - } - - $final = ''; - for ( $i = 0; $i < 256; ++$i ) { - $count = $counts[$i]; - - // The size of the hashtable will be double the item count. - // The rest of the slots will be empty. - $len = $count + $count; - $final .= pack( 'VV', $this->pos, $len ); - - $hashtable = array(); - for ( $u = 0; $u < $len; ++$u ) { - $hashtable[$u] = array( 'h' => 0, 'p' => 0 ); - } - - // Fill the hashtable, using the next empty slot if the hashed slot - // is taken. - for ( $u = 0; $u < $count; ++$u ) { - $hp = $packedTables[$starts[$i] + $u]; - $where = CdbFunctions::unsignedMod( - CdbFunctions::unsignedShiftRight( $hp['h'], 8 ), $len ); - while ( $hashtable[$where]['p'] ) { - if ( ++$where == $len ) { - $where = 0; - } - } - $hashtable[$where] = $hp; - } - - // Write the hashtable - for ( $u = 0; $u < $len; ++$u ) { - $buf = pack( 'vvV', - $hashtable[$u]['h'] & 0xffff, - CdbFunctions::unsignedShiftRight( $hashtable[$u]['h'], 16 ), - $hashtable[$u]['p'] ); - $this->write( $buf ); - $this->posplus( 8 ); - } - } - - // Write the pointer array at the start of the file - rewind( $this->handle ); - if ( ftell( $this->handle ) != 0 ) { - $this->throwException( 'Error rewinding to start of file "' . $this->tmpFileName . '".' ); - } - $this->write( $final ); - } - - /** - * Clean up the temp file and throw an exception - * - * @param string $msg - * @throws CdbException - */ - protected function throwException( $msg ) { - if ( $this->handle ) { - fclose( $this->handle ); - unlink( $this->tmpFileName ); - } - throw new CdbException( $msg ); - } -} diff --git a/includes/utils/IP.php b/includes/utils/IP.php index 0e2db8cc..4441236d 100644 --- a/includes/utils/IP.php +++ b/includes/utils/IP.php @@ -628,6 +628,25 @@ class IP { strcmp( $hexIP, $end ) <= 0 ); } + /** + * Determines if an IP address is a list of CIDR a.b.c.d/n ranges. + * + * @since 1.25 + * + * @param string $ip the IP to check + * @param array $ranges the IP ranges, each element a range + * + * @return bool true if the specified adress belongs to the specified range; otherwise, false. + */ + public static function isInRanges( $ip, $ranges ) { + foreach ( $ranges as $range ) { + if ( self::isInRange( $ip, $range ) ) { + return true; + } + } + return false; + } + /** * Convert some unusual representations of IPv4 addresses to their * canonical dotted quad representation. @@ -698,7 +717,7 @@ class IP { */ public static function isTrustedProxy( $ip ) { $trusted = self::isConfiguredProxy( $ip ); - wfRunHooks( 'IsTrustedProxy', array( &$ip, &$trusted ) ); + Hooks::run( 'IsTrustedProxy', array( &$ip, &$trusted ) ); return $trusted; } @@ -712,7 +731,6 @@ class IP { public static function isConfiguredProxy( $ip ) { global $wgSquidServers, $wgSquidServersNoPurge; - wfProfileIn( __METHOD__ ); // Quick check of known singular proxy servers $trusted = in_array( $ip, $wgSquidServers ); @@ -723,7 +741,6 @@ class IP { } $trusted = self::$proxyIpSet->match( $ip ); } - wfProfileOut( __METHOD__ ); return $trusted; } diff --git a/includes/utils/MWCryptHKDF.php b/includes/utils/MWCryptHKDF.php index cc136793..950dd846 100644 --- a/includes/utils/MWCryptHKDF.php +++ b/includes/utils/MWCryptHKDF.php @@ -103,6 +103,7 @@ class MWCryptHKDF { * @param string $algorithm Name of hashing algorithm * @param BagOStuff $cache * @param string|array $context Context to mix into HKDF context + * @throws MWException */ public function __construct( $secretKeyMaterial, $algorithm, $cache, $context ) { if ( strlen( $secretKeyMaterial ) < 16 ) { @@ -157,6 +158,7 @@ class MWCryptHKDF { /** * Return a singleton instance, based on the global configs. * @return HKDF + * @throws MWException */ protected static function singleton() { global $wgHKDFAlgorithm, $wgHKDFSecret, $wgSecretKey; @@ -271,14 +273,15 @@ class MWCryptHKDF { * * @param string $hash Hashing Algorithm * @param string $prk A pseudorandom key of at least HashLen octets - * (usually, the output from the extract step) + * (usually, the output from the extract step) * @param string $info Optional context and application specific information - * (can be a zero-length string) + * (can be a zero-length string) * @param int $bytes Length of output keying material in bytes - * (<= 255*HashLen) + * (<= 255*HashLen) * @param string &$lastK Set by this function to the last block of the expansion. - * In MediaWiki, this is used to seed future Extractions. + * In MediaWiki, this is used to seed future Extractions. * @return string Cryptographically secure random string $bytes long + * @throws MWException */ private static function HKDFExpand( $hash, $prk, $info, $bytes, &$lastK = '' ) { $hashLen = MWCryptHKDF::$hashLength[$hash]; diff --git a/includes/utils/MWCryptRand.php b/includes/utils/MWCryptRand.php index b602f78e..e6c0e784 100644 --- a/includes/utils/MWCryptRand.php +++ b/includes/utils/MWCryptRand.php @@ -294,7 +294,6 @@ class MWCryptRand { * @see self::generate() */ public function realGenerate( $bytes, $forceStrong = false ) { - wfProfileIn( __METHOD__ ); wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " . wfGetAllCallers( 5 ) . "\n" ); @@ -314,7 +313,6 @@ class MWCryptRand { // entropy so this is also preferable to just trying to read urandom because it may work // on Windows systems as well. if ( function_exists( 'mcrypt_create_iv' ) ) { - wfProfileIn( __METHOD__ . '-mcrypt' ); $rem = $bytes - strlen( $buffer ); $iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM ); if ( $iv === false ) { @@ -324,7 +322,6 @@ class MWCryptRand { wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) . " bytes of randomness.\n" ); } - wfProfileOut( __METHOD__ . '-mcrypt' ); } } @@ -337,7 +334,6 @@ class MWCryptRand { if ( function_exists( 'openssl_random_pseudo_bytes' ) && ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) ) ) { - wfProfileIn( __METHOD__ . '-openssl' ); $rem = $bytes - strlen( $buffer ); $openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong ); if ( $openssl_bytes === false ) { @@ -353,7 +349,6 @@ class MWCryptRand { // using it use it's say on whether the randomness is strong $this->strong = !!$openssl_strong; } - wfProfileOut( __METHOD__ . '-openssl' ); } } @@ -361,7 +356,6 @@ class MWCryptRand { if ( strlen( $buffer ) < $bytes && ( function_exists( 'stream_set_read_buffer' ) || $forceStrong ) ) { - wfProfileIn( __METHOD__ . '-fopen-urandom' ); $rem = $bytes - strlen( $buffer ); if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) { wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom " . @@ -400,7 +394,6 @@ class MWCryptRand { } else { wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" ); } - wfProfileOut( __METHOD__ . '-fopen-urandom' ); } // If we cannot use or generate enough data from a secure source @@ -414,12 +407,10 @@ class MWCryptRand { ": Falling back to using a pseudo random state to generate randomness.\n" ); } while ( strlen( $buffer ) < $bytes ) { - wfProfileIn( __METHOD__ . '-fallback' ); $buffer .= $this->hmac( $this->randomState(), mt_rand() ); // This code is never really cryptographically strong, if we use it // at all, then set strong to false. $this->strong = false; - wfProfileOut( __METHOD__ . '-fallback' ); } // Once the buffer has been filled up with enough random data to fulfill @@ -431,8 +422,6 @@ class MWCryptRand { wfDebug( __METHOD__ . ": " . strlen( $buffer ) . " bytes of randomness leftover in the buffer.\n" ); - wfProfileOut( __METHOD__ ); - return $generated; } diff --git a/includes/utils/MWFunction.php b/includes/utils/MWFunction.php index 3a0492dc..fa7eebe8 100644 --- a/includes/utils/MWFunction.php +++ b/includes/utils/MWFunction.php @@ -22,42 +22,19 @@ class MWFunction { - /** - * @deprecated since 1.22; use call_user_func() - * @param callable $callback - * @return mixed - */ - public static function call( $callback ) { - wfDeprecated( __METHOD__, '1.22' ); - $args = func_get_args(); - - return call_user_func_array( 'call_user_func', $args ); - } - - /** - * @deprecated since 1.22; use call_user_func_array() - * @param callable $callback - * @param array $argsarams - * @return mixed - */ - public static function callArray( $callback, $argsarams ) { - wfDeprecated( __METHOD__, '1.22' ); - - return call_user_func_array( $callback, $argsarams ); - } - /** * @param string $class * @param array $args * @return object + * @deprecated 1.25 Use ObjectFactory::getObjectFromSpec() instead */ public static function newObj( $class, $args = array() ) { - if ( !count( $args ) ) { - return new $class; - } - - $ref = new ReflectionClass( $class ); + wfDeprecated( __METHOD__, '1.25' ); - return $ref->newInstanceArgs( $args ); + return ObjectFactory::getObjectFromSpec( array( + 'class' => $class, + 'args' => $args, + 'closure_expansion' => false, + ) ); } } diff --git a/includes/utils/StringUtils.php b/includes/utils/StringUtils.php deleted file mode 100644 index 86f45122..00000000 --- a/includes/utils/StringUtils.php +++ /dev/null @@ -1,612 +0,0 @@ -cb(), $subject, $flags ); - } - - /** - * More or less "markup-safe" explode() - * Ignores any instances of the separator inside <...> - * @param string $separator - * @param string $text - * @return array - */ - static function explodeMarkup( $separator, $text ) { - $placeholder = "\x00"; - - // Remove placeholder instances - $text = str_replace( $placeholder, '', $text ); - - // Replace instances of the separator inside HTML-like tags with the placeholder - $replacer = new DoubleReplacer( $separator, $placeholder ); - $cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text ); - - // Explode, then put the replaced separators back in - $items = explode( $separator, $cleaned ); - foreach ( $items as $i => $str ) { - $items[$i] = str_replace( $placeholder, $separator, $str ); - } - - return $items; - } - - /** - * Escape a string to make it suitable for inclusion in a preg_replace() - * replacement parameter. - * - * @param string $string - * @return string - */ - static function escapeRegexReplacement( $string ) { - $string = str_replace( '\\', '\\\\', $string ); - $string = str_replace( '$', '\\$', $string ); - - return $string; - } - - /** - * Workalike for explode() with limited memory usage. - * Returns an Iterator - * @param string $separator - * @param string $subject - * @return ArrayIterator|ExplodeIterator - */ - static function explode( $separator, $subject ) { - if ( substr_count( $subject, $separator ) > 1000 ) { - return new ExplodeIterator( $separator, $subject ); - } else { - return new ArrayIterator( explode( $separator, $subject ) ); - } - } -} - -/** - * Base class for "replacers", objects used in preg_replace_callback() and - * StringUtils::delimiterReplaceCallback() - */ -class Replacer { - /** - * @return array - */ - function cb() { - return array( &$this, 'replace' ); - } -} - -/** - * Class to replace regex matches with a string similar to that used in preg_replace() - */ -class RegexlikeReplacer extends Replacer { - private $r; - - /** - * @param string $r - */ - function __construct( $r ) { - $this->r = $r; - } - - /** - * @param array $matches - * @return string - */ - function replace( $matches ) { - $pairs = array(); - foreach ( $matches as $i => $match ) { - $pairs["\$$i"] = $match; - } - - return strtr( $this->r, $pairs ); - } -} - -/** - * Class to perform secondary replacement within each replacement string - */ -class DoubleReplacer extends Replacer { - /** - * @param mixed $from - * @param mixed $to - * @param int $index - */ - function __construct( $from, $to, $index = 0 ) { - $this->from = $from; - $this->to = $to; - $this->index = $index; - } - - /** - * @param array $matches - * @return mixed - */ - function replace( $matches ) { - return str_replace( $this->from, $this->to, $matches[$this->index] ); - } -} - -/** - * Class to perform replacement based on a simple hashtable lookup - */ -class HashtableReplacer extends Replacer { - private $table, $index; - - /** - * @param array $table - * @param int $index - */ - function __construct( $table, $index = 0 ) { - $this->table = $table; - $this->index = $index; - } - - /** - * @param array $matches - * @return mixed - */ - function replace( $matches ) { - return $this->table[$matches[$this->index]]; - } -} - -/** - * Replacement array for FSS with fallback to strtr() - * Supports lazy initialisation of FSS resource - */ -class ReplacementArray { - private $data = false; - private $fss = false; - - /** - * Create an object with the specified replacement array - * The array should have the same form as the replacement array for strtr() - * @param array $data - */ - function __construct( $data = array() ) { - $this->data = $data; - } - - /** - * @return array - */ - function __sleep() { - return array( 'data' ); - } - - function __wakeup() { - $this->fss = false; - } - - /** - * Set the whole replacement array at once - * @param array $data - */ - function setArray( $data ) { - $this->data = $data; - $this->fss = false; - } - - /** - * @return array|bool - */ - function getArray() { - return $this->data; - } - - /** - * Set an element of the replacement array - * @param string $from - * @param string $to - */ - function setPair( $from, $to ) { - $this->data[$from] = $to; - $this->fss = false; - } - - /** - * @param array $data - */ - function mergeArray( $data ) { - $this->data = array_merge( $this->data, $data ); - $this->fss = false; - } - - /** - * @param ReplacementArray $other - */ - function merge( $other ) { - $this->data = array_merge( $this->data, $other->data ); - $this->fss = false; - } - - /** - * @param string $from - */ - function removePair( $from ) { - unset( $this->data[$from] ); - $this->fss = false; - } - - /** - * @param array $data - */ - function removeArray( $data ) { - foreach ( $data as $from => $to ) { - $this->removePair( $from ); - } - $this->fss = false; - } - - /** - * @param string $subject - * @return string - */ - function replace( $subject ) { - if ( function_exists( 'fss_prep_replace' ) ) { - wfProfileIn( __METHOD__ . '-fss' ); - if ( $this->fss === false ) { - $this->fss = fss_prep_replace( $this->data ); - } - $result = fss_exec_replace( $this->fss, $subject ); - wfProfileOut( __METHOD__ . '-fss' ); - } else { - wfProfileIn( __METHOD__ . '-strtr' ); - $result = strtr( $subject, $this->data ); - wfProfileOut( __METHOD__ . '-strtr' ); - } - - return $result; - } -} - -/** - * An iterator which works exactly like: - * - * foreach ( explode( $delim, $s ) as $element ) { - * ... - * } - * - * Except it doesn't use 193 byte per element - */ -class ExplodeIterator implements Iterator { - // The subject string - private $subject, $subjectLength; - - // The delimiter - private $delim, $delimLength; - - // The position of the start of the line - private $curPos; - - // The position after the end of the next delimiter - private $endPos; - - // The current token - private $current; - - /** - * Construct a DelimIterator - * @param string $delim - * @param string $subject - */ - function __construct( $delim, $subject ) { - $this->subject = $subject; - $this->delim = $delim; - - // Micro-optimisation (theoretical) - $this->subjectLength = strlen( $subject ); - $this->delimLength = strlen( $delim ); - - $this->rewind(); - } - - function rewind() { - $this->curPos = 0; - $this->endPos = strpos( $this->subject, $this->delim ); - $this->refreshCurrent(); - } - - function refreshCurrent() { - if ( $this->curPos === false ) { - $this->current = false; - } elseif ( $this->curPos >= $this->subjectLength ) { - $this->current = ''; - } elseif ( $this->endPos === false ) { - $this->current = substr( $this->subject, $this->curPos ); - } else { - $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos ); - } - } - - function current() { - return $this->current; - } - - /** - * @return int|bool Current position or boolean false if invalid - */ - function key() { - return $this->curPos; - } - - /** - * @return string - */ - function next() { - if ( $this->endPos === false ) { - $this->curPos = false; - } else { - $this->curPos = $this->endPos + $this->delimLength; - if ( $this->curPos >= $this->subjectLength ) { - $this->endPos = false; - } else { - $this->endPos = strpos( $this->subject, $this->delim, $this->curPos ); - } - } - $this->refreshCurrent(); - - return $this->current; - } - - /** - * @return bool - */ - function valid() { - return $this->curPos !== false; - } -} diff --git a/includes/utils/UIDGenerator.php b/includes/utils/UIDGenerator.php index 5346afa6..92415877 100644 --- a/includes/utils/UIDGenerator.php +++ b/includes/utils/UIDGenerator.php @@ -119,6 +119,7 @@ class UIDGenerator { /** * @param array $info (UIDGenerator::millitime(), counter, clock sequence) * @return string 88 bits + * @throws MWException */ protected function getTimestampedID88( array $info ) { list( $time, $counter ) = $info; @@ -163,6 +164,7 @@ class UIDGenerator { /** * @param array $info (UIDGenerator::millitime(), counter, clock sequence) * @return string 128 bits + * @throws MWException */ protected function getTimestampedID128( array $info ) { list( $time, $counter, $clkSeq ) = $info; @@ -260,6 +262,7 @@ class UIDGenerator { * @param int $count Number of IDs to return (1 to 10000) * @param int $flags (supports UIDGenerator::QUICK_VOLATILE) * @return array Ordered list of float integer values + * @throws MWException */ protected function getSequentialPerNodeIDs( $bucket, $bits, $count, $flags ) { if ( $count <= 0 ) { @@ -278,7 +281,7 @@ class UIDGenerator { if ( ( $flags & self::QUICK_VOLATILE ) && PHP_SAPI !== 'cli' ) { try { $cache = ObjectCache::newAccelerator( array() ); - } catch ( MWException $e ) { + } catch ( Exception $e ) { // not supported } } @@ -436,6 +439,7 @@ class UIDGenerator { /** * @param array $time Result of UIDGenerator::millitime() * @return string 46 MSBs of "milliseconds since epoch" in binary (rolls over in 4201) + * @throws MWException */ protected function millisecondsSinceEpochBinary( array $time ) { list( $sec, $msec ) = $time; diff --git a/includes/utils/ZipDirectoryReader.php b/includes/utils/ZipDirectoryReader.php index bc849766..86960aa1 100644 --- a/includes/utils/ZipDirectoryReader.php +++ b/includes/utils/ZipDirectoryReader.php @@ -186,6 +186,7 @@ class ZipDirectoryReader { * Throw an error, and log a debug message * @param mixed $code * @param string $debugMessage + * @throws ZipDirectoryReaderError */ function error( $code, $debugMessage ) { wfDebug( __CLASS__ . ": Fatal error: $debugMessage\n" ); -- cgit v1.2.2