$file_size - $length ) { throw new InvalidDatabaseException( 'The MaxMind DB file contains bad data (a read past the end of the file).' ); } if ( 0 !== fseek( $handle, $offset ) ) { throw new InvalidDatabaseException( 'The MaxMind DB file contains bad data (a seek failed).' ); } // A single fread() may return less than asked (PHP streams hand back at // most one buffer's worth on some builds), so read until the length is // complete, or until the stream stops making progress. $chunks = array(); $received = 0; while ( $received < $length ) { $wanted = $length - $received; if ( $wanted < 1 ) { break; } $chunk = fread( $handle, $wanted ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- random access into a database file; WP_Filesystem has no seek-and-read. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- random access into a database file; WP_Filesystem has no seek-and-read. if ( false === $chunk || '' === $chunk ) { break; } $chunks[] = $chunk; $received += strlen( $chunk ); } if ( $received !== $length ) { throw new InvalidDatabaseException( 'The MaxMind DB file contains bad data (a short read).' ); } return implode( '', $chunks ); } /** * A big-endian unsigned integer of up to seven bytes, which always fits * a PHP int. Pointers, size extensions, and fixed-width scalars use it. */ public static function unsigned( string $bytes ): int { $value = 0; for ( $i = 0, $length = strlen( $bytes ); $i < $length; ++$i ) { $value = ( $value << 8 ) | ord( $bytes[ $i ] ); } return $value; } /** * A big-endian unsigned integer of up to sixteen bytes: an int when it * fits PHP_INT_MAX, otherwise its exact decimal digits as a string. * * @return int|string */ public static function unsigned_value( string $bytes ) { if ( strlen( $bytes ) <= 7 ) { return self::unsigned( $bytes ); } $decimal = self::decimal( $bytes ); $fits = strlen( $decimal ) < 19 || ( 19 === strlen( $decimal ) && strcmp( $decimal, (string) PHP_INT_MAX ) <= 0 ); return $fits ? (int) $decimal : $decimal; } /** * The exact decimal form of a big-endian unsigned integer, with no * GMP or BCMath: multiply the running total by 256 and add each byte. */ private static function decimal( string $bytes ): string { $digits = array( 0 ); // Little-endian base-10 digits. for ( $i = 0, $length = strlen( $bytes ); $i < $length; ++$i ) { $carry = ord( $bytes[ $i ] ); foreach ( $digits as $position => $digit ) { $value = $digit * 256 + $carry; $digits[ $position ] = $value % 10; $carry = intdiv( $value, 10 ); } while ( $carry > 0 ) { $digits[] = $carry % 10; $carry = intdiv( $carry, 10 ); } } $decimal = ltrim( implode( '', array_reverse( $digits ) ), '0' ); return '' === $decimal ? '0' : $decimal; } }