/** * {@inheritDoc} * * @return Stream|Response */ public function indexAction() { $response = $this->getResponse(); $params = $this->params()->fromRoute(); if ($params['path'] === '') { $response->setStatusCode(404); return $response; } $info = pathinfo($params['path']); if ($info['dirname'] === '.') { $info['dirname'] = ''; } /* @var $folder \CmsFile\Mapping\FolderInterface */ $folder = $this->getFolderService()->getMapper()->findOneByPath('/' . trim($info['dirname'], '/')); if (!$folder) { $response->setStatusCode(404); return $response; } $file = $folder->getFile($info['basename']); if (!$file) { $response->setStatusCode(404); return $response; } $response = new Stream(); $response->setStream(fopen($file, 'r')); $response->setStatusCode(200); $headers = new Headers(); $headers->addHeaderLine('Content-Type', $file->getType())->addHeaderLine('Content-Disposition', 'attachment; filename="' . $file->getTitle() . '"')->addHeaderLine('Content-Length', filesize($file)); $response->setHeaders($headers); return $response; }
/** * Prepare cache-busting headers for GET requests * * Invoked from the onFinish() method for GET requests to disable client-side HTTP caching. * * @param Headers $headers */ protected function disableHttpCache(Headers $headers) { $headers->addHeader(new GenericHeader('Expires', '0')); $headers->addHeader(new GenericMultiHeader('Cache-Control', 'no-store, no-cache, must-revalidate')); $headers->addHeader(new GenericMultiHeader('Cache-Control', 'post-check=0, pre-check=0')); $headers->addHeaderLine('Pragma', 'no-cache'); }
/** * {@inheritdoc} */ public function sendRequest(RequestInterface $request) { $request = $this->sanitizeRequest($request); $headers = new Headers(); foreach ($request->getHeaders() as $key => $value) { $headers->addHeader(new GenericHeader($key, $request->getHeaderLine($key))); } $zendRequest = new Request(); $zendRequest->setMethod($request->getMethod()); $zendRequest->setUri((string) $request->getUri()); $zendRequest->setHeaders($headers); $zendRequest->setContent($request->getBody()->getContents()); $options = ['httpversion' => $request->getProtocolVersion()]; if (extension_loaded('curl')) { $options['curloptions'] = [CURLOPT_HTTP_VERSION => $this->getProtocolVersion($request->getProtocolVersion())]; } $this->client->setOptions($options); if ($this->client->getAdapter() instanceof ZendClient\Adapter\Curl && $request->getMethod()) { $request = $request->withHeader('Content-Length', '0'); } try { $zendResponse = $this->client->send($zendRequest); } catch (RuntimeException $exception) { throw new NetworkException($exception->getMessage(), $request, $exception); } return $this->responseFactory->createResponse($zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent(), $zendResponse->getVersion()); }
public function get($id) { $headers = new Headers(); $headers->addHeaderLine('Access-Control-Allow-Origin', '*'); $json = new JsonModel(array('data' => $this->listadoCursos($id))); return $json; }
/** * Normalize headers to use with HeaderAwareResponseInterface. * * Ensures multi-value headers are represented as a single string, via * comma concatenation. * * @param Headers $headers * @return array */ private function prepareResponseHeaders(Headers $headers) { $normalized = []; foreach ($headers->toArray() as $name => $value) { $normalized[$name] = is_array($value) ? implode(', ', $value) : $value; } return $normalized; }
/** * Retrieve Mobile-detect service * @param \Zend\Http\Headers $oHeaders * @return \Mobile_Detect */ public function __invoke(\Zend\Http\Headers $oHeaders = null) { $oMobileDetect = $this->getServiceLocator()->getServiceLocator()->get('MobileDetect'); if ($oHeaders) { $oMobileDetect->setHttpHeaders($oHeaders->toArray()); $oMobileDetect->setUserAgent($oHeaders->get('user-agent')->getFieldValue()); } return $oMobileDetect; }
function it_should_be_use_constant(Headers $headers) { $headers->clearHeaders()->shouldBeCalledTimes(1); $headers->addHeaderLine("Content-Type", "application/json")->shouldBeCalledTimes(1); $headers->addHeaderLine("Authorization", "token token")->shouldBeCalledTimes(1); $this->setHeaders($headers); $this->setStatusFor("aaa", ["state" => \Gstatus\Request\Status::FAILURE]); $this->prepareRequest("token"); $this->getContent()->shouldBe('{"state":"failure"}'); }
/** * @param \Zend_Controller_Response_Abstract $response * @return \Zend\Http\Headers */ protected function getHeadersFromResponse(\Zend_Controller_Response_Abstract $response) { $headers = new HttpHeaders(); foreach ($response->getRawHeaders() as $header) { $headers->addHeaderLine($header); } foreach ($response->getHeaders() as $header) { $headers->addHeaderLine($header['name'], $header['value']); } return $headers; }
public function testClearHeaderAndHeaderNotExists() { $response = $this->response = $this->getMock('Magento\\Framework\\HTTP\\PhpEnvironment\\Response', ['getHeaders', 'send']); $this->headers->addHeaderLine('Header-name: header-value'); $header = \Zend\Http\Header\GenericHeader::fromString('Header-name: header-value'); $this->headers->expects($this->once())->method('has')->with('Header-name')->will($this->returnValue(false)); $this->headers->expects($this->never())->method('get')->with('Header-name')->will($this->returnValue($header)); $this->headers->expects($this->never())->method('removeHeader')->with($header); $response->expects($this->once())->method('getHeaders')->will($this->returnValue($this->headers)); $response->clearHeader('Header-name'); }
/** * Validate the passed mediatype against the appropriate header * * @param string $match * @param HttpHeaders $headers * @return bool */ protected function validateMediaType($match, HttpHeaders $headers) { if (!$headers->has('accept')) { return true; } $accept = $headers->get('accept'); if ($accept->match($match)) { return true; } return false; }
/** * Get Request * * @return Request */ public function getRequest() { if (empty($this->request)) { $headers = new Headers(); $headers->addHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json')); $request = parent::getRequest(); $request->setHeaders($headers); $request->setMethod('POST'); } return $this->request; }
/** * Retrieve Mobile-detect service * * @param \Zend\Http\Headers $oHeaders * * @throws \LogicException * @return \Mobile_Detect */ public function __invoke(\Zend\Http\Headers $oHeaders = null) { $oController = $this->getController(); if (!$oController) { throw new \LogicException('Controller is undefined for MobileDetect controller plugin'); } if ($oHeaders) { $this->mobileDetect->setHttpHeaders($oHeaders->toArray()); $this->mobileDetect->setUserAgent($oHeaders->get('user-agent')->getFieldValue()); } return $this->mobileDetect; }
public function testFromResponseInCookie() { $response = new Response(); $headers = new Headers(); $header = new SetCookie("foo", "bar"); $header->setDomain("www.zend.com"); $header->setPath("/"); $headers->addHeader($header); $response->setHeaders($headers); $response = Cookies::fromResponse($response, "http://www.zend.com"); $this->assertSame($header, $response->getCookie('http://www.zend.com', 'foo')); }
/** * * @return \Zend\View\Model\ViewModel */ public function execute() { $optionsRenderer = $this->getOptionsRenderer(); $delimiter = ','; if (isset($optionsRenderer['delimiter'])) { $delimiter = $optionsRenderer['delimiter']; } $enclosure = '"'; if (isset($optionsRenderer['enclosure'])) { $enclosure = $optionsRenderer['enclosure']; } $options = $this->getOptions(); $optionsExport = $options['settings']['export']; $path = $optionsExport['path']; $saveFilename = date('Y-m-d_H-i-s') . $this->getCacheId() . '.csv'; $fp = fopen($path . '/' . $saveFilename, 'w'); // Force UTF-8 for CSV rendering in EXCEL. fprintf($fp, chr(0xef) . chr(0xbb) . chr(0xbf)); /* * Save the file */ // header if (isset($optionsRenderer['header']) && true === $optionsRenderer['header']) { $header = []; foreach ($this->getColumnsToExport() as $col) { $header[] = $this->getTranslator()->translate($col->getLabel()); } fputcsv($fp, $header, $delimiter, $enclosure); } // data foreach ($this->getData() as $row) { $csvRow = []; foreach ($this->getColumnsToExport() as $col) { $value = $row[$col->getUniqueId()]; if ($col->getType() instanceof Type\PhpArray || $col->getType() instanceof Type\Image) { $value = implode(',', $value); } $csvRow[] = $value; } fputcsv($fp, $csvRow, $delimiter, $enclosure); } fclose($fp); /* * Return the file */ $response = new ResponseStream(); $response->setStream(fopen($path . '/' . $saveFilename, 'r')); $headers = new Headers(); $headers->addHeaders(['Content-Type' => ['application/force-download', 'application/octet-stream', 'application/download', 'text/csv; charset=utf-8'], 'Content-Length' => filesize($path . '/' . $saveFilename), 'Content-Disposition' => 'attachment;filename=' . $this->getFilename() . '.csv', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT']); $response->setHeaders($headers); return $response; }
public static function nearby($countryCode, $postalCode) { $http = new Client(); $http->setOptions(array('sslverifypeer' => false)); $headers = new Headers(); $headers->addHeaderLine('Content-Type', 'application/json'); $http->setHeaders($headers); $http->setUri(self::$apiUrl . 'nearby/' . urlencode($countryCode) . '/' . urlencode($postalCode)); $http->setMethod('GET'); $response = $http->send(); $json = Json::decode($response->getBody()); return $json; }
/** * Get file stream response * * * @access public * @param string $file * @return Stream */ public function getFileResponse($file) { $response = new Response(); if (!empty($file) && file_exists($file)) { $response = new Stream(); $response->setStream(fopen($file, 'r')); $response->setStatusCode(200); $response->setStreamName(basename($file)); $headers = new Headers(); $headers->addHeaders(array('Content-Disposition' => 'attachment; filename="' . basename($file) . '"', 'Content-Type' => 'application/octet-stream', 'Content-Length' => filesize($file), 'Expires' => '@0', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'public')); $response->setHeaders($headers); } return $response; }
/** * @param Request $request * @return Response */ public function request(Request $request) { $headers = new Headers(); $headers->addHeaders($request->getHeaders()); $zendRequest = new ZendRequest(); $zendRequest->setVersion($request->getProtocolVersion()); $zendRequest->setMethod($request->getMethod()); $zendRequest->setUri((string) $request->getUrl()); $zendRequest->setHeaders($headers); $zendRequest->setContent($request->getContent()); /** @var ZendResponse $zendResponse */ $zendResponse = $this->client->send($zendRequest); return new Response((string) $zendResponse->getVersion(), $zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent()); }
public function testGet() { $expectedDate = '2015-01-01'; $headers = new Headers(); $headers->addHeaderLine(sprintf('Cookie: %s=%s', TimetableCookieListener::COOKIE_NAME, $expectedDate)); $request = new Request(); $request->setHeaders($headers); $response = new Response(); $listener = new TimetableCookieListener($request, $response); $event = new TimetableManagerEvent(); $listener->getTime($event); $this->assertTrue($event->hasPointInTime()); $this->assertEquals($expectedDate, $event->getPointInTime()->format('Y-m-d')); }
/** * */ private function injectEsiHeader() { if (!$this->esiHeaderInjected) { $this->responseHeaders->addHeaderLine('Surrogate-Control', 'ESI/1.0'); $this->esiHeaderInjected = true; } }
public function pharAction() { $client = $this->serviceLocator->get('zendServerClient'); $client = new Client(); if (defined('PHAR')) { // the file from which the application was started is the phar file to replace $file = $_SERVER['SCRIPT_FILENAME']; } else { $file = dirname($_SERVER['SCRIPT_FILENAME']) . '/zs-client.phar'; } $request = new Request(); $request->setMethod(Request::METHOD_GET); $request->setHeaders(Headers::fromString('If-Modified-Since: ' . gmdate('D, d M Y H:i:s T', filemtime($file)))); $request->setUri('https://github.com/zendtech/ZendServerSDK/raw/master/bin/zs-client.phar'); //$client->getAdapter()->setOptions(array('sslcapath' => __DIR__.'/../../../certs/')); $client->setAdapter(new Curl()); $response = $client->send($request); if ($response->getStatusCode() == 304) { return 'Already up-to-date.'; } else { ErrorHandler::start(); rename($file, $file . '.' . date('YmdHi') . '.backup'); $handler = fopen($file, 'w'); fwrite($handler, $response->getBody()); fclose($handler); ErrorHandler::stop(true); return 'The phar file was updated successfully.'; } }
/** * Execute the request * * @param RequestInterface $request * @param ResponseInterface $response (Default: null) * @return \Zend\Http\PhpEnvironment\Response */ public function dispatch(RequestInterface $request, ResponseInterface $response = null) { // the config hash $config = $this->getServiceLocator()->get('Config'); $config = $config['TpMinify']; // some important stuff $config['serveOptions']['quiet'] = true; // the time correction Minify::$uploaderHoursBehind = $config['uploaderHoursBehind']; // the cache engine Minify::setCache($config['cachePath'] ?: '', $config['cacheFileLocking']); // doc root corrections if ($config['documentRoot']) { $_SERVER['DOCUMENT_ROOT'] = $config['documentRoot']; Minify::$isDocRootSet = true; } // check for URI versioning if (preg_match('~&\\d~', $request->getUriString())) { $config['serveOptions']['maxAge'] = 31536000; } // minify result as array of information $result = Minify::serve('MinApp', $config['serveOptions']); // some corrections if (isset($result['headers']['_responseCode'])) { unset($result['headers']['_responseCode']); } // the headers set $headers = new Headers(); $headers->addHeaders($result['headers']); // final output return $response->setHeaders($headers)->setStatusCode($result['statusCode'])->setContent($result['content']); }
/** * @param string $collectionPath * @param \SimpleXMLElement $element * @return \SimpleXMLElement | null */ public function save($collectionPath, \SimpleXMLElement $element) { $uri = new Http($collectionPath); $request = new Request(); $request->setMethod('PUT'); $headers = new Headers(); $headers->addHeader(new GenericHeader('Content-Type', 'application/xml')); $request->setHeaders($headers); $request->setContent($element->asXML()); $response = $this->transport->put($uri, $request); $body = $response->getBody(); if ($response->isClientError() || empty($body)) { return null; } return new \SimpleXMLElement($body); }
public static function getCountries() { $http = new Client(); $http->setOptions(array('sslverifypeer' => false)); $headers = new Headers(); $headers->addHeaderLine('X-Mashape-Key', MASHAPE_API_KEY); $http->setHeaders($headers); $http->setUri("https://restcountries-v1.p.mashape.com/all"); $http->setMethod('GET'); $response = $http->send(); $json = Json::decode($response->getBody()); $data = array(); foreach ($json as $country) { $data[] = array("code" => strtolower($country->alpha2Code), "name" => $country->name); } return $data; }
/** * @param Headers $headers * * @return string|null */ private function getBrowseAcceptLanguage(Headers $headers) { if ($headers->has('Accept-Language')) { /** @var AcceptLanguage $acceptLanguageHeader */ $acceptLanguageHeader = $headers->get('Accept-Language'); $locales = $acceptLanguageHeader->getPrioritized(); $languages = $this->config->getAvailableLanguages(); /** @var LanguageFieldValuePart $locale */ foreach ($locales as $locale) { // Loop through all locales, highest priority first if ($browserLang = \Locale::lookup($languages, $locale->getRaw())) { return $browserLang; } } } return null; }
/** * Return the header container responsible for headers * * @return Headers */ public function getHeaders() { if ($this->headers === null || is_string($this->headers)) { // this is only here for fromString lazy loading $this->headers = is_string($this->headers) ? Headers::fromString($this->headers) : new Headers(); } return $this->headers; }
public function testRetrievingASingleValueForParameters() { $request = new Request(); $p = new \Zend\Stdlib\Parameters(array('foo' => 'bar')); $request->setQuery($p); $request->setPost($p); $request->setFiles($p); $this->assertSame('bar', $request->getQuery('foo')); $this->assertSame('bar', $request->getPost('foo')); $this->assertSame('bar', $request->getFiles('foo')); $headers = new Headers(); $h = new GenericHeader('foo', 'bar'); $headers->addHeader($h); $request->setHeaders($headers); $this->assertSame($headers, $request->getHeaders()); $this->assertSame($h, $request->getHeaders()->get('foo')); $this->assertSame($h, $request->getHeader('foo')); }
/** * @return string */ public function toString() { $str = $this->renderRequestLine() . "\r\n"; if ($this->headers) { $str .= $this->headers->toString(); } $str .= "\r\n"; $str .= $this->getContent(); return $str; }
/** * @param Headers $headers * * @return \SplFileInfo */ public function getStreamPath(Headers $headers) { $filename = null; $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid(); if (!file_exists($directory)) { mkdir($directory, 0775, true); } if (!$this->filename) { if ($headers->has('content-disposition')) { $field = $headers->get('content-disposition')->getFieldValue(); if (preg_match('`filename\\="(.*)"`', $field, $matches)) { $this->filename = basename($matches[1]); } } if (null === $filename) { $this->filename = uniqid(); } } return new \SplFileInfo($directory . DIRECTORY_SEPARATOR . $this->filename); }
/** * @param MvcEvent $event */ public function onDispatchError(MvcEvent $event) { if (Application::ERROR_ROUTER_NO_MATCH != $event->getError()) { // ignore other than 'no route' errors return; } // get URI stripped of a base URL $request = $event->getRequest(); $uri = str_replace($request->getBaseUrl(), '', $request->getRequestUri()); // try get image ID from URI $id = $this->manager->matchUri($uri); if (!$id) { // abort if URI does not match return; } // try get image from repository $image = $this->repository->find($id); if (!$image) { // abort if image does not exist return; } // store image $this->manager->store($image); // return image in response as a stream $headers = new Headers(); $headers->addHeaders(['Content-Type' => $image->getType(), 'Content-Length' => $image->getLength()]); $response = new Stream(); $response->setStatusCode(Response::STATUS_CODE_200); $response->setStream($image->getResource()); $response->setStreamName($image->getName()); $response->setHeaders($headers); $event->setResponse($response); }
/** * Retrieve Mobile-detect service * * @param \Zend\Http\Headers $oHeaders * * @return \Mobile_Detect */ public function __invoke(\Zend\Http\Headers $oHeaders = null) { if ($oHeaders) { $this->mobileDetect->setHttpHeaders($oHeaders->toArray()); $this->mobileDetect->setUserAgent($oHeaders->get('user-agent')->getFieldValue()); } return $this->mobileDetect; }