Example #1
2
 function decodeGz64()
 {
     $contentNodes = $this->xpath->query("//content");
     foreach ($contentNodes as $contentNode) {
         if ($contentNode->getAttribute("contentType") == "application/x-gzip" && $contentNode->getAttribute('contentTransferEncoding') == "base64") {
             $contentDOM = new \DOMDocument();
             $contentDOM->loadXML(gzdecode(base64_decode($contentNode->nodeValue)));
             $xmlns = "http://schemas.ogf.org/nml/2013/05/base#";
             $tagName = "Topology";
             foreach ($contentDOM->getElementsByTagNameNS($xmlns, $tagName) as $netNode) {
                 $node = $this->xml->importNode($netNode, true);
                 $contentNode->nodeValue = "";
                 $contentNode->removeAttribute("contentType");
                 $contentNode->removeAttribute('contentTransferEncoding');
                 $contentNode->appendChild($node);
             }
             $xmlns = "http://schemas.ogf.org/nsi/2014/02/discovery/nsa";
             $tagName = "nsa";
             foreach ($contentDOM->getElementsByTagNameNS($xmlns, $tagName) as $nsaNode) {
                 $node = $this->xml->importNode($nsaNode, true);
                 $contentNode->nodeValue = "";
                 $contentNode->removeAttribute("contentType");
                 $contentNode->removeAttribute('contentTransferEncoding');
                 $contentNode->appendChild($node);
             }
         }
     }
 }
Example #2
1
 public static function process()
 {
     $security = new Security();
     $security->verifyPre();
     $data = stream_get_contents(fopen('php://input', 'r'));
     $compressedSize = strlen($data);
     $security->verifyCompressedData($data, $compressedSize);
     $data = @gzdecode($data);
     $uncompressedSize = strlen($data);
     $security->validateData($data, $uncompressedSize);
     $json = json_decode($data, true);
     $security->validateJson($json);
     if (isset($json['icon'])) {
         $img = self::getServerIcon($json['icon']);
         $json['icon'] = $img;
         $data = json_encode($json);
         $uncompressedSize = strlen($data);
     }
     $key = Util::uuid(false);
     $cacheFile = Cache::getFile($key);
     Log::info("Uploaded {$uncompressedSize} bytes as {$key} to {$cacheFile}");
     Cache::put($key, $data);
     header("Location: " . BASE_URL_VIEW . "/?id={$key}");
     self::error("Compressed Size: {$compressedSize}\nUncompressed Size: {$uncompressedSize}\nRaw Upload: " . BASE_URL_VIEW . "/?id={$key}&raw=1");
 }
Example #3
0
 public function load()
 {
     $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->name;
     if (is_file($file)) {
         $this->data = array_merge($this->data, unserialize(gzdecode(file_get_contents($file))));
     }
 }
Example #4
0
 /**
  * Adds the content to the response, which will get JSON decoded and the curl info array.
  * 
  * @param string $content JSON encoded response content
  * @param array $info the curl info array
  *
  * @return void
  */
 public function setContentAndInfo($content, array $info)
 {
     $this->content = json_decode($content);
     $this->info = $info;
     //for some reason curl sometimes fails to decompress gzipped responses, so we must do it manually
     if (empty($this->content) and isset($this->header['Content-Encoding']) and $this->header['Content-Encoding'] == 'gzip') {
         $this->content = json_decode(gzdecode($content));
     }
     //add the response timestamp to the content
     if (isset($this->header['Date'])) {
         $this->content->dateTs = strtotime($this->header['Date']);
     }
     if (isset($this->content->access_token)) {
         //we need to expire (and refresh) the access token before it expires on CCPs side, which appears to happen
         //earlier than it should
         $this->expiry = time() + (int) $this->content->expires_in - 20;
     } elseif (isset($this->content->expires_in)) {
         $this->expiry = time() + (int) $this->content->expires_in;
     } elseif (isset($this->header['Cache-Control'])) {
         foreach (explode(',', $this->header['Cache-Control']) as $frag) {
             if (substr(trim($frag), 0, 8) == 'max-age=') {
                 $this->expiry = time() + (int) substr(trim($frag), 8);
             }
         }
     }
 }
Example #5
0
 public function output($files, $cache_key)
 {
     header('Content-Type: ' . $this->contentType);
     OC_Response::enableCaching();
     $etag = $this->generateETag($files);
     $cache_key .= '-' . $etag;
     $gzout = false;
     $cache = OC_Cache::getGlobalCache();
     if (!OC_Request::isNoCache() && (!defined('DEBUG') || !DEBUG)) {
         OC_Response::setETagHeader($etag);
         $gzout = $cache->get($cache_key . '.gz');
     }
     if (!$gzout) {
         $out = $this->minimizeFiles($files);
         $gzout = gzencode($out);
         $cache->set($cache_key . '.gz', $gzout);
         OC_Response::setETagHeader($etag);
     }
     if ($encoding = OC_Request::acceptGZip()) {
         header('Content-Encoding: ' . $encoding);
         $out = $gzout;
     } else {
         $out = gzdecode($gzout);
     }
     header('Content-Length: ' . strlen($out));
     echo $out;
 }
Example #6
0
 /**
  * Decompress the given value with the specific compression
  *
  * @param String $sValue
  *
  * @return String
  *
  * @throws Exception
  */
 public function decompress($sValue)
 {
     if (!is_string($sValue)) {
         throw new Exception('Invalid first argument, must be a string');
     }
     return gzdecode($sValue);
 }
Example #7
0
 public static function packDecode($str)
 {
     $header = substr($str, 0, 4);
     $len = unpack("Nlen", $header);
     $len = $len["len"];
     if (DoraConst::SW_DATASIGEN_FLAG == true) {
         $signedcode = substr($str, 4, 4);
         $result = substr($str, 8);
         //check signed
         if (pack("N", crc32($result . DoraConst::SW_DATASIGEN_SALT)) != $signedcode) {
             return self::packFormat("Signed check error!", 100005);
         }
         $len = $len - 4;
     } else {
         $result = substr($str, 4);
     }
     if ($len != strlen($result)) {
         //结果长度不对
         echo "error length...\n";
         return self::packFormat("packet length invalid 包长度非法", 100007);
     }
     //if compress the packet
     if (DoraConst::SW_DATACOMPRESS_FLAG == true) {
         $result = gzdecode($result);
     }
     $result = unserialize($result);
     return self::packFormat("OK", 0, $result);
 }
Example #8
0
 protected function decompress($content)
 {
     if ($this->gzipEnabled && \substr($content, 0, 2) === "‹") {
         return \gzdecode($content);
     }
     return $content;
 }
 /**
  * @param array $params
  *
  * @return mixed
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 private function send($params)
 {
     $url = $this->build_url();
     if (!$url) {
         throw new InvalidArgumentException('Empty target URL given!');
     }
     $response = null;
     if ($params) {
         $url = $this->add_parameters_to_url($url, $params);
         if ($this->method === 'GET') {
             $url = $this->add_params_to_query_string($url, $params);
         }
     }
     $context = $this->filter_request_params($params, $this->method);
     $api_response = $this->http_transport->request(esc_url_raw($url), $context);
     $this->handle_request_exceptions($api_response);
     if ($this->must_respond) {
         $api_response = $this->validate_response_content_type($api_response);
         $content_type = $api_response['headers']['content-type'];
         $response = $api_response['body'];
         if (false !== strpos($content_type, 'zip')) {
             $response = gzdecode($api_response['body']);
         }
         if ('json' === $this->response_format) {
             $response = json_decode($response);
         }
     }
     return $response;
 }
Example #10
0
 public static function put($killID, $raw)
 {
     $file = static::getFile($killID, true);
     $sem = sem_get(5632);
     // kmdb is 5632 on a phone
     if (!sem_acquire($sem)) {
         throw new Exception('Unable to obtain kmdb semaphore');
     }
     // Thread safe from here until sem_release
     if (!file_exists($file)) {
         $kills = array();
     } else {
         $contents = file_get_contents($file);
         $deflated = gzdecode($contents);
         $kills = unserialize($deflated);
         $contents = null;
     }
     if (!isset($kills["{$killID}"])) {
         $kills["{$killID}"] = $raw;
         $contents = serialize($kills);
         $compressed = gzencode($contents);
         file_put_contents($file, $compressed, LOCK_EX);
     }
     sem_release($sem);
 }
Example #11
0
function decode_gzip($data)
{
    if (function_exists('gzdecode')) {
        return gzdecode($data);
    }
    return gzinflate(substr($data, 10, -8));
}
 public function PerformDownload()
 {
     print 'Qcodo Package Manager (QPM) Downloader Tool v' . QCODO_VERSION . "\r\n\r\n";
     $strEndPoint = sprintf('%s/DownloadPackage?name=%s&u=%s&gz=', QPackageManager::QpmServiceEndpoint, $this->strPackageName, $this->strUsername);
     if (function_exists('gzdecode')) {
         $strQpmXmlCompressed = QFileInManifest::DownloadFileFromWebWithStatusOutput($strEndPoint . '1');
         $this->strQpmXml = gzdecode($strQpmXmlCompressed);
     } else {
         $this->strQpmXml = trim(QFileInManifest::DownloadFileFromWebWithStatusOutput($strEndPoint . '0'));
     }
     if (!$this->strQpmXml) {
         throw new Exception(sprintf('package not found: %s/%s', $this->strUsername, $this->strPackageName));
     }
     $this->objQpmXml = new SimpleXMLElement($this->strQpmXml);
     $this->CheckVersion();
     if (!$this->blnVersionMatch && !$this->blnForce) {
         print $this->GetVersionMismatchWarningText();
     }
     $strErrorArray = $this->AnalyzePackage();
     if (count($strErrorArray)) {
         print $this->GetErrorText($strErrorArray);
     }
     if (!$this->blnLive) {
         print $this->GetNonLiveText();
     } else {
         if (($this->blnVersionMatch || $this->blnForce) && !count($strErrorArray)) {
             $this->ExecuteDownload();
         }
     }
 }
Example #13
0
 /**
  * @param string $rawResponse
  *
  * @return Torrent[]
  */
 protected function transformResponse($rawResponse)
 {
     $crawler = new Crawler(gzdecode($rawResponse));
     return $crawler->filter('tr[id^="torrent_"]')->each(function ($node) {
         $magnet = $node->filter('.ka-magnet')->parents()->attr('href');
         preg_match('/btih:([0-9A-Za-z]+)&/', $magnet, $matches);
         $hash = $matches[1];
         $size = $node->filter('td.nobr')->text();
         preg_match('/([0-9\\.]+) ([A-Za-z]+)/', $size, $matches);
         $size = $matches[1];
         $unit = $matches[2];
         $converter = new Nomnom($size);
         $torrent = new Torrent();
         $torrent->setName($node->filter('a.cellMainLink')->text());
         $torrent->setHash($hash);
         $torrent->setMagnet($magnet);
         if ($unit == 'KB') {
             $unit = 'kB';
         }
         $torrent->setSize($converter->from($unit)->to('B'));
         $torrent->setSeeds($node->filter('td.green')->text());
         $torrent->setPeers($node->filter('td.red')->text());
         return $torrent;
     });
 }
Example #14
0
 public function testEncode()
 {
     $testString = 'a string to be compressed';
     $result = $this->encoder->encode($testString);
     $uncompressedResult = gzdecode($result);
     $this->assertSame($testString, $uncompressedResult);
 }
Example #15
0
 /**
  * Simulate a user visiting the URL from a browser as closely as we can
  *
  * @param string      $url
  * @param array|null  $cookies
  * @param string|null $referrer
  * @param bool        $skipBody
  *
  * @return array
  */
 static function legitimateRequest($url, $cookies = null, $referrer = null, bool $skipBody = false)
 {
     $r = curl_init();
     $curl_opt = array(CURLOPT_HTTPHEADER => array("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding: gzip, deflate, sdch", "Accept-Language: hu,en-GB;q=0.8,en;q=0.6", "Connection: keep-alive"), CURLOPT_HEADER => true, CURLOPT_URL => $url, CURLOPT_BINARYTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.5678.91 Safari/537.36");
     if (isset($referrer)) {
         $curl_opt[CURLOPT_REFERER] = $referrer;
     }
     if (is_array($cookies)) {
         $curl_opt[CURLOPT_COOKIE] = implode('; ', $cookies);
     }
     if ($skipBody === true) {
         $curl_opt[CURLOPT_NOBODY] = $skipBody;
     }
     curl_setopt_array($r, $curl_opt);
     $response = curl_exec($r);
     $responseCode = curl_getinfo($r, CURLINFO_HTTP_CODE);
     $headerSize = curl_getinfo($r, CURLINFO_HEADER_SIZE);
     $responseHeaders = rtrim(CoreUtils::substring($response, 0, $headerSize));
     $response = CoreUtils::substring($response, $headerSize);
     $curlError = curl_error($r);
     curl_close($r);
     if ($responseCode < 200 || $responseCode >= 300) {
         throw new CURLRequestException(rtrim("cURL fail for URL \"{$url}\" (HTTP {$responseCode}); {$curlError}", ' ;'), $responseCode);
     }
     global $http_response_header;
     $http_response_header = array_map("rtrim", explode("\n", $responseHeaders));
     if (preg_match(new RegExp('Content-Encoding:\\s?gzip'), $responseHeaders)) {
         $response = gzdecode($response);
     }
     return array('responseHeaders' => $responseHeaders, 'response' => $response);
 }
Example #16
0
function mta_decode($headers, $data)
{
    $encode_types = get_content_encoding($headers);
    $types = explode(',', $encode_types);
    $res_data = $data;
    foreach ($types as $type) {
        if ($type == 'rc4') {
            $res_data = mta_rc4($res_data);
        } else {
            if ($type == 'gzip') {
                $header = unpack('Nlength/Lgzip', $res_data);
                if (intval($header['gzip']) === 0x88b1f) {
                    $header = unpack('Nlength/H*body', $res_data);
                    //$header['ori_buf'] = bin2hex($res_data);
                    //$header['ori_len'] = strlen($res_data);
                    $res_data = hex2bin($header['body']);
                } else {
                }
                $res_data = gzdecode($res_data);
                //jsondb_logger('nofity', 'gzip log', ['res'=>$res_data,'len'=>strlen($res_data),'header'=>$header]);
            }
        }
    }
    if (empty($res_data)) {
        jsondb_logger('notify', 'error ' . bin2hex($data));
    }
    return json_decode($res_data);
}
Example #17
0
function getAsset($asset)
{
    $curl = curl_init("http://www.roblox.com/Asset/?id={$asset}");
    curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTPHEADER => array('Accept-Encoding: gzip')));
    $response = curl_exec($curl);
    return gzdecode($response);
}
 public function updateCountryIps($url)
 {
     set_time_limit(600);
     // Fetch all the countries
     $countries = [];
     $countries_db = $this->getModel('\\core\\classes\\models\\Country')->getMulti();
     foreach ($countries_db as $country) {
         $countries[strtoupper($country->code)] = $country;
     }
     $this->database->executeQuery('TRUNCATE country_ip4;');
     // download and decompress
     $contents = file_get_contents($url);
     $contents = gzdecode($contents);
     $lines = explode("\n", $contents);
     foreach ($lines as $line) {
         $row = str_getcsv($line);
         if (!preg_match('/:/', $row[0]) && isset($row[2])) {
             if (isset($countries[$row[2]])) {
                 $ip = $this->getModel('\\modules\\location_detect\\classes\\models\\CountryIP4');
                 $ip->start = $row[0];
                 $ip->end = $row[1];
                 $ip->country_id = $countries[strtoupper($row[2])]->id;
                 $ip->insert();
             }
         }
     }
 }
Example #19
0
 public function get(LogFile $logFile)
 {
     $args = self::getFilesystem($logFile->getArgs());
     $file = $args['filesystem']->read($args['path']);
     if (pathinfo($args['path'])['extension'] === 'gz') {
         $file = gzdecode($file);
     }
     $lines = explode("\n", $file);
     $parser = new LineLogParser();
     if (isset($args['pattern'])) {
         $hasCustomPattern = true;
         $parser->registerPattern('custom', $args['pattern']);
     } else {
         $hasCustomPattern = false;
     }
     foreach ($lines as $line) {
         $entry = $hasCustomPattern ? $parser->parse($line, 0, 'custom') : $parser->parse($line, 0);
         if (count($entry) > 0) {
             if (!$logFile->hasLogger($entry['logger'])) {
                 $logFile->addLogger($entry['logger']);
             }
             $logFile->addLine($entry);
         }
     }
     if ($this->reverse) {
         $logFile->reverseLines();
     }
     return $logFile;
 }
Example #20
0
 public function addQuestions($url)
 {
     $con = mysqli_connect($host, $user, $password, $database) or die('Error in Connecting: ' . mysqli_error($con));
     $binary = file_get_contents($url);
     $data = gzdecode($binary);
     $json = json_decode($data);
     foreach ($json->items as $row) {
         //Verificar se o autor já está na tabela Author antes
         /*$author_id = $row->owner->user_id;
         		$author_link = $row->owner->link;
         		$author_login = $row->owner->display_name;
         		
         		$sql = "INSERT INTO Author (id, link, login)
         			VALUES (".$author_id.", '".$author_link."', '".$author_login."')";
         			
         		$con->query($sql); */
         $link = $row->link;
         $title = $row->title;
         $creation = $row->creation_date;
         $answered = $row->is_answered;
         $sql = "INSERT INTO Question (link, title, creation, answered)\n        \t\tVALUES ('" . $link . "', '" . $title . "', '" . $creation . "', " . $answered . ")";
         //, ".$author_id.
         $con->query($sql);
         $con->close();
     }
 }
Example #21
0
 /**
  * Fetch a new feed.
  */
 private function fetch()
 {
     if (!$this->url) {
         return false;
     }
     $this->posted = array();
     $this->skipped = array();
     $this->duplicate = array();
     $this->lastReturned = 0;
     $this->time = '';
     $this->cachedTime = '';
     global $idfeedversion;
     $http = new http_request($this->getFullURL());
     $http->set_useragent("EDK IDFeedfetcher " . $idfeedversion);
     $http->set_timeout(300);
     //accept gzip encoding
     $http->set_header('Accept-Encoding: gzip');
     if (strpos($http->get_header(), 'Content-Encoding: gzip') !== false) {
         $this->xml = gzdecode($http->get_content());
     } else {
         $this->xml = $http->get_content();
     }
     if ($http->get_http_code() != 200) {
         trigger_error("HTTP error " . $http->get_http_code() . " while fetching feed from " . $this->url . $options . ".", E_USER_WARNING);
         return false;
     }
     if ($this->xml) {
         return true;
     } else {
         return false;
     }
 }
Example #22
0
File: Gzip.php Project: buse974/dms
 /**
  * (non-PHPdoc).
  *
  * @param string $data
  *
  * @see \Dms\Coding\CodingInterface::decode()
  */
 public function decode($data = null)
 {
     if ($data != null) {
         $this->setData($data);
     }
     return gzdecode($this->data);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $workerName = $input->getArgument('worker');
     $rawPayload = $input->getArgument('payload') === null ? '[]' : $input->getArgument('payload');
     $payload = $input->getOption('decode') ? json_decode(gzdecode(base64_decode($rawPayload))) : json_decode($rawPayload);
     $workerService = $this->getContainer()->get($workerName);
     call_user_func_array(array($workerService, 'execute'), $payload);
 }
Example #24
0
 /**
  * Get an item.
  *
  * @param  string $key
  * @return mixed Data on success, null on failure
  */
 public function getItem($key)
 {
     $data = $this->storageInterface->getItem($key);
     if ($data) {
         $data = gzdecode($data);
     }
     return $data;
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function uncompress($data)
 {
     $data = gzdecode($data);
     if (false === $data) {
         throw new \RuntimeException('Unable to uncompress data');
     }
     return $data;
 }
Example #26
0
 /**
  * @inheritDoc
  */
 public function decode($data)
 {
     $data = gzdecode($data);
     if (!$data) {
         throw new DecodeFailedException("gzinflate returned no data.");
     }
     return $data;
 }
 public function prepareData($incomingRawMessage)
 {
     $rawMessages = [];
     $rawMessage = new RawMessage();
     $rawMessage->setStompHeaders($incomingRawMessage->headers)->setNationalRailBody(gzdecode($incomingRawMessage->body));
     $rawMessages[] = $rawMessage;
     return $rawMessages;
 }
 /**
  * Get the uncompressed version of the given data.
  *
  * @param string $compressed The compressed data.
  *
  * @return string The uncompressed data.
  */
 protected function getUncompressed($compressed)
 {
     $decompressed = @gzdecode($compressed);
     if ($decompressed === false) {
         throw new Exception('Could not decompress data with native gzdecode()');
     }
     return $decompressed;
 }
Example #29
0
 protected static function _readMeta()
 {
     //$raw = file_get_contents(static::_getTableDataFileName());
     /** @var Model\Settings $settings */
     $settings = DI::getDefault()['Settings'];
     $raw = gzdecode($settings::get('_database_struct'));
     list($a1, $a2) = @unserialize($raw);
     return [$a1 ?: [], $a2 ?: []];
 }
Example #30
-1
 /**
  * @covers ::afterBackup
  */
 public function testCompress()
 {
     $file = new ReadableStreamBackupFile($this->filedir . '/item1.txt');
     // Gzip
     $compressed = $this->filter->afterBackup($file);
     $this->assertEquals('item1.txt.gz', $compressed->getFullName());
     $this->assertNotEquals($this->original, $compressed->readAll());
     $this->assertEquals($this->original, gzdecode($compressed->readAll()));
     $this->assertEquals($this->original, $file->readAll());
     // No compression
     $this->filter->setConfig(new Config(['compression' => 'none']));
     $compressed = $this->filter->afterBackup($file);
     $this->assertEquals('item1.txt', $compressed->getFullName());
     $this->assertEquals($this->original, $compressed->readAll());
     $this->assertEquals($this->original, $file->readAll());
     // Bzip
     $this->filter->setConfig(new Config(['compression' => 'bzip']));
     $compressed = $this->filter->afterBackup($file);
     $this->assertEquals('item1.txt.bz2', $compressed->getFullName());
     $handle = bzopen($compressed->realpath(), 'r');
     $this->assertEquals($this->original, bzread($handle));
     $this->assertNotEquals($this->original, $compressed->readAll());
     $this->assertEquals($this->original, $file->readAll());
     // Zip
     //    $this->filter->setConfig(new Config(['compression' => 'zip']));
     //    $compressed = $this->filter->afterBackup($file);
     //    $this->assertEquals('item1.txt.zip', $compressed->getFullName());
     //    $this->assertNotEquals($this->original, $compressed->readAll());
     //    $this->assertEquals($this->original, $file->readAll());
     //
     //    $handle = zip_open($compressed->realpath());
     //    $file_handle = zip_read (zip_open($compressed->realpath()));
     //    $this->assertEquals($this->original, bzread($handle));
 }