Ejemplo n.º 1
0
 /**
  * Login
  *
  * @param \Zend\Http\Request $request
  * @param \Zend\Http\Response $response
  * @return null|array|\Zend\Http\Response
  */
 public function login(array $options, HttpRequest $request, HttpResponse $response = null)
 {
     if (null === $response) {
         $response = new PhpResponse();
     }
     $session = $this->getSessionContainer();
     $code = $request->getQuery('code');
     if (empty($options['redirect_uri'])) {
         $options['redirect_uri'] = $request->getUri()->getScheme() . '://' . $this->getSiteInfo()->getFulldomain() . $request->getRequestUri();
     }
     if (empty($code)) {
         $session['state'] = String::generateRandom(32);
         $session['redirect_uri'] = $options['redirect_uri'];
         $response->setContent('')->setStatusCode(302)->getHeaders()->clearHeaders()->addHeaderLine('Location', static::DIALOG_URI . '?' . http_build_query(array('client_id' => $options['client_id'], 'redirect_uri' => $options['redirect_uri'], 'state' => $session['state'], 'scope' => 'email')));
         if ($response instanceof PhpResponse) {
             $response->send();
             exit;
         } else {
             return $response;
         }
     }
     $state = $request->getQuery('state');
     if (empty($session['state']) || $state !== $session['state']) {
         return null;
     }
     $client = $this->getHttpClient();
     $params = null;
     @parse_str($client->setMethod('GET')->setUri(static::ACCESS_URI)->setParameterGet(array('client_id' => $options['client_id'], 'redirect_uri' => $session['redirect_uri'], 'client_secret' => $options['client_secret'], 'code' => $code))->send()->getBody(), $params);
     unset($session['state']);
     unset($session['redirect_uri']);
     if (empty($params['access_token'])) {
         return null;
     }
     return @json_decode($client->setMethod('GET')->setUri(static::API_URI)->setParameterGet(array('access_token' => $params['access_token']))->send()->getBody(), true);
 }
Ejemplo n.º 2
0
 public function getResponse()
 {
     $this->serviceManager->get('log')->warn('No concrete RequestHandler found.');
     $response = new ZendResponse();
     $response->setStatusCode(500);
     return $response;
 }
Ejemplo n.º 3
0
 /**
  * Clear authorization Cookie
  *
  * @param string $authDomain
  */
 private function clearCookie(Request $request, Response $response, $authDomain)
 {
     if ($request->getCookie()->offsetExists($authDomain)) {
         $cookie = new SetCookie($authDomain, '', strtotime('-1 Year', time()), '/');
         $response->getHeaders()->addHeader($cookie);
         $response->send();
     }
 }
Ejemplo n.º 4
0
 /**
  * @param Response $response
  *
  * @return Response
  */
 public function getImageResponse(Response $response)
 {
     if (is_file($this->trackingFile)) {
         $imageContent = file_get_contents($this->trackingFile);
         $response->setContent($imageContent);
         $response->getHeaders()->addHeaderLine('Content-Transfer-Encoding', 'binary')->addHeaderLine('Content-Type', 'image/gif')->addHeaderLine('Content-Length', mb_strlen($imageContent));
     }
     return $response;
 }
Ejemplo n.º 5
0
 public function testInvoke()
 {
     $url = 'someUrl';
     $this->routeMatch->expects($this->once())->method('getMatchedRouteName')->will($this->returnValue('someRoute'));
     $headers = $this->getMock('Zend\\Http\\Headers');
     $headers->expects($this->once())->method('addHeaderLine')->with('Location', $url);
     $this->router->expects($this->any())->method('assemble')->with(array(), array('name' => 'zfcuser'))->will($this->returnValue($url));
     $this->response->expects($this->once())->method('getHeaders')->will($this->returnValue($headers));
     $this->response->expects($this->once())->method('setStatusCode')->with(302);
     $result = $this->redirectCallback->__invoke();
     $this->assertSame($this->response, $result);
 }
Ejemplo n.º 6
0
 public function getResponse()
 {
     $doc = new DOMDocument();
     $doc->loadXML('<nodeid>' . $this->context->queryToValue('//id') . '</nodeid>');
     $uiComposer = new \BaseXMS\UiComposer\UiComposer();
     $uiComposer->setServiceLocator($this->getServiceLocator());
     $uiComposer->setContextData($doc);
     $response = new ZendResponse();
     $response->setContent($uiComposer->run()->output());
     $response->setStatusCode(200);
     return $response;
 }
 public function testContentIsLoadedFromCacheAndSetOnResponse()
 {
     $expectedResponse = new HttpResponse();
     $expectedResponse->setContent('mockContent');
     $this->cacheServiceMock->shouldReceive('load')->once()->andReturn('mockContent');
     $this->cacheServiceMock->shouldReceive('save')->never();
     $mvcEvent = $this->createMvcEvent();
     $this->cacheListener->getOptions()->setCacheResponse(false);
     $response = $this->cacheListener->onRoute($mvcEvent);
     $this->assertEquals($expectedResponse->getContent(), $response->getContent());
     $this->cacheListener->onFinish($mvcEvent);
 }
 public function doAction()
 {
     /** @var $rq Request */
     $rq = $this->getRequest();
     $id = $this->params('id');
     $endpoint = $this->params('endpoint');
     $service = $this->getApiService();
     $result = $service->perform($id, $endpoint, $rq->getPost());
     $result = Json::encode($result);
     $response = new Response();
     $response->getHeaders()->addHeaderLine('Content-Type: application/json');
     $response->setContent($result);
     return $response;
 }
Ejemplo n.º 9
0
 /**
  * 
  * {@inheritDoc}
  */
 public function selectSite(Request $request, Response $response)
 {
     if (!$request->isGet()) {
         return false;
     }
     $siteId = $request->getQuery('siteId', self::ENGLISH_SITE_ID);
     $site = $this->siteService->find($siteId);
     if (!$site) {
         $siteId = self::ENGLISH_SITE_ID;
     }
     // Just in case
     $this->siteId = $siteId;
     $cookie = new SetCookie(self::SITE_ID_COOKIE, $siteId, time() + 30 * 24 * 60 * 60);
     // now + 1 month
     $response->getHeaders()->addHeader($cookie);
     return true;
 }
 public function triggerSubscriptionEvent(array $payload)
 {
     $response = new Response();
     if (!array_key_exists('event_type', $payload)) {
         $response->setStatusCode(400)->setContent('Invalid payload.');
         return $response;
     }
     switch ($payload['event_type']) {
         case 'subscription_created':
             $this->getEventManager()->trigger('subscriptionCreated', $this, ['subscription' => $payload['data']['subscription']]);
             break;
         case 'subscription_renewed':
             $this->getEventManager()->trigger('subscriptionRenewed', $this, ['subscription' => $payload['data']['subscription']]);
             break;
         case 'subscription_activation':
             $this->getEventManager()->trigger('subscriptionActivated', $this, ['subscription' => $payload['data']['subscription']]);
             break;
         case 'subscription_expired':
         case 'subscription_cancelled':
             break;
         case 'subscription_upgraded':
         case 'subscription_downgraded':
             $this->getEventManager()->trigger('subscriptionUpdated', $this, ['subscription' => $payload['data']['subscription']]);
             break;
         default:
             $response->setStatusCode(400)->setContent('Invalid event type: ' . $payload['event_type']);
             return $response;
     }
     $response->setStatusCode(200)->setContent('Success.');
     return $response;
 }
Ejemplo n.º 11
0
 /**
  * Запись логов
  * @param Request $request
  * @param Response $response
  */
 public function write($request, $response)
 {
     $serverOptions = $request->getServer()->toArray();
     $requestUri = isset($serverOptions['REQUEST_URI']) ? $serverOptions['REQUEST_URI'] : null;
     // Проверка на запись от правильного запроса
     if (is_null($requestUri) || !preg_match($this->_patternRequestWriteLog, $requestUri)) {
         return;
     }
     $remoteAddr = isset($serverOptions['REMOTE_ADDR']) ? $serverOptions['REMOTE_ADDR'] : '';
     $requestTime = isset($serverOptions['REQUEST_TIME']) ? $serverOptions['REQUEST_TIME'] : 0;
     $requestTimeFloat = isset($serverOptions['REQUEST_TIME_FLOAT']) ? $serverOptions['REQUEST_TIME_FLOAT'] : 0;
     /** @var DocumentManager $dm */
     $dm = $this->getServiceLocator()->get('doctrine-document');
     $logsClient = new LogsClient();
     $logsClient->setDatetime((new \DateTime())->setTimestamp($requestTime))->setHeaders($request->getHeaders()->toString())->setRequest($request->getContent())->setResponse($response->getContent())->setIpAddress($remoteAddr)->setDuration(round(microtime(true), 4) - $requestTimeFloat);
     $dm->persist($logsClient);
     $dm->flush();
 }
Ejemplo n.º 12
0
 /**
  * Metodo privado para obter instacia do Model RelatorioTable
  *
  * @return Select
  */
 public function getSelect($id)
 {
     echo "<script>console.log('PHP: " . json_encode($id) . "');</script>";
     $this->relatorioTable = (array) $this->getRelatorioTable()->getSelect($id);
     //echo json_encode($this->relatorioTable);
     // return vairavel de classe com service RelatorioTable
     //return $this->relatorioTable;
     return Response::json($this->relatorioTable);
 }
Ejemplo n.º 13
0
 /**
  * Test that response has status 302 Redirect and optionally that the 
  * location header is set to a specific URL.
  * 
  * @param string $url
  */
 protected function assertResponseRedirect($url = null)
 {
     $this->assertResponseStatusCode(302, "Failed asserting response status is redirect");
     $this->assertTrue($this->response->isRedirect(), "Failed asserting response is redirect");
     if (null !== $url) {
         $location = $this->response->getHeaders()->get('location')->getFieldValue();
         $this->assertEquals($url, $location, "Failed asserting redirect location '{$location}' is '{$url}'");
     }
 }
Ejemplo n.º 14
0
 public function testResponseDocumentToString()
 {
     $httpHeaders = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nAccept: application/json\r\n\r\n";
     $httpString = "<html>\r\n<body>\r\n    This is a test document\r\n</body>\r\n</html>";
     $zf2Response = \Zend\Http\PhpEnvironment\Response::fromString($httpHeaders . $httpString);
     $response = Response::create($zf2Response, array('DrestCommon\\Response\\Adapter\\ZendFramework2'));
     ob_start();
     ob_get_contents();
     echo $response;
     $actual = ob_get_contents();
     ob_end_clean();
     $this->assertEquals($httpString, $actual);
 }
 public function callbackAction()
 {
     $payload = file_get_contents("php://input");
     $zohoConfig = $this->getServiceLocator()->get('config')['zoho'];
     $accessToken = $this->params()->fromQuery('token');
     if (!array_key_exists('webhook_access_token', $zohoConfig) || $accessToken !== $zohoConfig['webhook_access_token']) {
         $response = new Response();
         $response->setStatusCode(403)->setReasonPhrase('Invalid access token.')->setContent('Invalid access token.');
         return $response;
     }
     if (substr($payload, 0, 8) === 'payload=') {
         $payload = substr($payload, 8);
     }
     $data = Json::decode(urldecode($payload), Json::TYPE_ARRAY);
     /** @var \Zoho\Subscriptions\Service\Webhook\Subscription $serviceWebhook */
     $serviceWebhook = $this->getServiceLocator()->get('Zoho\\Subscriptions\\Service\\Webhook\\Subscription');
     try {
         $response = $serviceWebhook->triggerSubscriptionEvent($data);
     } catch (\Exception $e) {
         $response = new Response();
         $response->setStatusCode(500)->setReasonPhrase('Unexpected server error.')->setContent('Unexpected server error.');
     }
     return $response;
 }
Ejemplo n.º 16
0
 public function testCanExplicitlySetVersion()
 {
     $response = new Response();
     $response->setVersion(Response::VERSION_11);
     $this->assertSame(Response::VERSION_11, $response->getVersion());
     $response->setVersion(Response::VERSION_10);
     $this->assertSame(Response::VERSION_10, $response->getVersion());
     $this->setExpectedException('Zend\\Http\\Exception\\InvalidArgumentException');
     $response->setVersion('zf/2.0');
 }
Ejemplo n.º 17
0
 /**
  * Perform an authentication check on this request
  *  
  * @param MvcEvent $e
  */
 public function checkAuthentication(MvcEvent $e)
 {
     $request = $this->getRequest($e);
     // make sure we have a request object
     $controller_map = $request->getControllerMap();
     // make sure we have a controller map
     $restricted = $controller_map->isRestricted();
     $requires_login = $controller_map->requiresLogin();
     // get user from session
     $user = $request->getUser();
     // this action requires authentication
     if ($restricted || $requires_login) {
         $redirect_to_login = false;
         // this action requires a logged-in user, but user is not logged-in
         if ($requires_login && !$user->isAuthenticated()) {
             $redirect_to_login = true;
         } elseif ($restricted && !$user->isAuthenticated() && !$user->isInLocalIpRange()) {
             $redirect_to_login = true;
         }
         // redirect to login page
         if ($redirect_to_login == true) {
             $params = array('controller' => 'authenticate', 'action' => 'login', 'return' => $this->request->server()->get('REQUEST_URI'));
             $url = $request->url_for($params);
             $response = new HttpResponse();
             $response->headers()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             return $response;
         }
     }
 }
Ejemplo n.º 18
0
 /**
  * @param string $request Request uri
  * @throws \RuntimeException
  * @return \Zend\Http\PhpEnvironment\Response
  */
 public function dispatch($request)
 {
     if (!$this->getResolver()) {
         throw new \RuntimeException("No resolver setted");
     }
     $asset = $this->resolver->resolve($request);
     $content = null;
     $responseCode = 404;
     $headers = Headers::fromString("Content-Type: text/plain");
     if ($asset) {
         $headers = $this->getHeaders($asset->getFile(), $asset->getMime());
         if ($this->browserCached($asset->getFile())) {
             $responseCode = 304;
             $headers->addHeader(Connection::fromString("Connection: close"));
         } else {
             $responseCode = 200;
             $cacheKey = "assets-cache-" . md5($request);
             if ($this->cache) {
                 $content = $this->cache->getItem($cacheKey);
             }
             if (!$content) {
                 $content = $asset->getContent();
                 $assetName = end(explode('\\', get_class($asset)));
                 if (array_key_exists($assetName, $this->filters)) {
                     foreach ($this->filters[$assetName] as $filter) {
                         $content = $filter->filter($content);
                     }
                 }
                 if ($this->cache) {
                     $this->cache->addItem($cacheKey, $content);
                 }
             }
         }
     } else {
         $content = "Asset not found!";
     }
     $response = new Response();
     $response->setStatusCode($responseCode);
     $response->setContent($content);
     $response->setHeaders($headers);
     return $response;
 }
Ejemplo n.º 19
0
 public function checkAuthentication(MvcEvent $e)
 {
     $request = $this->getRequest($e);
     // make sure we have a request object
     $controller_map = $request->getControllerMap();
     // make sure we have a controller map
     $restricted = $controller_map->isRestricted();
     $requires_login = $controller_map->requiresLogin();
     // get user from session
     $user = $request->getUser();
     ##### xerxes 1 transition hack  @todo remove this
     if ($user->isLocal() || $user->isGuest()) {
         foreach ($_COOKIE as $key => $value) {
             if (strstr($key, 'xerxessession')) {
                 if ($user->username != $value) {
                     $username = Parser::removeRight($user->username, '@');
                     $request->setSessionData("username", $username . '@' . $value);
                     $user = $request->getUser();
                 }
                 break;
             }
         }
     }
     ###### end hack
     // this action requires authentication
     if ($restricted || $requires_login) {
         $redirect_to_login = false;
         // this action requires a logged-in user, but user is not logged-in
         if ($requires_login && !$user->isAuthenticated()) {
             $redirect_to_login = true;
         } elseif ($restricted && !$user->isAuthenticated() && !$user->isInLocalIpRange()) {
             $redirect_to_login = true;
         }
         // redirect to login page
         if ($redirect_to_login == true) {
             $params = array('controller' => 'authenticate', 'action' => 'login', 'return' => $this->request->server()->get('REQUEST_URI'));
             $url = $request->url_for($params);
             $response = new HttpResponse();
             $response->headers()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             return $response;
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * @param int $code error code
  */
 public function __invoke($code = 404)
 {
     $this->response->setStatusCode((int) $code);
     $this->layout->setVariables(['message' => '404 Not found', 'reason' => 'The link you have requested doesn\'t exists', 'exception' => '']);
     $this->layout->setTemplate('error/index');
 }
Ejemplo n.º 21
0
 /**
  * @group 2981
  */
 public function testReturnsResponseFromListenerWhenDispatchEventShortCircuits()
 {
     $this->application->bootstrap();
     $testResponse = new Response();
     $response = $this->application->getResponse();
     $events = $this->application->getEventManager();
     $events->clearListeners(MvcEvent::EVENT_ROUTE);
     $events->attach(MvcEvent::EVENT_DISPATCH, function ($e) use($testResponse) {
         $testResponse->setContent('triggered');
         return $testResponse;
     }, 100);
     $self = $this;
     $triggered = false;
     $events->attach(MvcEvent::EVENT_FINISH, function ($e) use($self, $testResponse, &$triggered) {
         $self->assertSame($testResponse, $e->getResponse());
         $triggered = true;
     });
     $this->application->run();
     $this->assertTrue($triggered);
 }
Ejemplo n.º 22
0
 public function testPostDispatchResultIsPassedByReferenceToEventListeners()
 {
     $app = $this->setupActionController();
     $app->events()->attach('dispatch', function ($e) {
         $result = $e->getResult();
         if (!$result) {
             return;
         }
         $result['foo'] = 'bar';
     });
     $app->events()->attach('dispatch', function ($e) {
         $result = $e->getResult();
         if (!$result) {
             return;
         }
         $response = new Response();
         $content = json_encode($result);
         $response->setContent($content);
         return $response;
     });
     $response = $app->run();
     $response = json_decode($response->getContent());
     $this->assertTrue(isset($response->foo), var_export($response, 1));
     $this->assertEquals('bar', $response->foo);
 }
 public function displayDownload($contents, $fileName)
 {
     $response = new Response();
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Disposition: attachment; filename="' . $fileName . '"');
     $headers->addHeaderLine('Content-Type: ' . "application/force-download");
     $headers->addHeaderLine('Content-Length: ' . strlen($contents));
     $response->setContent($contents);
     return $response;
 }
Ejemplo n.º 24
0
 /**
  * Easily bind role with resources
  * @return type
  * Author: Tahmina Khatoon
  */
 public function bindRolesAction()
 {
     $request = $this->getRequest();
     if ($request->isPost()) {
         $confirm = '';
         $formdata = $request->getPost();
         if (!empty($formdata['role_id']) && !empty($formdata['resource_id']) && md5($formdata['role_id'] * $formdata['resource_id']) == $formdata['token']) {
             $existdata = $this->getRoleResourcesTable()->getRoleResourcesByRoleIdAndResourceId($formdata['role_id'], $formdata['resource_id']);
             $resourceDetails = $this->getResourcesTable()->getResources($formdata['resource_id']);
             $resource_name = explode('/', $resourceDetails->name);
             $group = array('index', 'search');
             $formDataAll = array();
             if (empty($resource_name[1]) || in_array($resource_name[1], $group)) {
                 $select = new Select();
                 $where = new \Zend\Db\Sql\Where();
                 $where->in('name', array($resource_name[0], $resource_name[0] . '/index', $resource_name[0] . '/search'));
                 $select->where($where);
                 $main_resources = $this->getResourcesTable()->fetchAll($select);
                 $total = $main_resources->count();
                 if ($total > 0) {
                     foreach ($main_resources as $row) {
                         $role_resources = new RoleResources();
                         $formDataAll[] = array('role_id' => $formdata['role_id'], 'resource_id' => $row->id);
                     }
                 }
             } else {
                 $formDataAll[] = array('role_id' => $formdata['role_id'], 'resource_id' => $formdata['resource_id']);
             }
             if (!empty($formdata['status'])) {
                 foreach ($formDataAll as $data) {
                     $role_resources = new RoleResources();
                     $role_resources->exchangeArray($data);
                     $confirm = $this->getRoleResourcesTable()->saveRoleResources($role_resources);
                 }
             } else {
                 foreach ($formDataAll as $data) {
                     $existdata = $this->getRoleResourcesTable()->getRoleResourcesByRoleIdAndResourceId($data['role_id'], $data['resource_id']);
                     if (!empty($existdata)) {
                         $id = $existdata->id;
                         $confirm = $this->getRoleResourcesTable()->deleteRoleResources($id);
                     }
                 }
             }
         }
         $response = new Response();
         $response->getHeaders()->addHeaderLine('Content-Type: application/json');
         $response->setContent(Json::encode($confirm));
         $response->setStatusCode(200);
         return $response;
     } else {
         $select = new Select();
         $order_by = $this->params()->fromRoute('order_by') ? $this->params()->fromRoute('order_by') : 'name';
         $order = $this->params()->fromRoute('order') ? $this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
         $select->order($order_by . ' ' . $order);
         $resources = $this->getResourcesTable()->fetchAll($select);
         $roles = $this->getRolesTable()->fetchAll();
         $primaryResources = $this->formetArray($this->getResourcesTable()->getPrimaryResources(), 'id');
         $roleResources = array();
         if (!empty($roles)) {
             foreach ($roles as $role) {
                 $roleResources[$role->id] = $this->formetArray($this->getRoleResourcesTable()->getResourcesBasedOnRole($role->id), 'resource_id');
             }
         }
         $this->vm->setVariables(array('resources' => $resources, 'roles' => $roles, 'roleResources' => $roleResources, 'primaryResources' => $primaryResources, 'order_by' => $order_by, 'order' => $order, 'pageAction' => 'resources/bind_roles'));
     }
     return $this->vm;
 }
Ejemplo n.º 25
0
 /**
  * @return array
  */
 public function toArray()
 {
     return ['method' => $this->request->getMethod(), 'uri' => $this->request->getUriString(), 'responseCode' => $this->response->getStatusCode(), 'execution_time' => $this->endTime - $_SERVER['REQUEST_TIME_FLOAT'], 'timers' => $this->timersReport];
 }
Ejemplo n.º 26
0
 /**
  * Asserts that the provided response code matches the one resulting from the most recent dispatch.
  *
  * @param  integer $code    The HTTP response code.
  * @param  string  $message (Optional) The message to output on failure.
  * @return void
  */
 public function assertResponseCode($code, $message = '')
 {
     $actualCode = !empty($this->response) ? $this->response->getStatusCode() : null;
     $this->assertSame($code, $actualCode, $message);
 }
Ejemplo n.º 27
0
 /**
  * Prepare the response with the CSV export and return it
  *
  * @return HttpResponse
  * @throws \Exception if any exceptions are thrown within the content callback
  */
 public function getResponse()
 {
     if (method_exists($this->controller, 'getResponse')) {
         /** @var HttpResponse $response */
         $response = $this->controller->getResponse();
     } else {
         $response = new HttpResponse();
     }
     $fp = fopen('php://output', 'w');
     ob_start();
     fputcsv($fp, $this->header, $this->delimiter, $this->enclosure);
     foreach ($this->content as $i => $item) {
         try {
             $fields = $this->callback ? call_user_func($this->callback, $item) : $item;
             if (!is_array($fields)) {
                 throw new \RuntimeException('CsvExport can only accept arrays, ' . gettype($fields) . ' provided at index ' . $i . '. Either use arrays when setting the records or use a callback to convert each record into an array.');
             }
             fputcsv($fp, $fields, $this->delimiter, $this->enclosure);
         } catch (\Exception $ex) {
             ob_end_clean();
             throw $ex;
         }
     }
     fclose($fp);
     $response->setContent(ob_get_clean());
     $response->getHeaders()->addHeaders(array('Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment;filename="' . str_replace('"', '\\"', $this->name) . '.csv"'));
     return $response;
 }