public function onRoute(MvcEvent $e) { $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } $application = $e->getApplication(); $serviceLocator = $application->getServiceManager(); // Load the configuration for maintenance mode if ($serviceLocator->has('MaintenanceConfig')) { $config = $serviceLocator->get('MaintenanceConfig'); } else { $config = new Config(); } if (!$config->isEnabled()) { // Maintenance mode is disabled. return; } // Check the white list if ($request instanceof PhpRequest) { $address = $request->getServer('REMOTE_ADDR', null); } else { $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; } if (!empty($address)) { if (in_array($address, $config->getWhitelist())) { return; } } // Render the maintenance layout $renderer = new PhpRenderer(); if ($serviceLocator->has('ViewHelperManager')) { $renderer->setHelperPluginManager($serviceLocator->get('ViewHelperManager')); } $resolver = new TemplateMapResolver(); $resolver->add('maintenance', $config->getTemplate()); $renderer->setResolver($resolver); $content = $renderer->render('maintenance'); // Set the response $response = $e->getResponse(); if (!$response instanceof HttpResponse) { $response = new HttpResponse(); } $statusCode = $config->getStatusCode(); $response->setStatusCode($statusCode); if ($statusCode === 503 && !$response->getHeaders()->has('Retry-After')) { $retryDate = $config->getRetryAfter(); if ($retryDate instanceof DateTime) { $retryAfter = new RetryAfter(); $retryAfter->setDate($retryDate); $response->getHeaders()->addHeader($retryAfter); } } $response->setContent($content); $e->setResponse($response); // Return the response return $response; }
public function vCardAction() { $contact = $this->contactService->find($this->params('id')); if (!$contact) { return $this->notFoundAction(); } $builder = new VCardBuilder(); switch (true) { case $contact instanceof Company: $vcard = $builder->buildCompany($contact); break; case $contact instanceof Person: $vcard = $builder->buildPerson($contact); break; default: throw new RuntimeException('Invalid type provided.'); } $data = $vcard->serialize(); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_200); $response->setContent($data); $headers = $response->getHeaders(); $headers->addHeaderLine('Content-Disposition', 'attachment; filename="' . $contact->getDisplayName() . '.vcf"'); $headers->addHeaderLine('Content-Length', strlen($data)); $headers->addHeaderLine('Content-Type', 'text/plain'); return $response; }
function plugin_preview_action() { global $vars; $page = isset($vars['page']) ? $vars['page'] : ''; $modified = 0; $response = new Response(); if (!empty($page)) { $wiki = Factory::Wiki($page); if ($wiki->isReadable()) { $source = $wiki->get(); array_splice($source, 10); $response->setStatusCode(Response::STATUS_CODE_200); $response->setContent('<' . '?xml version="1.0" encoding="UTF-8"?' . ">\n" . RendererFactory::factory($source)); $headers = Header::getHeaders('text/xml', $wiki->time()); } else { $response->setStatusCode(Response::STATUS_CODE_404); $headers = Header::getHeaders('text/xml'); } } else { $response->setStatusCode(Response::STATUS_CODE_404); $headers = Header::getHeaders('text/xml'); } $response->getHeaders()->addHeaders($headers); header($response->renderStatusLine()); foreach ($response->getHeaders() as $_header) { header($_header->toString()); } echo $response->getBody(); exit; }
public function getXmlAction($isin) { $display = new DisplayHelper(); $certificate = $this->certificateRepository->load($isin); if (empty($certificate)) { return $this->response->setStatusCode(404); } try { $xml = $display->displayAsXml($certificate); } catch (\RuntimeException $e) { return $this->response->setStatusCode(405)->setContent($e->getMessage()); } $this->response->headers()->addHeaderLine('Content-type', 'application/xml'); return $this->response->setContent($xml); }
/** * @expectedException Exception * @expectedExceptionMessage request failed * @excpetedExceptionCode 1 */ public function testSubmitBookmarkHttpError() { $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_403); $this->mockSubmitClient($response); $this->sut->submitBookmark($this->getBookmark()); }
public function onRoute(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); $routeMatchName = $e->getRouteMatch()->getMatchedRouteName(); if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) { return; } $config = $serviceManager->get('Config'); $identityGuards = $config['zource_guard']['identity']; $needsIdentity = null; foreach ($identityGuards as $guard => $needed) { if (fnmatch($guard, $routeMatchName)) { $needsIdentity = $needed; break; } } if ($needsIdentity === null) { throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName)); } if (!$needsIdentity) { return; } $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService'); if ($authenticationService->hasIdentity()) { return; } $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]); $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_302); $response->getHeaders()->addHeaderLine('Location: ' . $url); return $response; }
private function sendHandshakeResponse() { try { $challengeHeader = $this->getHandshakeRequest()->getHeader('Sec-Websocket-Key', null); if (!$challengeHeader) { throw new Exception("No Sec-WebSocket-Key received!"); } // Check for newer handshake $challenge = $challengeHeader->getFieldValue(); // Build response $response = new Response(); $response->setStatusCode(101); $response->setReasonPhrase("WebSocket Protocol Handshake"); $headers = new Headers(); $response->setHeaders($headers); $headers->addHeaderLine("Upgrade", "WebSocket"); $headers->addHeaderLine("Connection", "Upgrade"); $headers->addHeaderLine("Sec-WebSocket-Accept", self::calcHybiResponse($challenge)); $this->setResponse($response); $handshakeRequest = new Handshake($this->getHandshakeRequest(), $this->getHandshakeResponse()); $this->emit("handshake", array($handshakeRequest)); if ($handshakeRequest->isAborted()) { $this->close(); } else { $this->_socket->write($response->toString()); $this->logger->debug("Got an HYBI style request, sent HYBY handshake response"); $this->connected = true; $this->emit("connect"); } } catch (Exception $e) { $this->logger->err("Connection error, message: " . $e->getMessage()); $this->close(); } }
/** * Creates the response to be returned for a QR Code * @param $content * @param $contentType * @return HttpResponse */ protected function createResponse($content, $contentType) { $resp = new HttpResponse(); $resp->setStatusCode(200)->setContent($content); $resp->getHeaders()->addHeaders(array('Content-Length' => strlen($content), 'Content-Type' => $contentType)); return $resp; }
public function getClientFail() { $response = new HttpResponse(); $response->setStatusCode(404); $client = new ClientNotReset(); $client->setResponse($response); return $client; }
public function testConstructorWithHttpResponse() { $httpResponse = new Response(); $httpResponse->setStatusCode(200); $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html'); $response = new CaptchaResponse($httpResponse); $this->assertSame(true, $response->getStatus()); }
/** * @param int $status * @param array $body */ private function rawResponse($status, $body) { $zfResponse = new ZfResponse(); $zfResponse->setStatusCode($status); $reasonPhrase = $zfResponse->getReasonPhrase(); \header('HTTP/1.0 ' . $status . ' ' . $reasonPhrase); \header('Content-Type: application/json'); die(json_encode($body)); }
function it_traps_unauthorized(MvcEvent $event, Response $response, Application $application) { unset($_SERVER['HTTP_X_REQUESTED_WITH']); $event->getTarget()->willReturn($application); $event->setRouteMatch(new RouteMatch(['controller' => 'Controller', 'action' => 'Action']))->shouldBeCalled(); $response->setStatusCode(403)->shouldBeCalled(); $event->getResponse()->willReturn($response); $this->handle($event, AccessService::ACCESS_UNAUTHORIZED)->shouldBe(true); }
/** * @dataProvider exceptionDataProvider */ public function testExceptionsAreThrownOnErrors($statusCode, $expectedException) { $method = new ReflectionMethod('SlmMail\\Service\\MailgunService', 'parseResponse'); $method->setAccessible(true); $response = new HttpResponse(); $response->setStatusCode($statusCode); $this->setExpectedException($expectedException); $method->invoke($this->service, $response); }
public function testConstructorWithMissingStatus() { $params = array('error' => 'error'); $httpResponse = new Response(); $httpResponse->setStatusCode(200); $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html'); $httpResponse->setContent(json_encode($params)); $response = new CaptchaResponse($httpResponse); $this->assertSame(false, $response->getStatus()); }
/** * Creates a new entry * * @param mixed $data * @return Response */ public function create($data) { $sintegra = new Sintegra(); $sintegra->exchangeArray($data); $this->getSintegraTable()->saveSintegra($sintegra); $response = new Response(); $response->setStatusCode(200); $response->setContent(json_encode(array('status' => 'ok'))); return $response; }
/** * @param MvcEvent $e * @return Response */ public function preDispatch(MvcEvent $e) { if (!$e->getRouteMatch()->getParam('module') || $e->getRouteMatch()->getParam('module') !== 'install') { $session = new Container('progress_tracker'); $action = Install::getCurrentStep(); $response = new Response(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', "/install/index/{$action}"); return $response; } }
/** * @param array $params * @return array|Response */ public function fetchAll($params = []) { if (!isset($this->loadedModules['ZF\\Apigility\\Doctrine\\Admin']) || !isset($this->loadedModules['ZF\\Apigility\\Doctrine\\Server'])) { $response = new Response(); $response->setStatusCode(204); return $response; } if (false === ($adapters = $this->model->fetchAll($params))) { return []; } return $adapters; }
/** * Wrap the Jaxon response into an HTTP response. * * @param $code The HTTP Response code * * @return \Zend\Http\Response */ public function httpResponse($code = '200') { // Send HTTP Headers // $this->response->sendHeaders(); // Create and return a ZF2 HTTP response $response = new HttpResponse(); $headers = $response->getHeaders(); $headers->addHeaderLine('Content-Type', $this->response->getContentType() . '; charset=' . $this->response->getCharacterEncoding()); $response->setStatusCode(intval($code)); $response->setContent($this->response->getOutput()); return $response; }
/** * Set HTTP headers to prompt the client for authentication, and return a failed authentication * result. * * @return \Zend\Authentication\Result */ protected function _failureResult() { $oAuthResponse = $this->provider->getOAuthResponse(); if ($this->response) { $this->response->setStatusCode($oAuthResponse->getStatusCode())->getHeaders()->addHeaders($oAuthResponse->getHttpHeaders()); } if ($oAuthResponse->getParameter('error')) { $description = $oAuthResponse->getParameter('error_description'); return new AuthResult(AuthResult::FAILURE_CREDENTIAL_INVALID, null, array($description ?: 'Unable to authenticate token')); } else { return new AuthResult(AuthResult::FAILURE_IDENTITY_AMBIGUOUS, null, array('No access token was presented')); } }
public function testConstructorWithHttpResponse() { $status = 'false'; $errorCode = 'foobar'; $responseBody = $status . "\n" . $errorCode; $httpResponse = new Response(); $httpResponse->setStatusCode(200); $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html'); $httpResponse->setContent($responseBody); $response = new ReCaptcha\Response(null, null, $httpResponse); $this->assertSame(false, $response->getStatus()); $this->assertSame($errorCode, $response->getErrorCode()); }
/** * @param array $params * @return array */ public function fetchAll($params = []) { $modules = $this->getServiceLocator()->get('ModuleManager'); $loaded = $modules->getLoadedModules(false); if (!isset($loaded['ZF\\Apigility\\Doctrine\\Admin']) || !isset($loaded['ZF\\Apigility\\Doctrine\\Server'])) { $response = new Response(); $response->setStatusCode(204); return $response; } if (false === ($adapters = $this->model->fetchAll($params))) { return []; } return $adapters; }
/** * @return JsonModel */ public function create($data = []) { $this->response->setStatusCode(400); $campaign = $this->campaignRepository->getOneBySecurityKey($this->getRequest()->getPost('securityKey')); if (!$campaign) { return $this->sendResult('Campaign not found.'); } $subscriber = $this->subscriberRepository->getOneByEmailAddress($this->getRequest()->getPost('emailAddress')); if (!$subscriber) { $subscriber = $this->subscriberRepository->getNewEntity(); } try { if ($this->manager->handlePost($subscriber, $campaign)) { $this->response->setStatusCode(201); return $this->sendResult(true); } } catch (\Exception $exc) { $this->exceptionLogger->log(0, $exc->getMessage()); $this->response->setStatusCode(500); return $this->sendResult('Unexpected error while saving data'); } return $this->sendResult($this->manager->getForm()->getMessages()); }
/** * Fetch a generated package. * * @param string $fileId * @param string $format * @param \Zend\Http\Response $response * @return \Zend\Http\Response */ private function fetch($fileId, $format, $response) { if (!$fileId || !$format) { $response->setStatusCode(404); return $response; } $package = $this->getPackageFile($fileId, $format); if (!file_exists($package)) { $response->setStatusCode(404); return $response; } $stream = fopen($package, 'r'); if (false === $stream) { $response->setStatusCode(500); return $response; } // Mark the package for deletion when the request spins down. $this->sentPackage = $package; // Create a streamable response. $response = new Stream(); $response->setStream($stream); $response->getHeaders()->addHeaderLine('Content-Type', 'application/octet-stream')->addHeaderLine('Content-Disposition', sprintf('attachment; filename="apigility_%s.%s"', date('Y-m-d_H-i-s'), $format))->addHeaderLine('Content-Length', filesize($package)); return $response; }
public function saveAction(Params $params, Request $request, Response $response, Form $form, Finder $finderService, Update $updateService, Form $form, View $view) { if ($request->getMethod() !== Request::METHOD_PUT) { return $view; } $id = $params('id'); $entity = $finderService->find(['T4webTranslate' => ['Words' => ['Id' => (int) $id]]]); if (!$entity) { $response->setStatusCode(Response::STATUS_CODE_404); $view->setErrors(['message' => 'bad params']); return $view; } $data = Json::decode($request->getContent(), Json::TYPE_ARRAY); $form->setData($data); if (!$form->isValid()) { $response->setStatusCode(Response::STATUS_CODE_404); $view->setErrors($form->getMessages()); return $view; } $entity->populate($data); $result = $updateService->update($id, $entity->extract()); $view->setVariables($result->extract()); return $view; }
/** * Create a preflight response by adding the corresponding headers * * @param HttpRequest $request * @return HttpResponse */ public function createPreflightCorsResponse(HttpRequest $request) { $response = new HttpResponse(); $response->setStatusCode(200); $headers = $response->getHeaders(); $headers->addHeaderLine('Access-Control-Allow-Origin', $this->getAllowedOriginValue($request)); $headers->addHeaderLine('Access-Control-Allow-Methods', implode(', ', $this->options->getAllowedMethods())); $headers->addHeaderLine('Access-Control-Allow-Headers', implode(', ', $this->options->getAllowedHeaders())); $headers->addHeaderLine('Access-Control-Max-Age', $this->options->getMaxAge()); $headers->addHeaderLine('Content-Length', 0); if ($this->options->getAllowedCredentials()) { $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true'); } return $response; }
/** * @param array $params * @param $responseContent * @param $responseContentType * @param $responseStatusCode * @param $format * @param string $exceptionType * @dataProvider providerServiceRequestResponseException */ public function testHttpMethodRequestResponseException(array $params, $responseContent, $responseContentType, $responseStatusCode, $format, $exceptionType = '\\Matryoshka\\Service\\Api\\Exception\\InvalidResponseException') { $httpClient = $this->getMockBuilder('Zend\\Http\\Client')->disableOriginalConstructor()->setMethods(['dispatch', 'getResponse'])->getMock(); $response = new Response(); $response->setContent($responseContent); if ($responseContentType) { $response->getHeaders()->addHeaderLine('Content-Type: ' . $responseContentType); } $response->setStatusCode($responseStatusCode); $httpClient->expects($this->any())->method('dispatch')->will($this->returnValue($response)); $httpClient->expects($this->any())->method('getResponse')->will($this->returnValue($response)); $api = new HttpApi($httpClient); $api->setRequestFormat($format); $this->setExpectedException($exceptionType); $api->dispatchRequest(call_user_func_array([$api, 'prepareRequest'], $params)); }
/** * Get the output with given format, false if nothing: better throw an exception... * * @param array $content * @return \Zend\View\Model\JsonModel|\Zend\Http\Response */ public function setupOutput(array $content) { switch ($this->outputFormat) { case "json": if ($this->getStatusCode() != 200) { $jsonModel = new JsonModel($content); return $jsonModel; } break; case "xml": case "rdf": $response = new Response(); $response->setStatusCode($this->getStatusCode()); $response->getHeaders()->addHeaderLine('Content-Type', 'text/xml; charset=utf-8'); $response->setContent($this->array2xml($content)); return $response; } return false; }
public function doAction() { $token = $this->getHttpRequestVerifier()->verify($this); $this->getHttpRequestVerifier()->invalidate($token); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); try { $gateway->execute(new Refund($token)); } catch (ReplyInterface $reply) { if ($reply instanceof HttpRedirect) { $this->redirect()->toUrl($reply->getUrl()); } if ($reply instanceof HttpResponse) { $this->getResponse()->setContent($reply->getContent()); $response = new Response(); $response->setStatusCode(200); $response->setContent($reply->getContent()); return $response; } throw new \LogicException('Unsupported reply', null, $reply); } $this->redirect()->toUrl($token->getAfterUrl()); }
public function testOnDispatchStatus200() { $resolver = $this->getMock(ResolverInterface::class); $assetManager = $this->getMock(AssetManager::class, array('resolvesToAsset', 'setAssetOnResponse'), array($resolver)); $assetManager->expects($this->once())->method('resolvesToAsset')->will($this->returnValue(true)); $amResponse = new Response(); $amResponse->setContent('bacon'); $assetManager->expects($this->once())->method('setAssetOnResponse')->will($this->returnValue($amResponse)); $serviceManager = $this->getMock(ServiceLocatorInterface::class); $serviceManager->expects($this->any())->method('get')->will($this->returnValue($assetManager)); $application = $this->getMock(ApplicationInterface::class); $application->expects($this->once())->method('getServiceManager')->will($this->returnValue($serviceManager)); $event = new MvcEvent(); $response = new Response(); $request = new Request(); $module = new Module(); $event->setApplication($application); $response->setStatusCode(404); $event->setResponse($response); $event->setRequest($request); $return = $module->onDispatch($event); $this->assertEquals(200, $return->getStatusCode()); }
/** * Listen for specific thrown exceptions and display the proper error page * and code for each. * * @param MvcEvent $e */ public function handleException(MvcEvent $e) { $result = $e->getResult(); // Don't interfere with a complete response. if ($result instanceof ResponseInterface) { return; } // Only handle exceptions. if ($e->getError() !== ZendApplication::ERROR_EXCEPTION) { return; } $exception = $e->getParam('exception'); $this->getServiceLocator()->get('Omeka\\Logger')->err((string) $exception); if ($exception instanceof AclException\PermissionDeniedException) { $template = 'error/403'; $status = 403; } else { if ($exception instanceof ApiException\NotFoundException || $exception instanceof MvcException\NotFoundException) { $template = 'error/404'; $status = 404; } else { return; } } $model = new ViewModel(['exception' => $exception]); $model->setTemplate($template); $response = $e->getResponse(); if (!$response) { $response = new Response(); } $response->setStatusCode($status); $e->setResponse($response); $e->getViewModel()->addChild($model); }