現在の接続においてGZIPエンコーディングが有効かどうか調べます。

@return	bool	GZIPエンコーディングが有効な場合はTRUE、そうでない場合はFALSE
194500
public static function EnableGZipEncoding () {
		return static::LasyClassVarConstAccessCallback('accept_encoding_gzip', function () {
			$accept_encodings = \ickx\fw2\core\net\http\Request::GetHeader('Accept-Encoding');
			if ($accept_encodings === false) {
				return false;
			}
			foreach (explode(',', $accept_encodings) as $accept_encoding) {
				if (trim($accept_encoding) === 'gzip') {
					return true;
				}
			}
			return false;
		});
	}
806498
public function getCache()
    {
        // make sure filters are parsed again if cache expired
        if (!$this->isValidFile($this->path)) {
            return false;
        }

        $data = unserialize(file_get_contents($this->path));

        return $data;
    }
690222
private function getCacheFiles()
    {
        if (!($files = @scandir($this->directory, 1))) {
            return false;
        }

        $negExtLen = -1 * strlen($this->extension);
        $return = array();
        foreach ($files as $file) {
            if (substr($file, $negExtLen) === $this->extension) {
                $return[] = $this->directory . '/' . $file;
            }
        }
        return $return;
    }
96512
private function validateRegex(): bool
    {
        $isValid = \preg_match($this->options['pattern'], $this->value) ? true : false;
        if (!$isValid) {
            $this->setError(self::VALIDATOR_ERROR_REGEX_PATTERN_NOT_MATCH);
        }
        return $isValid;
    }
361702
def gzip_encode(data):
    
    if not gzip:
        raise NotImplementedError
    f = StringIO.StringIO()
    gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
    gzf.write(data)
    gzf.close()
    encoded = f.getvalue()
    f.close()
    return encoded
808681
public static function headers()
    {
        if (!self::isDebug()) {
            return false;
        }

        if (function_exists('apache_request_headers')) {
            $data = array(
                'Request'  => apache_request_headers(),
                'Response' => apache_response_headers(),
                'List'     => headers_list()
            );

        } else {
            $data = array(
                'List' => headers_list()
            );
        }

        if (headers_sent($filename, $linenum)) {
            $data['Sent'] = 'Headers already sent in ' . self::i()->_getRalativePath($filename) . ':' . $linenum;
        } else {
            $data['Sent'] = false;
        }

        return self::i()->dump($data, '! headers !');
    }
1369402
function fp()
    {
        if ( !isset( $GLOBALS['eZMutex_FP_' . $this->FileName] ) ||
             $GLOBALS['eZMutex_FP_' . $this->FileName] === false )
        {
            $GLOBALS['eZMutex_FP_' . $this->FileName] = fopen( $this->FileName, 'w' );
            if ( $GLOBALS['eZMutex_FP_' . $this->FileName] === false )
            {
                eZDebug::writeError( 'Failed to open file: ' . $this->FileName );
            }
        }
        return $GLOBALS['eZMutex_FP_' . $this->FileName];
    }
1270046
public function parse()
    {
        // Validate user based regex
        try {
            preg_match(
                config("{$this->configBase}.parser.file_regex"),
                '',
                $matches
            );

        } catch (\Exception $e) {
            $this->warningCount++;

            return $this->failed('Configuration error in the regular expression');
        }

        foreach ($this->parsedMail->getAttachments() as $attachment) {
            if (strpos($attachment->filename, '.zip') !== false
                && ($attachment->contentType == 'application/octet-stream'
                        || $attachment->contentType == 'application/zip'
                )
            ) {
                $zip = new Zipper;

                if (!$this->createWorkingDir()) {
                    return $this->failed(
                        "Unable to create working directory"
                    );
                }

                file_put_contents($this->tempPath . $attachment->filename, $attachment->getContent());

                $zip->zip($this->tempPath . $attachment->filename);
                $zip->extractTo($this->tempPath);

                foreach ($zip->listFiles() as $index => $compressedFile) {
                    if (strpos($compressedFile, '.csv') !== false) {
                        // For each CSV file we find, we are going to do magic (however they usually only send 1 zip)
                        if (preg_match(
                            config("{$this->configBase}.parser.file_regex"),
                            $compressedFile,
                            $matches
                        )) {
                            $this->feedName = $matches[1];

                            // If feed is known and enabled, validate data and save report
                            if ($this->isKnownFeed() && $this->isEnabledFeed()) {
                                $csvReports = new Reader\CsvReader(
                                    new SplFileObject($this->tempPath . $compressedFile)
                                );
                                $csvReports->setHeaderRowNumber(0);

                                foreach ($csvReports as $report) {

                                    // Handle field mappings first
                                    $aliasses = config("{$this->configBase}.feeds.{$this->feedName}.aliasses");
                                    if (is_array($aliasses)) {
                                        foreach ($aliasses as
                                                 $alias => $real) {
                                            if (array_key_exists($alias, $report)) {
                                                $report[$real] = $report[$alias];
                                                unset($report[$alias]);
                                            }
                                        }
                                    }
                                    /*
                                     * Emergency fix for major false positives from shadowserver feed
                                     * This only happens under very specific conditions and will be filtered out
                                     * as specific as possible.
                                     */
                                    if ($this->feedName == 'spam_url') {
                                        $urlFilter = '/([a-zA-Z]{3,5}.[a-zA-Z]{3,5}.com)/';
                                        if( $report['src_geo'] == 'RU' &&
                                            $report['url'] == "http://{$report['host']}" &&
                                            $report['src_asn'] == "8402" &&
                                            preg_match($urlFilter, $report['host'], $filterMatches)
                                        ) {
                                            continue;
                                        }
                                    }

                                    /*
                                     * Legacy 3.x fix for migrations.
                                     *
                                     * This resolves shadowserver errors where the CSV was send in duplicate resulting
                                     * in the header fields being used as data. If the header is detected the row can
                                     * be skipped safely
                                     */
                                    if ($report['ip'] === 'ip') {
                                        continue;
                                    }

                                    // Sanity check
                                    if ($this->hasRequiredFields($report) === true) {
                                        // incident has all requirements met, filter and add!
                                        $report = $this->applyFilters($report);

                                        $incident = new Incident();
                                        $incident->source      = config("{$this->configBase}.parser.name");
                                        $incident->source_id   = false;
                                        $incident->ip          = $report['ip'];
                                        $incident->domain      = false;
                                        $incident->class       =
                                            config("{$this->configBase}.feeds.{$this->feedName}.class");
                                        $incident->type        =
                                            config("{$this->configBase}.feeds.{$this->feedName}.type");
                                        $incident->timestamp   = strtotime($report['timestamp']);
                                        $incident->information = json_encode($report);

                                        // some rows have a domain, which is an optional column we want to register
                                        switch ($this->feedName) {
                                            case "spam_url":
                                                if (isset($report['url'])) {
                                                    $incident->domain = getDomain($report['url']);
                                                }
                                                break;
                                            case "ssl_scan":
                                                if (isset($report['subject_common_name'])) {

                                                    /*
                                                     * Common name does not add http://, but that is required for
                                                     * the domain helper check so lets add it manually
                                                     */
                                                    $testurl = "http://{$report['subject_common_name']}";

                                                    $incident->domain = getDomain($testurl);
                                                }
                                                break;
                                            case "compromised_website":
                                                if (isset($report['http_host'])) {
                                                    $incident->domain = getDomain($report['http_host']);
                                                }
                                                break;
                                        }

                                        $this->incidents[] = $incident;

                                    } //End hasRequired fields
                                } // End foreach report loop
                            } // End isKnown & isEnabled
                        } else { // Pregmatch failed to get feedName from attachment
                            $this->warningCount++;
                        }
                    } else { // Attached file is not a CSV within a ZIP file
                        $this->warningCount++;
                    }
                } // End each file in ZIP attachment loop
            } // End if not a ZIP attachment
        } // End foreach attachment loop

        return $this->success();
    }
7049
protected static function clientEncoding()
	{
		if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']))
		{
			return false;
		}

		$encoding = false;

		if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
		{
			$encoding = 'gzip';
		}

		if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip'))
		{
			$encoding = 'x-gzip';
		}

		return $encoding;
	}
382338
public function encoding()
    {
        if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || headers_sent()) {
            return false;
        }

        $accept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING'];

        if (strpos($accept_encoding, 'x-gzip') !== false) {
            return 'x-gzip';
        }

        if (strpos($accept_encoding, 'gzip') !== false) {
            return 'gzip';
        }

        return false;
    }
655588
private function _gzdecode($message)
    {
        $messageLength  = strlen($message);
        $isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);

        /* make sure this is actually gzipped */
        if ($messageLength < 18 || strcmp(substr($message, 0, 2), "\x1f\x8b")) {

            if ($isDebugEnabled) {

                $this->_logger->debug('Not in GZIP format.');
            }

            return false;
        }

        /* grab the compression method and flags */
        $compressionMethod = ord(substr($message, 2, 1));
        $compressionFlags  = ord(substr($message, 3, 1));

        if ($compressionFlags & 31 != $compressionFlags) {

            if ($isDebugEnabled) {

                $this->_logger->debug('Reserved bits not allowed.');
            }

            return false;
        }

        /* NOTE: $mtime may be negative (PHP integer limitations) */
        $mtime        = unpack('V', substr($message, 4, 4));
        $mtime        = $mtime[1];
        $xfl          = substr($message, 8, 1);
        $os           = substr($message, 8, 1);
        $headerLength = 10;
        $extraLength  = 0;
        $extra        = '';

        if ($compressionFlags & 4) {

            /* 2-byte length prefixed EXTRA data in header */
            if ($messageLength - $headerLength - 2 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('2-byte length prefixed EXTRA data in header');
                }

                return false;
            }

            $extraLength = unpack('v', substr($message, 8, 2));
            $extraLength = $extraLength[1];

            if ($messageLength - $headerLength - 2 - $extraLength < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('Invalid extra length');
                }

                return false;
            }

            $extra         = substr($message, 10, $extraLength);
            $headerLength += 2 + $extraLength;
        }

        $filenameLength = 0;
        $filename       = '';

        /* If FNAME is set, an original file name is present, terminated by a zero byte. */
        if ($compressionFlags & 8) {

            if ($messageLength - $headerLength - 1 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('C-Style string');
                }

                return false;
            }

            $filenameLength = strpos(substr($message, $headerLength), chr(0));

            if ($filenameLength === false || $messageLength - $headerLength - $filenameLength - 1 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('Invalid filename length');
                }

                return false;
            }

            $filename      = substr($message, $headerLength, $filenameLength);
            $headerLength += $filenameLength + 1;
        }

        $commentlen = 0;
        $comment    = '';

        /* If FCOMMENT is set, a zero-terminated file comment is present */
        if ($compressionFlags & 16) {

            if ($messageLength - $headerLength - 1 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('C-Style string COMMENT data in header');
                }

                return false;
            }

            $commentlen = strpos(substr($message, $headerLength), chr(0));

            if ($commentlen === false || $messageLength - $headerLength - $commentlen - 1 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('Invalid comment length');
                }

                return false;
            }

            $comment       = substr($message, $headerLength, $commentlen);
            $headerLength += $commentlen + 1;
        }

        $headercrc = '';

        /* If FHCRC is set, a CRC16 for the gzip header is present, immediately before the compressed data */
        if ($compressionFlags & 2) {

            if ($messageLength - $headerLength - 2 < 8) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('2-bytes (lowest order) of CRC32 on header present');
                }

                return false;
            }

            $calccrc   = crc32(substr($message, 0, $headerLength)) & 0xffff;
            $headercrc = unpack('v', substr($message, $headerLength, 2));
            $headercrc = $headercrc[1];

            if ($headercrc != $calccrc) {

                if ($isDebugEnabled) {

                    $this->_logger->debug('Header checksum failed.');
                }

            }

            $headerLength += 2;
        }

        $datacrc = unpack('V', substr($message, -8, 4));
        $datacrc = sprintf('%u', $datacrc[1] & 0xFFFFFFFF);
        $isize   = unpack('V', substr($message, -4));
        $isize   = $isize[1];

        $bodyLength = $messageLength - $headerLength - 8;

        if ($bodyLength < 1) {

            if ($isDebugEnabled) {

                $this->_logger->debug('Negative body length');
            }

            return false;
        }

        $compressedBody = substr($message, $headerLength, $bodyLength);
        $decompressed   = '';

        if ($bodyLength > 0) {

            switch ($compressionMethod) {

                case 8:
                    // Currently the only supported compression method:
                    $decompressed = gzinflate($compressedBody, null);
                    break;

                default:

                    if ($isDebugEnabled) {

                        $this->_logger->debug('Unknown compression method.');
                    }

                    return false;
            }
        }

        $crc   = sprintf("%u", crc32($decompressed));
        $crcOK = $crc == $datacrc;
        $lenOK = $isize == strlen($decompressed);

        if (!$lenOK || !$crcOK) {

            return false;
        }

        return $decompressed;
    }
216371
public function gc()
	{
		$prefix = $this->options['hash'] . '-cache-';

		foreach ($this->data as $key => $value)
		{
			if (substr($key, 0, strlen($prefix)) == $prefix)
			{
				$value = $this->data[$key];

				if ($this->isDataExpired($value))
				{
					unset($this->data[$key]);
				}
			}
		}

		return true;
	}
218643
protected function decodeRegexString(): bool
    {
        $regex_string = '#([0-9]+)[\s]*('.implode('|', array_keys($this->tokensValues)).'){1}#i';
        $regex_clock_string = '#^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$#i';

        if (preg_match_all($regex_string, $this->expression, $matches)) {
            foreach ($matches[1] as $index => $value) {
                $this->time += $this->tokensValues[$matches[2][$index]] * $value;
            }
            $this->di = DateInterval::createFromDateString($this->integerToString($this->time));
            return true;
        } elseif (preg_match_all($regex_clock_string, $this->expression, $matches) && count($matches) == 4) {
            if (!empty($matches[1][0])) {
                $this->time += (int)$matches[1][0] * 3600;
            }
            if (!empty($matches[2][0])) {
                $this->time += (int)$matches[2][0] * 60;
            }
            if (!empty($matches[3][0])) {
                $this->time += (int)$matches[3][0];
            }
            $this->di = DateInterval::createFromDateString($this->integerToString($this->time));
            return true;
        }

        return false;
    }
172484
private function _isCompressed()
    {
        if (is_dir($this->bag)) {
            return false;
        } else {
            $bag = strtolower($this->bag);
            if (endsWith($bag, '.zip')) {
                $this->bagCompression = 'zip';
                return true;
            } else if (endsWith($bag, '.tar.gz') || endsWith($bag, '.tgz')) {
                $this->bagCompression = 'tgz';
                return true;
            }
        }
        return false;
    }
836739
public function disableGzip()
  {
    if (
        isset($this->requestHeaders['accept-encoding']) &&
        $this->requestHeaders['accept-encoding'] == "gzip"
    ) {
      unset($this->requestHeaders['accept-encoding']);
    }
    $this->canGzip = false;
    $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
  }
756770
public function send() {
    if (!isset($this->files[$this->sent])) {
      return FALSE;
    }

    $file = $this->files[$this->sent];

    // Local header
    $local = $file->genLocal(self::ZIP_VERSION, $this->dosStamp);
    $this->output($local);

    // Body
    $file->hasDeflation() ? $this->outputDeflated($file) : $this->outputRaw($file);

    // Data descriptor
    $dataDescriptor = $file->isSmooth() ? $file->genDataDescriptor() : '';
    $this->output($dataDescriptor);

    $file->setLocalOffset($this->localOffset);
    $this->localOffset += strlen($local) + $file->getDeflatedSize() + strlen($dataDescriptor);

    // Central header (not output, see flush)
    $file->genCentral(self::ZIP_VERSION, $this->dosStamp);
    $this->centralLength += strlen($file->getCentral());

    $this->sent++;
    return TRUE;
  }
1280289
private boolean isMessageCompressed() {
        String contentEncoding = m_request.getHeader(HttpDefs.CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (!contentEncoding.equalsIgnoreCase("gzip")) {
                throw new IllegalArgumentException("Unsupported Content-Encoding: " + contentEncoding);
            }
            return true;
        }
        return false;
    }