| 1 | <?php |
| 2 | /** |
| 3 | * This program is free software; you can redistribute it and/or modify |
| 4 | * it under the terms of the GNU General Public License as published by |
| 5 | * the Free Software Foundation; either version 2 of the License, or |
| 6 | * (at your option) any later version. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, |
| 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU General Public License along |
| 14 | * with this program; if not, write to the Free Software Foundation, Inc., |
| 15 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 16 | * |
| 17 | */ |
| 18 | |
| 19 | /** |
| 20 | * Server-side helper for client-side compressed content. |
| 21 | * |
| 22 | * @since 1.32 |
| 23 | */ |
| 24 | class Deflate { |
| 25 | |
| 26 | /** |
| 27 | * Whether the content is deflated |
| 28 | * |
| 29 | * @param string $data |
| 30 | * |
| 31 | * @return bool |
| 32 | */ |
| 33 | public static function isDeflated( string $data ): bool { |
| 34 | return substr( $data, 0, 11 ) === 'rawdeflate,'; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * For content that has been compressed with deflate in the client, |
| 39 | * try to uncompress it with inflate. |
| 40 | * |
| 41 | * If data is not prefixed with 'rawdeflate,' it will be returned unmodified. |
| 42 | * |
| 43 | * Data can be compressed in the client using the 'mediawiki.deflate' module: |
| 44 | * |
| 45 | * @code |
| 46 | * mw.loader.using( 'mediawiki.deflate' ).then( function () { |
| 47 | * var deflated = mw.deflate( myContent ); |
| 48 | * } ); |
| 49 | * @endcode |
| 50 | * |
| 51 | * @param string $data Deflated data |
| 52 | * @return StatusValue Inflated data will be set as the value |
| 53 | * @throws InvalidArgumentException If the data wasn't deflated |
| 54 | */ |
| 55 | public static function inflate( string $data ): StatusValue { |
| 56 | if ( !self::isDeflated( $data ) ) { |
| 57 | throw new InvalidArgumentException( 'Data does not begin with deflated prefix' ); |
| 58 | } |
| 59 | $deflated = base64_decode( substr( $data, 11 ), true ); |
| 60 | if ( $deflated === false ) { |
| 61 | return StatusValue::newFatal( 'deflate-invaliddeflate' ); |
| 62 | } |
| 63 | // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged |
| 64 | $inflated = @gzinflate( $deflated ); |
| 65 | if ( $inflated === false ) { |
| 66 | return StatusValue::newFatal( 'deflate-invaliddeflate' ); |
| 67 | } |
| 68 | return StatusValue::newGood( $inflated ); |
| 69 | } |
| 70 | } |