StreamedPart.php 11.8 KB
Newer Older
1 2 3 4 5 6 7 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
<?php

/*
 * This file is part of the MultiPartParser package.
 *
 * (c) Romain Cambien <romain@cambien.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Riverline\MultiPartParser;

/**
 * Class StreamedPart
 */
class StreamedPart
{
    /**
     * @var resource
     */
    private $stream;

    /**
     * @var array
     */
    private $headers;

    /**
     * @var int
     */
    private $bodyOffset;

    /**
     * @var StreamedPart[]
     */
    private $parts = array();

    /**
     * The length of the EOL character.
     *
     * @var int
     */
    private $EOLCharacterLength;

    /**
     * StreamParser constructor.
     *
     * @param resource $stream
     * @param int $EOLCharacterLength
     */
    public function __construct($stream, $EOLCharacterLength = 2)
    {
        if (false === is_resource($stream)) {
            throw new \InvalidArgumentException('Input is not a stream');
        }

        if (false === is_integer($EOLCharacterLength)) {
            throw new \InvalidArgumentException('EOL Length is not an integer');
        }

        $this->stream = $stream;
        $this->EOLCharacterLength = $EOLCharacterLength;

        // Reset the stream
        rewind($this->stream);

        // Parse headers
        $endOfHeaders = false;
        $bufferSize = 8192;
        $headerLines = [];
        $buffer = '';

        while (false !== ($line = fgets($this->stream, $bufferSize))) {
            // Append to buffer
            $buffer .= rtrim($line, "\r\n");

            if (strlen($line) === $bufferSize-1) {
                // EOL not reached, continue
                continue;
            }

            if ('' === $buffer) {
                // Empty line cause by double new line, we reached the end of the headers section
                $endOfHeaders = true;
                break;
            }

            // Detect horizontal whitescapes before header
            $trimmed = ltrim($buffer);
            if (strlen($buffer) > strlen($trimmed)) {
                // Multi lines header, append to previous line
                $headerLines[count($headerLines)-1] .= "\x20".$trimmed;
            } else {
                $headerLines[] = $buffer;
            }

            // Reset buffer
            $buffer = '';
        }

        if (false === $endOfHeaders) {
            throw new \InvalidArgumentException('Content is not valid');
        }

        $this->headers = [];
        foreach ($headerLines as $line) {
            $lineSplit = explode(':', $line, 2);

            if (2 === count($lineSplit)) {
                list($key, $value) = $lineSplit;
                // Decode value
                $value = mb_decode_mimeheader(trim($value));
            } else {
                // Bogus header
                $key = $lineSplit[0];
                $value = '';
            }

            // Case-insensitive key
            $key = strtolower($key);
            if (false === key_exists($key, $this->headers)) {
                $this->headers[$key] = $value;
            } else {
                // Already got an header with this key, convert to array
                if (false === is_array($this->headers[$key])) {
                    $this->headers[$key] = (array) $this->headers[$key];
                }
                $this->headers[$key][] = $value;
            }
        }

        $this->bodyOffset = ftell($stream);

        // Is MultiPart ?
        if ($this->isMultiPart()) {
            // MultiPart !
            $boundary = self::getHeaderOption($this->getHeader('Content-Type'), 'boundary');

            if (null === $boundary) {
                throw new \InvalidArgumentException("Can't find boundary in content type");
            }

            $separator = '--'.$boundary;

            $partOffset = 0;
            $endOfBody = false;
            while ($line = fgets($this->stream, $bufferSize)) {
                $trimmed = rtrim($line, "\r\n");

                // Search the separator
                if ($trimmed === $separator || $trimmed === $separator.'--') {
                    if ($partOffset > 0) {
                        $currentOffset = ftell($this->stream);
                        // Get end of line length (should be 2)
                        $eofLength = strlen($line) - strlen($trimmed);
                        $partLength = $currentOffset - $partOffset - strlen($trimmed) - (2 * $eofLength);

                        // if we are at the end of a part, and there is no trailing new line ($eofLength == 0)
                        // means that we are also at the end of the stream.
                        // we do not know if $eofLength is 1 or two, so we'll use the EOLCharacterLength value
                        // which is 2 by default.
                        if ($eofLength === 0 && feof($this->stream)) {
                            $partLength = $currentOffset - $partOffset - strlen($line) - $this->EOLCharacterLength;
                        }

                        // Copy part in a new stream
                        $partStream = fopen('php://temp', 'rw');
                        stream_copy_to_stream($this->stream, $partStream, $partLength, $partOffset);
                        $this->parts[] = new self($partStream, $this->EOLCharacterLength);
                        // Reset current stream offset
                        fseek($this->stream, $currentOffset);
                    }

                    if ($trimmed === $separator.'--') {
                        // We reach the end separator
                        $endOfBody = true;
                        break;
                    }

                    // Update the part offset
                    $partOffset = ftell($this->stream);
                }
            }


            if (0 === count($this->parts)
                || false === $endOfBody
            ) {
                throw new \LogicException("Can't find multi-part content");
            }
        }
    }


    /**
     * @return bool
     */
    public function isMultiPart()
    {
        return ('multipart' === mb_strstr(
            self::getHeaderValue($this->getHeader('Content-Type')),
            '/',
            true
        ));
    }

    /**
     * @return string
     *
     * @throws \LogicException if is multipart
     */
    public function getBody()
    {
        if ($this->isMultiPart()) {
            throw new \LogicException("MultiPart content, there aren't body");
        }

        $body = stream_get_contents($this->stream, -1, $this->bodyOffset);

        // Decode
        $encoding = strtolower((string) $this->getHeader('Content-Transfer-Encoding'));
        switch ($encoding) {
            case 'base64':
                $body = base64_decode($body);
                break;
            case 'quoted-printable':
                $body = quoted_printable_decode($body);
                break;
        }

        // Convert to UTF-8 ( Not if binary or 7bit ( aka Ascii ) )
        if (false === in_array($encoding, array('binary', '7bit'))) {
            // Charset
            $contentType = $this->getHeader('Content-Type');
            $charset = self::getHeaderOption($contentType, 'charset');
            if (null === $charset) {
                // Try to detect
                $charset = mb_detect_encoding($body) ?: 'utf-8';
            }

            // Only convert if not UTF-8
            if ('utf-8' !== strtolower($charset)) {
                $body = mb_convert_encoding($body, 'utf-8', $charset);
            }
        }

        return $body;
    }

    /**
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param string $key
     *
     * @param mixed  $default
     *
     * @return mixed
     */
    public function getHeader($key, $default = null)
    {
        // Case-insensitive key
        $key = strtolower($key);

        if (false === isset($this->headers[$key])) {
            return $default;
        }

        return $this->headers[$key];
    }

    /**
     * @param string $header
     *
     * @return string
     */
    public static function getHeaderValue($header)
    {
        list($value) = self::parseHeaderContent($header);

        return $value;
    }

    /**
     * @param string $header
     *
     * @return array
     */
    public static function getHeaderOptions($header)
    {
        list(, $options) = self::parseHeaderContent($header);

        return $options;
    }

    /**
     * @param string $header
     * @param string $key
     *
     * @param mixed  $default
     *
     * @return mixed
     */
    public static function getHeaderOption($header, $key, $default = null)
    {
        $options = self::getHeaderOptions($header);

        if (false === isset($options[$key])) {
            return $default;
        }

        return $options[$key];
    }

    /**
     * @return string
     */
    public function getMimeType()
    {
        // Find Content-Disposition
        $contentType = $this->getHeader('Content-Type');

        return self::getHeaderValue($contentType) ?: 'application/octet-stream';
    }

    /**
     * @return string|null
     */
    public function getName()
    {
        // Find Content-Disposition
        $contentDisposition = $this->getHeader('Content-Disposition');

        return self::getHeaderOption($contentDisposition, 'name');
    }

    /**
     * @return string|null
     */
    public function getFileName()
    {
        // Find Content-Disposition
        $contentDisposition = $this->getHeader('Content-Disposition');

        return self::getHeaderOption($contentDisposition, 'filename');
    }

    /**
     * @return bool
     */
    public function isFile()
    {
        return (false === is_null($this->getFileName()));
    }

    /**
     * @return StreamedPart[]
     *
     * @throws \LogicException if is not multipart
     */
    public function getParts()
    {
        if (false === $this->isMultiPart()) {
            throw new \LogicException("Not MultiPart content, there aren't any parts");
        }

        return $this->parts;
    }

    /**
     * @param string $name
     *
     * @return Part[]
     *
     * @throws \LogicException if is not multipart
     */
    public function getPartsByName($name)
    {
        $parts = array();

        foreach ($this->getParts() as $part) {
            if ($part->getName() === $name) {
                $parts[] = $part;
            }
        }

        return $parts;
    }

    /**
     * @param string $content
     *
     * @return array
     */
    private static function parseHeaderContent($content)
    {
        $parts = explode(';', (string) $content);
        $headerValue = array_shift($parts);
        $options = array();
        // Parse options
        foreach ($parts as $part) {
            if (false === empty($part)) {
                $partSplit = explode('=', $part, 2);
                if (2 === count($partSplit)) {
                    list ($key, $value) = $partSplit;
                    if ('*' === substr($key, -1)) {
                        // RFC 5987
                        $key = substr($key, 0, -1);
                        if (preg_match(
                            "/(?P<charset>[\w!#$%&+^_`{}~-]+)'(?P<language>[\w-]*)'(?P<value>.*)$/",
                            $value,
                            $matches
                        )) {
                            $value = mb_convert_encoding(
                                rawurldecode($matches['value']),
                                'utf-8',
                                $matches['charset']
                            );
                        }
                    }
                    $options[trim($key)] = trim($value, ' "');
                } else {
                    // Bogus option
                    $options[$partSplit[0]] = '';
                }
            }
        }

        return array($headerValue, $options);
    }
}