示例#1
0
文件: Context.php 项目: jgswift/qio
 /**
  * Initializes observr collections by aliasing
  * stream_context_set_option and stream_context_set_params
  */
 private function initialize()
 {
     $this->options->merge(\stream_context_get_options($this->context));
     $this->options->attach('set', function ($sender, $e) {
         \stream_context_set_option($this->context, $this->wrapper, $e->offset, $e->value);
     });
     $this->data->merge(\stream_context_get_params($this->context));
     $this->data->attach('set', function ($sender, $e) {
         \stream_context_set_params($this->context, $this->data->toArray());
     });
 }
示例#2
0
 /**
  * Loads a remote document or context
  *
  * @param string $url The URL of the document to load.
  *
  * @return RemoteDocument The remote document.
  *
  * @throws JsonLdException If loading the document failed.
  */
 public static function loadDocument($url)
 {
     // if input looks like a file, try to retrieve it
     $input = trim($url);
     if (false == (isset($input[0]) && "{" === $input[0] || "[" === $input[0])) {
         $remoteDocument = new RemoteDocument($url);
         $streamContextOptions = array('method' => 'GET', 'header' => "Accept: application/ld+json, application/json; q=0.9, */*; q=0.1\r\n", 'timeout' => Processor::REMOTE_TIMEOUT);
         $context = stream_context_create(array('http' => $streamContextOptions, 'https' => $streamContextOptions));
         $httpHeadersOffset = 0;
         stream_context_set_params($context, array('notification' => function ($code, $severity, $msg, $msgCode, $bytesTx, $bytesMax) use(&$remoteDocument, &$http_response_header, &$httpHeadersOffset) {
             if ($code === STREAM_NOTIFY_MIME_TYPE_IS) {
                 $remoteDocument->mediaType = $msg;
             } elseif ($code === STREAM_NOTIFY_REDIRECTED) {
                 $remoteDocument->documentUrl = $msg;
                 $remoteDocument->mediaType = null;
                 $httpHeadersOffset = count($http_response_header);
             }
         }));
         if (false === ($input = @file_get_contents($url, false, $context))) {
             throw new JsonLdException(JsonLdException::LOADING_DOCUMENT_FAILED, sprintf('Unable to load the remote document "%s".', $url), $http_response_header);
         }
         // Extract HTTP Link headers
         $linkHeaderValues = array();
         for ($i = count($http_response_header) - 1; $i > $httpHeadersOffset; $i--) {
             if (0 === substr_compare($http_response_header[$i], 'Link:', 0, 5, true)) {
                 $value = substr($http_response_header[$i], 5);
                 $linkHeaderValues[] = $value;
             }
         }
         $linkHeaderValues = self::parseContextLinkHeaders($linkHeaderValues, new IRI($url));
         if (count($linkHeaderValues) === 1) {
             $remoteDocument->contextUrl = reset($linkHeaderValues);
         } elseif (count($linkHeaderValues) > 1) {
             throw new JsonLdException(JsonLdException::MULTIPLE_CONTEXT_LINK_HEADERS, 'Found multiple contexts in HTTP Link headers', $http_response_header);
         }
         // If we got a media type, we verify it
         if ($remoteDocument->mediaType) {
             // Drop any media type parameters such as profiles
             if (false !== ($pos = strpos($remoteDocument->mediaType, ';'))) {
                 $remoteDocument->mediaType = substr($remoteDocument->mediaType, 0, $pos);
             }
             $remoteDocument->mediaType = trim($remoteDocument->mediaType);
             if ('application/ld+json' === $remoteDocument->mediaType) {
                 $remoteDocument->contextUrl = null;
             } elseif ('application/json' !== $remoteDocument->mediaType && 0 !== substr_compare($remoteDocument->mediaType, '+json', -5)) {
                 throw new JsonLdException(JsonLdException::LOADING_DOCUMENT_FAILED, 'Invalid media type', $remoteDocument->mediaType);
             }
         }
         $remoteDocument->document = Processor::parse($input);
         return $remoteDocument;
     }
     return new RemoteDocument($url, Processor::parse($input));
 }
示例#3
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $current = $this->getApplication()->getVersion();
     if (false === ($latest = @file_get_contents('http://kzykhys.com/coupe/version'))) {
         $output->writeln('<error>Failed to connect to http://kzykhys.com/coupe/version</error>');
         return 255;
     }
     if (!$input->getOption('force')) {
         if ($current === $latest) {
             $output->writeln('<info>You are using the latest version [' . $current . ']</info>');
             return 0;
         }
     }
     /* @var \Symfony\Component\Console\Helper\ProgressHelper $progress */
     $progress = $this->getHelper('progress');
     $fileSize = 0;
     $currentPercent = 0;
     $progress->start($output, 100);
     $context = stream_context_create();
     stream_context_set_params($context, ["notification" => function ($c, $s, $m, $mc, $transferred, $max) use(&$progress, &$fileSize, &$currentPercent) {
         switch ($c) {
             case STREAM_NOTIFY_FILE_SIZE_IS:
                 $fileSize = $max;
                 break;
             case STREAM_NOTIFY_PROGRESS:
                 if ($transferred > 0) {
                     $percent = (int) ($transferred / $fileSize * 100);
                     $progress->advance($percent - $currentPercent);
                     $currentPercent = $percent;
                 }
                 break;
         }
     }]);
     $output->writeln('Downloading <fg=green;options=bold>' . $latest . '</fg=green;options=bold> ...');
     if (false === ($phar = @file_get_contents('http://kzykhys.com/coupe/coupe.phar', false, $context))) {
         $output->writeln('<error>Failed to download new coupe version</error>');
         return 255;
     }
     $progress->setCurrent(100);
     $progress->finish();
     $pharPath = $GLOBALS['argv'][0];
     $fs = new Filesystem();
     $fs->copy($pharPath, $backup = tempnam(sys_get_temp_dir(), 'coupe_phar_backup'));
     if (false == @file_put_contents($pharPath, $phar)) {
         $fs->remove($pharPath);
         $fs->rename($backup, $pharPath);
         $output->writeln('<error>Failed to update coupe to the latest version</error>');
         return 1;
     }
     $fs->remove($backup);
     return 0;
 }
function _hush_download($down_file, $save_file)
{
    $ctx = stream_context_create();
    stream_context_set_params($ctx, array("notification" => "_hush_download_callback"));
    $fp = fopen($down_file, "r", false, $ctx);
    if (is_resource($fp) && file_put_contents($save_file, $fp)) {
        echo "\nDone!\n";
        return true;
    }
    $err = error_get_last();
    echo "\nError.. ", $err["message"], "\n";
    return false;
}
 public function createSocket($recreate = false)
 {
     $flags = STREAM_CLIENT_ASYNC_CONNECT;
     if (!$this->_socket || $recreate === true) {
         if ($this->_socket = @stream_socket_client($this->protocol . "://" . $this->host . ':' . $this->port, $errno, $errstr, $this->timeout, $flags)) {
             stream_set_blocking($this->_socket, false);
             stream_context_set_params($this->_socket, array("notification" => array($this, 'stream_notification_callback')));
             $this->_state_socket = true;
             $this->_socket_error = array();
         } else {
             $this->_socket_error = array('error_num' => $errno, 'error_message' => $errstr);
         }
     }
 }
示例#6
0
 /**
  * @param string $version
  * @return string
  */
 public function updates($version = self::LATEST)
 {
     $tag = $version;
     if (self::LATEST == $version) {
         $tag = 'master';
     }
     if (ini_get('phar.readonly') == true) {
         throw new \RuntimeException('Unable to update the PHAR, phar.readonly is set, use \'-d phar.readonly=0\'');
     }
     if (ini_get('allow_url_fopen') == false) {
         throw new \RuntimeException('Unable to update the PHAR, allow_url_fopen is not set, use \'-d allow_url_fopen=1\'');
     }
     $currentPharLocation = \Phar::running(false);
     if (!file_exists($currentPharLocation) || strlen($currentPharLocation) == 0) {
         throw new \LogicException("You're not currently using Phar. If you have installed PhpMetrics with Composer, please updates it using Composer.");
     }
     if (!is_writable($currentPharLocation)) {
         throw new \RuntimeException(sprintf('%s is not writable', $currentPharLocation));
     }
     // downloading
     $url = sprintf($this->url, $tag);
     $ctx = stream_context_create();
     stream_context_set_params($ctx, array("notification" => array($this, 'stream_notification_callback')));
     $content = file_get_contents($url, false, $ctx);
     // replacing file
     if (!$content) {
         throw new \RuntimeException('Download failed');
     }
     // check if all is OK
     $tmpfile = tempnam(sys_get_temp_dir(), 'phar');
     file_put_contents($tmpfile, $content);
     $output = shell_exec(sprintf('"%s" "%s" --version', PHP_BINARY, $tmpfile));
     if (!preg_match('!(v\\d+\\.\\d+\\.\\d+)!', $output, $matches)) {
         throw new \RuntimeException('Phar is corrupted. Please retry');
     }
     // compare versions
     $downloadedVersion = $matches[1];
     if (self::LATEST !== $version && $downloadedVersion !== $version) {
         throw new \RuntimeException('Incorrect version. Please retry');
     }
     // at this step, all is ok
     file_put_contents($currentPharLocation, $content);
     return $version;
 }
 public static function run($r)
 {
     foreach (pts_types::identifiers_to_test_profile_objects($r, true, true) as $test_profile) {
         echo 'Checking: ' . $test_profile . PHP_EOL;
         foreach (pts_test_install_request::read_download_object_list($test_profile) as $test_file_download) {
             foreach ($test_file_download->get_download_url_array() as $url) {
                 $stream_context = pts_network::stream_context_create();
                 stream_context_set_params($stream_context, array('notification' => 'pts_stream_status_callback'));
                 $file_pointer = @fopen($url, 'r', false, $stream_context);
                 //fread($file_pointer, 1024);
                 if ($file_pointer == false) {
                     echo PHP_EOL . 'BAD URL: ' . $test_file_download->get_filename() . ' / ' . $url . PHP_EOL;
                 } else {
                     @fclose($file_pointer);
                 }
             }
         }
     }
 }
示例#8
0
 /**
  * Send the request
  *
  * This function sends the actual request to the
  * remote/local webserver using php streams.
  */
 public function sendRequest()
 {
     $proxyurl = '';
     $request_fulluri = false;
     if (!is_null($this->proxy)) {
         $proxyurl = $this->proxy->url;
         $request_fulluri = true;
     }
     $info = array($this->uri->protocol => array('method' => $this->verb, 'content' => $this->body, 'header' => $this->buildHeaderString(), 'proxy' => $proxyurl, 'ignore_errors' => true, 'max_redirects' => 3, 'request_fulluri' => $request_fulluri));
     // create context with proper junk
     $ctx = stream_context_create($info);
     if (count($this->_listeners)) {
         stream_context_set_params($ctx, array('notification' => array($this, 'streamNotifyCallback')));
     }
     $fp = fopen($this->uri->url, 'rb', false, $ctx);
     if (!is_resource($fp)) {
         throw new Request\Exception('Url ' . $this->uri->url . ' could not be opened (PhpStream Adapter)');
     } else {
         restore_error_handler();
     }
     stream_set_timeout($fp, $this->requestTimeout);
     $body = stream_get_contents($fp);
     if ($body === false) {
         throw new Request\Exception('Url ' . $this->uri->url . ' did not return a response');
     }
     $meta = stream_get_meta_data($fp);
     fclose($fp);
     $headers = $meta['wrapper_data'];
     $details = $this->uri->toArray();
     $tmp = $this->parseResponseCode($headers[0]);
     $details['code'] = $tmp['code'];
     $details['httpVersion'] = $tmp['httpVersion'];
     $cookies = array();
     $this->headers = $this->cookies = array();
     foreach ($headers as $line) {
         $this->processHeader($line);
     }
     return new Request\Response($details, $body, new Request\Headers($this->headers), $this->cookies);
 }
 /**
  * @param \FlickrDownloadr\Photo\Photo $photo
  * @param string $filename
  * @param string $dirname
  * @return int Number of bytes that were written to the file, or FALSE on failure
  */
 public function download(Photo $photo, $filename, $dirname)
 {
     $url = $photo->getUrl();
     if ($this->dryRun) {
         return 0;
     }
     \Nette\Utils\FileSystem::createDir($dirname . '/' . dirname($filename));
     $this->setupProgressBar();
     $ctx = stream_context_create();
     stream_context_set_params($ctx, array("notification" => $this->getNotificationCallback($filename)));
     $bytes = file_put_contents($dirname . '/' . $filename, fopen($url, 'r', FALSE, $ctx));
     if ($bytes === FALSE) {
         $this->progress->setMessage('<error>Error!</error>', 'final_report');
     } else {
         list($time, $size, $speed) = $this->getFinalStats($this->progress->getMaxSteps(), $this->progress->getStartTime());
         $this->progress->setMessage('<comment>[' . $size . ' in ' . $time . ' (' . $speed . ')]</comment>', 'final_report');
         $this->progress->setFormat('%message% %final_report%' . "\n");
     }
     $this->progress->finish();
     $this->output->writeln('');
     return $bytes;
 }
示例#10
0
/**
 * Download a file ($url) to a given path ($savepath) and display progress information while doing it
 * Optionally check saved file against a known md5 hash
*/
function download_file($url, $savepath, $md5hash = false)
{
    // Stream the file, and output status information as defined in stream_notification_callback() via STREAM_NOTIFY_PROGRESS
    // Requires PHP 5.2.0+
    $ctx = stream_context_create();
    stream_context_set_params($ctx, array('notification' => 'stream_notification_callback'));
    $fp = fopen($url, 'r', false, $ctx);
    if (!$fp) {
        echo "ERROR: Unable to open this url for download: {$url}", PHP_EOL;
        return false;
    }
    if (is_resource($fp) && file_put_contents($savepath, $fp)) {
        fclose($fp);
        if ($md5hash) {
            if (md5_file($savepath) === $md5hash) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }
    return false;
}
示例#11
0
 /**
  * Sends a PSR-7 request.
  *
  * @param RequestInterface $request
  *
  * @return ResponseInterface
  *
  * @throws \Http\Client\Exception If an error happens during processing the request.
  * @throws \Exception             If processing the request is impossible (eg. bad configuration).
  */
 public function sendRequest(RequestInterface $request)
 {
     $body = (string) $request->getBody();
     $headers = [];
     foreach (array_keys($request->getHeaders()) as $headerName) {
         if (strtolower($headerName) === 'content-length') {
             $values = array(strlen($body));
         } else {
             $values = $request->getHeader($headerName);
         }
         foreach ($values as $value) {
             $headers[] = $headerName . ': ' . $value;
         }
     }
     $streamContextOptions = array('protocol_version' => $request->getProtocolVersion(), 'method' => $request->getMethod(), 'header' => implode("\r\n", $headers), 'timeout' => $this->timeout, 'ignore_errors' => true, 'follow_location' => $this->followRedirects ? 1 : 0, 'max_redirects' => 100);
     if (strlen($body) > 0) {
         $streamContextOptions['content'] = $body;
     }
     $context = stream_context_create(array('http' => $streamContextOptions, 'https' => $streamContextOptions));
     $httpHeadersOffset = 0;
     $finalUrl = (string) $request->getUri();
     stream_context_set_params($context, array('notification' => function ($code, $severity, $msg, $msgCode, $bytesTx, $bytesMax) use(&$remoteDocument, &$http_response_header, &$httpHeadersOffset) {
         if ($code === STREAM_NOTIFY_REDIRECTED) {
             $finalUrl = $msg;
             $httpHeadersOffset = count($http_response_header);
         }
     }));
     $response = $this->messageFactory->createResponse();
     if (false === ($responseBody = @file_get_contents((string) $request->getUri(), false, $context))) {
         if (!isset($http_response_header)) {
             throw new NetworkException('Unable to execute request', $request);
         }
     } else {
         $response = $response->withBody($this->streamFactory->createStream($responseBody));
     }
     $parser = new HeaderParser();
     try {
         return $parser->parseArray(array_slice($http_response_header, $httpHeadersOffset), $response);
     } catch (\Exception $e) {
         throw new RequestException($e->getMessage(), $request, $e);
     }
 }
示例#12
0
 public function _build_context($url, $params = '', $method = 'GET', $headers = '', $files = array())
 {
     $options = array();
     $options['http']['header'] = array();
     $options['http']['method'] = $method;
     $options['http']['timeout'] = $this->client->timeout;
     if ($this->client->bindip) {
         $options['socket']['bindto'] = $this->client->bindip;
     }
     $context = $this->_init_context();
     if (is_array($params)) {
         $data = http_build_query($params);
     } else {
         $data = $params;
     }
     if (!empty($files)) {
         $boundary = "---------------------" . substr(uniqid(), 0, 10);
         $data = "--{$boundary}\r\n";
         foreach ($params as $key => $val) {
             $data .= "Content-Disposition: form-data; name=\"" . $key . "\"\r\n\r\n" . $val . "\r\n";
             $data .= "--{$boundary}\r\n";
         }
         foreach ($files as $key => $file) {
             $size = @getimagesize($file);
             if (isset($size['mime'])) {
                 $mime = $size['mime'];
             } else {
                 $mime = 'application/octet-stream';
             }
             $data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file}\"\r\n";
             $data .= "Content-Type: {$mime}\r\n";
             $data .= "Content-Transfer-Encoding: binary\r\n\r\n";
             $data .= file_get_contents($file) . "\r\n";
             $data .= "--{$boundary}\r\n";
         }
     }
     if ($method == 'POST') {
         if ($files) {
             $options['http']['header'][] = "Content-Type: multipart/form-data; boundary={$boundary}\r\n";
         } else {
             $options['http']['header'][] = "Content-Type: application/x-www-form-urlencoded\r\n";
         }
         if ($data) {
             $options['http']['content'] = $data;
         }
     } elseif ($method == 'GET') {
         if ($params) {
             $url .= '?' . $data;
         }
     }
     if ($headers) {
         if (is_array($headers)) {
             $options['http']['header'] = array_merge($options['http']['header'], $headers);
         } else {
             $options['http']['header'][] = $headers;
         }
         if (!empty($this->client->headers)) {
             $options['http']['header'] = array_merge($options['http']['header'], $this->client->headers);
         }
     }
     if (!empty($this->client->cookie)) {
         if (!is_scalar($this->client->cookie)) {
             $cookie = http_build_query($this->client->cookie);
         } else {
             $cookie = $this->client->cookie;
         }
         $options['http']['header'][] = "Cookie: {$cookie}\r\n";
     }
     $options['http']['header'] = implode("\r\n", array_map('trim', $options['http']['header']));
     $options['http']['ignore_errors'] = 1;
     stream_context_set_params($context, $options);
     return $context;
 }
 public static function validate_test_profile(&$test_profile)
 {
     if ($test_profile->get_file_location() == null) {
         echo PHP_EOL . 'ERROR: The file location of the XML test profile source could not be determined.' . PHP_EOL;
         return false;
     }
     // Validate the XML against the XSD Schemas
     libxml_clear_errors();
     // Now re-create the pts_test_profile object around the rewritten XML
     $test_profile = new pts_test_profile($test_profile->get_identifier());
     $valid = $test_profile->validate();
     if ($valid == false) {
         echo PHP_EOL . 'Errors occurred parsing the main XML.' . PHP_EOL;
         pts_validation::process_libxml_errors();
         return false;
     }
     // Rewrite the main XML file to ensure it is properly formatted, elements are ordered according to the schema, etc...
     $test_profile_writer = new pts_test_profile_writer();
     $test_profile_writer->rebuild_test_profile($test_profile);
     $test_profile_writer->save_xml($test_profile->get_file_location());
     // Now re-create the pts_test_profile object around the rewritten XML
     $test_profile = new pts_test_profile($test_profile->get_identifier());
     $valid = $test_profile->validate();
     if ($valid == false) {
         echo PHP_EOL . 'Errors occurred parsing the main XML.' . PHP_EOL;
         pts_validation::process_libxml_errors();
         return false;
     } else {
         echo PHP_EOL . 'Test Profile XML Is Valid.' . PHP_EOL;
     }
     // Validate the downloads file
     $download_xml_file = $test_profile->get_file_download_spec();
     if (empty($download_xml_file) == false) {
         $writer = new pts_test_profile_downloads_writer();
         $writer->rebuild_download_file($test_profile);
         $writer->save_xml($download_xml_file);
         $downloads_parser = new pts_test_downloads_nye_XmlReader($download_xml_file);
         $valid = $downloads_parser->validate();
         if ($valid == false) {
             echo PHP_EOL . 'Errors occurred parsing the downloads XML.' . PHP_EOL;
             pts_validation::process_libxml_errors();
             return false;
         } else {
             echo PHP_EOL . 'Test Downloads XML Is Valid.' . PHP_EOL;
         }
         // Validate the individual download files
         echo PHP_EOL . 'Testing File Download URLs.' . PHP_EOL;
         $files_missing = 0;
         $file_count = 0;
         foreach (pts_test_install_request::read_download_object_list($test_profile) as $download) {
             foreach ($download->get_download_url_array() as $url) {
                 $stream_context = pts_network::stream_context_create();
                 stream_context_set_params($stream_context, array('notification' => 'pts_stream_status_callback'));
                 $file_pointer = fopen($url, 'r', false, $stream_context);
                 if ($file_pointer == false) {
                     echo 'File Missing: ' . $download->get_filename() . ' / ' . $url . PHP_EOL;
                     $files_missing++;
                 } else {
                     fclose($file_pointer);
                 }
                 $file_count++;
             }
         }
         if ($files_missing > 0) {
             return false;
         }
     }
     // Validate the parser file
     $parser_file = $test_profile->get_file_parser_spec();
     if (empty($parser_file) == false) {
         $writer = self::rebuild_result_parser_file($parser_file);
         $writer->saveXMLFile($parser_file);
         $parser = new pts_parse_results_nye_XmlReader($parser_file);
         $valid = $parser->validate();
         if ($valid == false) {
             echo PHP_EOL . 'Errors occurred parsing the results parser XML.' . PHP_EOL;
             pts_validation::process_libxml_errors();
             return false;
         } else {
             echo PHP_EOL . 'Test Results Parser XML Is Valid.' . PHP_EOL;
         }
     }
     // Make sure no extra files are in there
     $allowed_files = pts_validation::test_profile_permitted_files();
     foreach (pts_file_io::glob($test_profile->get_resource_dir() . '*') as $tp_file) {
         if (!is_file($tp_file) || !in_array(basename($tp_file), $allowed_files)) {
             echo PHP_EOL . basename($tp_file) . ' is not allowed in the test package.' . PHP_EOL;
             return false;
         }
     }
     return true;
 }
 public static function stream_download($download, $download_to, $stream_context_parameters = null, $callback_function = array('pts_network', 'stream_status_callback'))
 {
     $stream_context = pts_network::stream_context_create($stream_context_parameters);
     if (function_exists('stream_context_set_params')) {
         // HHVM 2.1 doesn't have stream_context_set_params()
         stream_context_set_params($stream_context, array('notification' => $callback_function));
     }
     /*
     if(strpos($download, 'https://openbenchmarking.org/') !== false)
     {
     	stream_context_set_option($stream_context, 'ssl', 'local_cert', PTS_CORE_STATIC_PATH . 'certificates/openbenchmarking-server.pem');
     }
     else if(strpos($download, 'https://www.phoromatic.com/') !== false)
     {
     	stream_context_set_option($stream_context, 'ssl', 'local_cert', PTS_CORE_STATIC_PATH . 'certificates/phoromatic-com.pem');
     }
     */
     $file_pointer = @fopen($download, 'r', false, $stream_context);
     if (is_resource($file_pointer) && file_put_contents($download_to, $file_pointer)) {
         return true;
     }
     return false;
 }
示例#15
0
/**
 * The default implementation to retrieve JSON-LD at the given secure URL.
 *
 * @param string $url the secure URL to to retrieve.
 *
 * @return stdClass the RemoteDocument object.
 */
function jsonld_default_secure_document_loader($url)
{
    if (strpos($url, 'https') !== 0) {
        throw new Exception("Could not GET url: '{$url}'; 'https' is required.");
    }
    $redirects = array();
    // default JSON-LD https GET implementation
    $opts = array('https' => array('verify_peer' => true, 'method' => "GET", 'header' => "Accept: application/ld+json\r\n" . "User-Agent: JSON-LD PHP Client/1.0\r\n"));
    $stream = stream_context_create($opts);
    stream_context_set_params($stream, array('notification' => function ($notification_code, $severity, $message) use(&$redirects) {
        switch ($notification_code) {
            case STREAM_NOTIFY_REDIRECTED:
                $redirects[] = $message;
                break;
        }
    }));
    $result = @file_get_contents($url, false, $stream);
    if ($result === false) {
        throw new Exception("Could not GET url: '{$url}'");
    }
    foreach ($redirects as $redirect) {
        if (strpos($redirect, 'https') !== 0) {
            throw new Exception("Could not GET redirected url: '{$redirect}'; 'https' is required.");
        }
        $url = $redirect;
    }
    // return RemoteDocument
    return (object) array('contextUrl' => null, 'document' => $result, 'documentUrl' => $url);
}
 function podlovewebplayer_render_chapters($input)
 {
     global $post;
     if (json_decode($input) === null) {
         $input = trim($input);
         $chapters = false;
         if ($input != '') {
             if (substr($input, 0, 7) == 'http://' || substr($input, 0, 8) == 'https://') {
                 $http_context = stream_context_create();
                 stream_context_set_params($http_context, array('user_agent' => 'UserAgent/1.0'));
                 $chapters = trim(@file_get_contents($input, 0, $http_context));
                 $json_chapters = json_decode($chapters);
                 if ($json_chapters !== null) {
                     return $json_chapters;
                 }
             } elseif ($chapters = get_post_custom_values($input, $post->ID)) {
                 $chapters = trim($chapters[0]);
                 $json_chapters = json_decode($chapters);
                 if ($json_chapters !== null) {
                     return $json_chapters;
                 }
             }
         }
         if ($chapters == '') {
             return '';
         }
         preg_match_all('/((\\d+:)?(\\d\\d?):(\\d\\d?)(?:\\.(\\d+))?) ([^<>\\r\\n]{3,}) ?(<([^<>\\r\\n]*)>\\s*(<([^<>\\r\\n]*)>\\s*)?)?\\r?/', $chapters, $chapterArrayTemp, PREG_SET_ORDER);
         $chaptercount = count($chapterArrayTemp);
         for ($i = 0; $i < $chaptercount; ++$i) {
             $chapterArray[$i]['start'] = $chapterArrayTemp[$i][1];
             $chapterArray[$i]['title'] = htmlspecialchars($chapterArrayTemp[$i][6], ENT_QUOTES);
             if (isset($chapterArrayTemp[$i][9])) {
                 $chapterArray[$i]['image'] = trim($chapterArrayTemp[$i][10], '<> ()\'');
             }
             if (isset($chapterArrayTemp[$i][7])) {
                 $chapterArray[$i]['href'] = trim($chapterArrayTemp[$i][8], '<> ()\'');
             }
         }
         return $chapterArray;
     }
     return $input;
 }
function file_get_contents_with_console($filename)
{
    consoleLog("Download: " . $filename);
    $ctx = stream_context_create();
    stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
    $data = @file_get_contents($filename, false, $ctx);
    if ($data !== false) {
        $size = strlen($data);
        consoleLogProgressBar($size, $size);
        consoleLogBlank();
        consoleLogBlank();
        return $data;
    }
    $err = error_get_last();
    consoleLog("<span>Error:</span> " . $err["message"]);
    consoleLogBlank();
    return false;
}
示例#18
0
 public function __callback_createStreamContext()
 {
     $stream = stream_context_create($this->_closure_createStreamContext_options);
     stream_context_set_params($stream, $this->_closure_createStreamContext_params);
     return $stream;
 }
<?php

require 'server.inc';
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max)
{
    if ($notification_code == STREAM_NOTIFY_REDIRECTED) {
        // $http_response_header is now a string, but will be used as an array
        // by php_stream_url_wrap_http_ex() later on
        $GLOBALS['http_response_header'] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    }
}
$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
$responses = array("data://text/plain,HTTP/1.0 302 Found\r\nLocation: http://127.0.0.1:22345/try-again\r\n\r\n", "data://text/plain,HTTP/1.0 404 Not Found\r\n\r\n");
$pid = http_server("tcp://127.0.0.1:22345", $responses, $output);
$f = file_get_contents('http://127.0.0.1:22345/', 0, $ctx);
http_server_kill($pid);
var_dump($f);
?>
==DONE==
示例#20
0
 function __set($key, $value)
 {
     $param = array($key => $value);
     stream_context_set_params($this->getContext()->getResource(), $param);
     parent::__set($key, $value);
 }
示例#21
0
/**
 * The default implementation to retrieve JSON-LD at the given secure URL.
 *
 * @param string $url the secure URL to to retrieve.
 *
 * @return stdClass the RemoteDocument object.
 */
function jsonld_default_secure_document_loader($url)
{
    if (strpos($url, 'https') !== 0) {
        throw new JsonLdException("Could not GET url: '{$url}'; 'https' is required.", 'jsonld.LoadDocumentError', 'loading document failed');
    }
    $doc = (object) array('contextUrl' => null, 'document' => null, 'documentUrl' => $url);
    $redirects = array();
    // default JSON-LD https GET implementation
    $opts = array('http' => array('method' => 'GET', 'header' => "Accept: application/ld+json\r\n"), 'ssl' => array('verify_peer' => true, 'allow_self_signed' => false, 'cafile' => '/etc/ssl/certs/ca-certificates.crt'));
    $context = stream_context_create($opts);
    $content_type = null;
    stream_context_set_params($context, array('notification' => function ($notification_code, $severity, $message) use(&$redirects, &$content_type) {
        switch ($notification_code) {
            case STREAM_NOTIFY_REDIRECTED:
                $redirects[] = $message;
                break;
            case STREAM_NOTIFY_MIME_TYPE_IS:
                $content_type = $message;
                break;
        }
    }));
    $result = @file_get_contents($url, false, $context);
    if ($result === false) {
        throw new JsonLdException('Could not retrieve a JSON-LD document from the URL: ' + $url, 'jsonld.LoadDocumentError', 'loading document failed');
    }
    $link_header = array();
    foreach ($http_response_header as $header) {
        if (strpos($header, 'link') === 0) {
            $value = explode(': ', $header);
            if (count($value) > 1) {
                $link_header[] = $value[1];
            }
        }
    }
    $link_header = jsonld_parse_link_header(join(',', $link_header));
    if (isset($link_header['http://www.w3.org/ns/json-ld#context'])) {
        $link_header = $link_header['http://www.w3.org/ns/json-ld#context'];
    } else {
        $link_header = null;
    }
    if ($link_header && $content_type !== 'application/ld+json') {
        // only 1 related link header permitted
        if (is_array($link_header)) {
            throw new JsonLdException('URL could not be dereferenced, it has more than one ' . 'associated HTTP Link Header.', 'jsonld.LoadDocumentError', 'multiple context link headers', array('url' => $url));
        }
        $doc->{'contextUrl'} = $link_header->target;
    }
    // update document url based on redirects
    foreach ($redirects as $redirect) {
        if (strpos($redirect, 'https') !== 0) {
            throw new JsonLdException("Could not GET redirected url: '{$redirect}'; 'https' is required.", 'jsonld.LoadDocumentError', 'loading document failed');
        }
        $url = $redirect;
    }
    $doc->document = $result;
    $doc->documentUrl = $url;
    return $doc;
}
function fiftyone_degrees_download_to_file($url, $file_name)
{
    $result = FALSE;
    $params = array('http' => array('method' => 'GET', 'header' => "Accept: application/octet-stream\r\n" . "Accept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n"));
    $name = fiftyone_degrees_get_current_dataset_name();
    if ($name != 'Lite') {
        $data_date = fiftyone_degrees_get_data_date();
        $fdate = date('r', $data_date);
        $params['http']['header'] .= "Last-Modified: {$fdate}\r\n";
    }
    ini_set('user_agent', '51Degrees PHP Device Data Updater');
    $ctx = stream_context_create($params);
    stream_context_set_params($ctx, array("notification" => "fiftyone_degrees_stream_notification"));
    $file = fopen($url, "rb", FALSE, $ctx);
    if (fiftyone_degrees_response_is_304($http_response_header)) {
        fiftyone_degrees_write_message("There is no available data file newer than the one previously installed.");
        if (isset($fdate)) {
            fiftyone_degrees_write_message("Current data is dated {$fdate}.");
        }
        return TRUE;
    }
    $temp_file_name = $file_name . '.tmp';
    if ($file) {
        $newf = fopen($temp_file_name, "wb");
        global $fiftyone_degrees_bytes_max;
        if ($newf) {
            $bytes_loaded = 0;
            while (!feof($file)) {
                /* fread used in this way presents two separate files as the same stream.
                   This checks if the content length has been reached and stops the download
                   before the file is corrupted. */
                $bytes_left = $fiftyone_degrees_bytes_max - $bytes_loaded;
                if ($bytes_left > 0) {
                    $bytes_to_read = 1024 * 8;
                    if ($bytes_to_read > $bytes_left) {
                        $bytes_to_read = $bytes_left;
                    }
                    $segment = fread($file, $bytes_to_read);
                    $written = fwrite($newf, $segment, $bytes_to_read);
                    $bytes_loaded += $written;
                } else {
                    break;
                }
            }
            fclose($newf);
            if (fiftyone_degrees_has_valid_hash($http_response_header, $temp_file_name)) {
                // check that the file is a supported version
                $temp_file = fopen($temp_file_name, 'rb');
                $info = fiftyone_degrees_get_data_info($temp_file);
                $version = "{$info['major_version']}.{$info['minor_version']}";
                $supported_version = fiftyone_degrees_get_supported_version();
                fclose($temp_file);
                if ($version != $supported_version) {
                    fiftyone_degrees_write_message('The data file downloaded has a newer format version than this API supports. Update the API to get new data files.');
                } else {
                    $attempt = 0;
                    while (!@rename($temp_file_name, $file_name) && $attempt < 20) {
                        usleep(500);
                        $attempt++;
                    }
                    if ($attempt >= 20) {
                        fiftyone_degrees_write_message('The data file cannot be written, probably because the server does not have sufficient permissions, or another process is locking the file.');
                    } else {
                        $new_data_date = fiftyone_degrees_get_data_date();
                        $new_data_date_f = date('r', $new_data_date);
                        fiftyone_degrees_write_message("New data downloaded published on {$new_data_date_f}");
                        $result = TRUE;
                    }
                }
            } else {
                fiftyone_degrees_write_message('Invalid file hash. The file is probably corrupted.');
            }
            @unlink($temp_file_name);
        }
        fclose($file);
    }
    return $result;
}
示例#23
0
<?php

$arrayLarge = array_fill(0, 113663, '*');
$resourceFileTemp = fopen('php://temp', 'r+');
stream_context_set_params($resourceFileTemp, array());
preg_replace('', function () {
}, $resourceFileTemp);
示例#24
0
 function setParams(array $params)
 {
     stream_context_set_params($this->context, $params);
 }
示例#25
0
 /**
  * Set the stream context params
  *
  * @param array|resource $context An stream, wrapper or context resource or  an array of context parameters
  * @return bool
  */
 public function setContext($context)
 {
     $result = false;
     //Get the context params from the resource
     if (is_resource($context)) {
         $context = (array) stream_context_get_params($context);
     }
     if (is_array($context)) {
         if (!isset($this->_context)) {
             $this->_context = $context;
         } else {
             $this->_context = array_merge($this->_context, $context);
         }
         $result = stream_context_set_params($this->_resource, $this->_context);
     }
     return $result;
 }
示例#26
0
}
</style>


<?php 
$filename = "cache.txt";
// define cache file
$useragent = 'UserAgent/1.0';
//define user agent
$interval = rand(72000, 100800);
//define random scrape time (between 20  and 28 hours)
if (time() - filemtime($filename) > $interval) {
    // if cache file is older than 20 hours, fetch new data
    $context = stream_context_create();
    // setup options
    stream_context_set_params($context, array('user_agent' => $useragent));
    // fake user agent as option
    $html = file_get_html('http://twitter.com/ruruhuis', 0, $context);
    $fp = fopen($filename, "w");
    //open or create cache file
    foreach ($html->find('p') as $element) {
        echo $element->innertext . "<br><br>";
        // echo the content in all the p tags on screen
        fwrite($fp, $element->innertext . "<br><br>");
        // write elements to static 'cache' file
    }
    fclose($fp);
    //close cache file
} else {
    // if cache file is younger than 20 hours, fetch new data
    echo file_get_contents($filename);
 function xmlPost($url, $request_xml, $verify_peer = false)
 {
     $curl_available = extension_loaded("curl");
     // generate request
     $header = array();
     if (!$curl_available) {
         $url = parse_url($url);
         if (empty($url['port'])) {
             $url['port'] = $url['scheme'] == "https" ? 443 : 80;
         }
         $header[] = "POST " . $url['path'] . "?" . $url['query'] . " HTTP/1.1";
         $header[] = "Host: " . $url['host'] . ":" . $url['port'];
         $header[] = "Content-Length: " . strlen($request_xml);
     }
     $header[] = "Content-Type: text/xml";
     $header[] = "Connection: close";
     // issue request
     if ($curl_available) {
         $ch = curl_init($url);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $request_xml);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, 120);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_peer);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
         curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
         curl_setopt($ch, CURLOPT_HEADER, true);
         //curl_setopt($ch, CURLOPT_HEADER_OUT,     true);
         $reply_data = curl_exec($ch);
     } else {
         $request_data = implode("\r\n", $header);
         $request_data .= "\r\n\r\n";
         $request_data .= $request_xml;
         $reply_data = "";
         $errno = 0;
         $errstr = "";
         $fp = fsockopen(($url['scheme'] == "https" ? "ssl://" : "") . $url['host'], $url['port'], $errno, $errstr, 30);
         if ($fp) {
             if (function_exists("stream_context_set_params")) {
                 stream_context_set_params($fp, array('ssl' => array('verify_peer' => $verify_peer, 'allow_self_signed' => $verify_peer)));
             }
             fwrite($fp, $request_data);
             fflush($fp);
             while (!feof($fp)) {
                 $reply_data .= fread($fp, 1024);
             }
             fclose($fp);
         }
     }
     // check response
     if ($curl_available) {
         if (curl_errno($ch)) {
             $this->error_code = -1;
             $this->error = "curl error: " . curl_errno($ch);
             return false;
         }
         $reply_info = curl_getinfo($ch);
         curl_close($ch);
     } else {
         if ($errno) {
             $this->error_code = -1;
             $this->error = "connection error: " . $errno;
             return false;
         }
         $header_size = strpos($reply_data, "\r\n\r\n");
         $header_data = substr($reply_data, 0, $header_size);
         $header = explode("\r\n", $header_data);
         $status_line = explode(" ", $header[0]);
         $content_type = "application/octet-stream";
         foreach ($header as $header_line) {
             $header_parts = explode(":", $header_line);
             if (strtolower($header_parts[0]) == "content-type") {
                 $content_type = trim($header_parts[1]);
                 break;
             }
         }
         $reply_info = array('http_code' => (int) $status_line[1], 'content_type' => $content_type, 'header_size' => $header_size + 4);
     }
     if ($reply_info['http_code'] != 200) {
         $this->error_code = -1;
         $this->error = "http error: " . $reply_info['http_code'];
         return false;
     }
     if (strstr($reply_info['content_type'], "/xml") === false) {
         $this->error_code = -1;
         $this->error = "content type error: " . $reply_info['content_type'];
         return false;
     }
     // split header and body
     $reply_header = substr($reply_data, 0, $reply_info['header_size'] - 4);
     $reply_xml = substr($reply_data, $reply_info['header_size']);
     if (empty($reply_xml)) {
         $this->error_code = -1;
         $this->error = "received empty response";
         return false;
     }
     return $reply_xml;
 }
示例#28
0
文件: Purl.php 项目: noughts/purl
 /**
  * Make request using file_get_contents.
  * Trying to set as much curl original settings as possible
  *
  * @param string $query GET query string
  * @param array $headers headers to send along with request
  * @return boolean|string
  */
 protected function _call($query, $headers)
 {
     $options = array('http' => array('method' => $this->_method, 'header' => $headers, 'ignore_errors' => true, 'user_agent' => $this->_agent));
     // HTTP context settings
     if (isset($this->_options[CURLOPT_TIMEOUT])) {
         $options['http']['timeout'] = $this->_options[CURLOPT_TIMEOUT];
     }
     if (isset($this->_options[CURLOPT_FOLLOWLOCATION])) {
         $options['http']['follow_location'] = $this->_options[CURLOPT_FOLLOWLOCATION];
     }
     if (isset($this->_options[CURLOPT_MAXREDIRS])) {
         $options['http']['max_redirects'] = $this->_options[CURLOPT_MAXREDIRS];
     }
     if (isset($this->_options[CURLOPT_PROXY])) {
         $options['http']['proxy'] = $this->_options[CURLOPT_PROXY];
         $options['http']['request_fulluri'] = true;
     }
     // SSL context settings
     if (isset($this->_options[CURLOPT_SSL_VERIFYPEER])) {
         $options['ssl']['verify_peer'] = $this->_options[CURLOPT_SSL_VERIFYPEER];
     }
     if (isset($this->_options[CURLOPT_CAINFO])) {
         $options['ssl']['cafile'] = $this->_options[CURLOPT_CAINFO];
     }
     if (isset($this->_options[CURLOPT_USERPWD]) && $this->_options[CURLOPT_USERPWD]) {
         $url_parts = explode('://', $this->_url);
         $this->_url = $url_parts[0] . '://' . $this->_options[CURLOPT_USERPWD] . '@' . $url_parts[1];
     }
     if ($this->_method === 'POST') {
         $options['http']['content'] = $query;
     } elseif (!empty($query)) {
         $this->_url .= '?' . $query;
     }
     $context = stream_context_create($options);
     stream_context_set_params($context, array('notification' => function () {
         // not working yet :/
         $this->_logs[] = func_get_args();
     }));
     $reporting = error_reporting(0);
     if (!empty($this->_options[CURLOPT_NOBODY])) {
         $handler = fopen($this->_url, 'r', false, $context);
     } else {
         $this->_result = file_get_contents($this->_url, false, $context);
     }
     $httpCode = explode(' ', $http_response_header[0])[1];
     $this->_info['http_code'] = (int) $httpCode;
     // response Content Type
     foreach ($http_response_header as $header) {
         if (1 === preg_match('/Content\\-Type/iu', $header)) {
             $this->_info['content_type'] = $header;
             break;
         }
     }
     error_reporting($reporting);
     // on failure
     if ($this->_result === false || isset($handler) && $handler === false) {
         $this->_errorHandler();
         return false;
     }
     if (!empty($this->_options[CURLOPT_HEADER])) {
         $this->_result = implode($http_response_header, "\r\n") . "\r\n\r\n" . $this->_result;
     }
     $this->_responseno = explode(' ', $http_response_header[0])[1];
     return isset($this->_options[CURLOPT_RETURNTRANSFER]) ? $this->_result : true;
 }
示例#29
0
 /**
  * Create the context of this stream with the options passed, callback function if set.
  *
  * @return resource $return The created context resource
  */
 protected function create_context()
 {
     $this->context = stream_context_create($this->context_options);
     if (is_callable($this->notification)) {
         stream_context_set_params($this->context, array('notification' => $this->notification));
     }
     return $this->context;
 }
示例#30
0
<?php

$ctx = stream_context_get_default();
stream_context_set_params($ctx, array("options" => 1));