public function __invoke(Request $req, Response $res, callable $next) { $res = $next($req, $res); $identity = $this->authService->getIdentity(); if (!$identity) { return $res; } try { $user = R::findOne('user', 'mail = ?', [$identity->mail]); if (!$user) { $user = R::dispense('user'); $user->uid = $identity->uid; $user->mail = $identity->mail; $user->display_name = $identity->displayName; $user->office_name = $identity->officeName; $user->authentication_source = $identity->authenticationSource; $user->password = ''; $user->created = time(); $user->role = 'school'; $this->logger->info(sprintf('User %s imported from sso.sch.gr to database', $identity->mail)); } $user->last_login = time(); $user_id = R::store($user); $identityClass = get_class($identity); $newIdentity = new $identityClass($user_id, $user->uid, $user->mail, $user->display_name, $user->office_name, $user->authentication_source); $this->authService->getStorage()->write($newIdentity); } catch (\Exception $e) { $this->authService->clearIdentity(); $this->flash->addMessage('danger', 'A problem occured storing user in database. <a href="%s" title="SSO logout">SSO Logout</a>'); $this->logger->error('Problem inserting user form CAS in database', $identity->toArray()); $this->logger->debug('Exception', [$e->getMessage(), $e->getTraceAsString()]); return $res->withRedirect($this->userErrorRedirectUrl); } return $res; }
/** * logs failed request api call including options and error message * * @param string $scope * @param string $name * @param array $opts * @param string $message * @return boolean */ public function errorLog($scope, $name, $opts, $message) { // stop measure the response time $this->stop(); $this->logger->error(sprintf('failed: %s to %s (%2.4fs), message: %s', Config::getInstance()->http_post ? 'POST' : 'GET', $this->formatUrl($scope, $name, $opts), $this->responseTime, $message)); return true; }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $logRef = uniqid(); $exception = $event->getException(); if ($exception instanceof NotFoundHttpException) { $event->setResponse(new VndErrorResponse("Not found", Response::HTTP_NOT_FOUND)); return; } if ($exception instanceof AuthenticationException) { $event->setResponse(new VndErrorResponse("Unauthorized", Response::HTTP_UNAUTHORIZED)); return; } new VndErrorResponse("Authentication Failure", Response::HTTP_UNAUTHORIZED); $code = $exception->getCode(); if (strlen($code) !== 3) { $this->fallback($message, $code, $logRef, $exception); } else { switch (substr($code, 0, 1)) { case '4': $message = 'Input Error'; $this->logger->notice("Input error [logref {$logRef}]: " . $exception->__toString()); break; case '5': $message = 'Server Error'; $this->logger->error("Runtime error [logref {$logRef}]: " . $exception->__toString()); break; default: $this->fallback($message, $code, $logRef, $exception); } } $event->setResponse(new VndErrorResponse($message, $code, $logRef)); }
public function switchLocaleAction(Request $request) { $this->guard->userIsLoggedIn(); $this->logger->notice('User requested to switch locale'); $returnUrl = $request->query->get('return-url'); // Return URLs generated by us always include a path (ie. at least a forward slash) // @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L878 $domain = $request->getSchemeAndHttpHost() . '/'; if (strpos($returnUrl, $domain) !== 0) { $this->logger->error(sprintf('Illegal return-url ("%s") for redirection after changing locale, aborting request', $returnUrl)); throw new BadRequestHttpException('Invalid return-url given'); } $command = new ChangeLocaleCommand(); $form = $this->formFactory->create('profile_switch_locale', $command, [])->handleRequest($request); $this->logger->notice(sprintf('Switching locale from "%s" to "%s"', $request->getLocale(), $command->newLocale)); if ($form->isValid()) { $this->userService->changeLocale($command); $this->flashBag->add('success', 'profile.locale.locale_change_success'); $this->logger->notice(sprintf('Successfully switched locale from "%s" to "%s"', $request->getLocale(), $command->newLocale)); } else { $this->flashBag->add('error', 'profile.locale.locale_change_fail'); $this->logger->error('Locale not switched: the switch locale form contained invalid data'); } return new RedirectResponse($returnUrl); }
/** * Authenticate a user from shibboleth * * If the user is not yet logged in send a redirect Request * If the user is logged in, but no account exists send an error * If the user is authenticated send a JWT * @param Request $request * * @throws \Exception when the shibboleth attributes do not contain a value for the configured user id attribute * @return JsonResponse */ public function login(Request $request) { $applicationId = $request->server->get('Shib-Application-ID'); if (!$applicationId) { return new JsonResponse(array('status' => 'redirect', 'errors' => [], 'jwt' => null), JsonResponse::HTTP_OK); } $userId = $request->server->get($this->userIdAttribute); if (!$userId) { $msg = "No '{$this->userIdAttribute}' found for authenticated user."; $logVars = []; $shibProperties = ['Shib-Session-ID', 'Shib-Authentication-Instant', 'Shib-Authentication-Method', 'Shib-Session-Index']; foreach ($shibProperties as $key) { $logVars[$key] = $request->server->get($key); } $logVars['HTTP_REFERER'] = $request->server->get('HTTP_REFERER'); $logVars['REMOTE_ADDR'] = $request->server->get('REMOTE_ADDR'); $this->logger->error($msg, ['server variables' => var_export($logVars, true)]); throw new \Exception($msg); } /* @var \Ilios\CoreBundle\Entity\AuthenticationInterface $authEntity */ $authEntity = $this->authManager->findOneBy(array('username' => $userId)); if ($authEntity) { $user = $authEntity->getUser(); if ($user->isEnabled()) { $jwt = $this->jwtManager->createJwtFromUser($user); return $this->createSuccessResponseFromJWT($jwt); } } return new JsonResponse(array('status' => 'noAccountExists', 'userId' => $userId, 'errors' => [], 'jwt' => null), JsonResponse::HTTP_OK); }
/** * Load messages from message directory. */ protected function loadMessages() { if ($this->messages === null) { $this->messages = array(); foreach (glob("{$this->messageDirectory}/*.json") as $file) { $lang = strtolower(substr(basename($file), 0, -5)); if ($lang === 'qqq') { // Ignore message documentation continue; } if (is_readable($file)) { $json = file_get_contents($file); if ($json === false) { $this->logger->error('Error reading file', array('method' => __METHOD__, 'file' => $file)); continue; } $data = json_decode($json, true); if ($data === null) { $this->logger->error('Error parsing json', array('method' => __METHOD__, 'file' => $file, 'json_error' => json_last_error())); continue; } // Discard metadata unset($data['@metadata']); if (empty($data)) { // Ignore empty languages continue; } $this->messages[$lang] = $data; } } } }
/** * @param Message $message */ public function process(Message $message) { // Only process messages where ShareMonkey is mentioned if ($this->shareMonkeyIsMentioned($message->getText()) === false) { return; } $text = $message->getText(); $urls = $text->getUrls(); $tags = $text->getTags(); if (count($urls) === 0) { $this->logger->debug('No urls found in message'); return; } $user = $this->userRepository->findOneBySlackId($message->getUserId()); if (!$user instanceof User) { $this->logger->error(sprintf('User "%s" not found', $message->getUserId()->getValue())); return; } foreach ($urls as $url) { $this->logger->debug(sprintf('processing url %s', $url)); $info = Embed::create($url); $link = Link::fromSlack($message->getId(), $user, $message->getCreatedAt(), $info->getTitle() ?: $message->getText(), $url, $tags); $this->objectManager->persist($link); $this->objectManager->flush(); $this->objectManager->clear(); $this->logger->debug(sprintf('Saved link %s', $link->getUrl())); } }
/** * @param \ErrorException $exception * * @return bool */ protected function handleErrorException(\ErrorException $exception) { switch ($exception->getSeverity()) { case E_ERROR: case E_RECOVERABLE_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: case E_PARSE: $this->logger->error($this->buildLogMessage($exception)); break; case E_WARNING: case E_USER_WARNING: case E_CORE_WARNING: case E_COMPILE_WARNING: $this->logger->warning($this->buildLogMessage($exception)); break; case E_NOTICE: case E_USER_NOTICE: $this->logger->notice($this->buildLogMessage($exception)); break; case E_STRICT: case E_DEPRECATED: case E_USER_DEPRECATED: $this->logger->info($this->buildLogMessage($exception)); break; } return true; }
/** * Run the daemon. * * @return int */ public function run() { $this->logger->info("Status: starting up."); while (true) { $this->taskPersist->begin(); $tasks = $this->tasksFinder->findDueTasks(); foreach ($tasks as $task) { try { $handlerClass = $task->getHandlerClass(); /** @var TaskHandlerInterface $handler */ $handler = new $handlerClass(...$task->getArguments()); $this->decorate($handler); $this->logger->info("Handle {$handlerClass}"); $handler->handle(); if ($task->isReoccurring()) { $task->reoccur(); $this->taskPersist->persist($task); } else { $this->taskPersist->remove($task); } } catch (Exception $e) { $this->logger->error("{$e->getMessage()}\n{$e->getTraceAsString()}"); $task->setDisabled(); $this->taskPersist->persist($task); } } $this->taskPersist->commit(); sleep(1); } }
/** * @param string $email * @param string $message_id * @return string */ public function send($email, $message_id) { $message = $this->saml_data_manager->get($message_id); if (!$message) { if ($this->logger) { $this->logger->error("Saml message with id {$message_id} not found or expired"); } throw new RuntimeException('Authentication message does not exist'); } $this->saml_data_manager->delete($message_id); $response = new Response(); $assertion = new Assertion(); $response->addAssertion($assertion)->setID(Helper::generateID())->setIssueInstant(new DateTime())->setDestination($message->getAssertionConsumerServiceURL())->setIssuer(new Issuer($message->getIssuer()->getValue())); $assertion->setId(Helper::generateID())->setIssueInstant(new DateTime())->setIssuer(new Issuer($message->getIssuer()->getValue()))->setSubject((new Subject())->setNameID(new NameID($email, SamlConstants::NAME_ID_FORMAT_EMAIL))->addSubjectConfirmation((new SubjectConfirmation())->setMethod(SamlConstants::CONFIRMATION_METHOD_BEARER)->setSubjectConfirmationData((new SubjectConfirmationData())->setInResponseTo($message->getID())->setNotOnOrAfter(new DateTime('+1 MINUTE'))->setRecipient($message->getAssertionConsumerServiceURL()))))->setConditions((new Conditions())->setNotBefore(new DateTime())->setNotOnOrAfter(new DateTime('+1 MINUTE'))->addItem(new AudienceRestriction([$message->getAssertionConsumerServiceURL()])))->addItem((new AttributeStatement())->addAttribute(new Attribute(ClaimTypes::EMAIL_ADDRESS, $email)))->addItem((new AuthnStatement())->setAuthnInstant(new DateTime('-10 MINUTE'))->setSessionIndex($message_id)->setAuthnContext((new AuthnContext())->setAuthnContextClassRef(SamlConstants::AUTHN_CONTEXT_PASSWORD_PROTECTED_TRANSPORT))); $certificate = X509Certificate::fromFile($this->saml_crt); $private_key = KeyHelper::createPrivateKey($this->saml_key, '', true); $response->setSignature(new SignatureWriter($certificate, $private_key)); $binding_factory = new BindingFactory(); $post_binding = $binding_factory->create(SamlConstants::BINDING_SAML2_HTTP_POST); $message_context = new MessageContext(); $message_context->setMessage($response); /** @var SymfonyResponse $http_response */ $http_response = $post_binding->send($message_context); return $http_response->getContent(); }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof ExternalApiException) { $this->logger->error($exception->getMessage()); } }
public static function register(LoggerInterface $logger) { register_shutdown_function(function () use($logger) { $errfile = "unknown file"; $errstr = "shutdown"; $errno = E_CORE_ERROR; $errline = 0; $error = error_get_last(); if ($error !== NULL) { $errno = $error["type"]; $errfile = $error["file"]; $errline = $error["line"]; $errstr = $error["message"]; } $message = sprintf('Fatal error: %s at %s line %s', $errstr, $errfile, $errline); $logger->critical($message); }); set_error_handler(function ($errno, $errstr, $errfile, $errline) use($logger) { $message = sprintf('Error: %s at %s line %s', $errstr, $errfile, $errline); $logger->error($message); echo "{$message}\n"; }); set_exception_handler(function (\Exception $e) use($logger) { $message = sprintf('%s: %s (uncaught exception) at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()); $logger->error($message); echo "{$message}\n"; }); }
/** * Error handler * * @param $errno * @param $errstr * @param $errfile * @param $errline */ public function error($errno, $errstr, $errfile, $errline) { $message = $errstr . ' in ' . $errfile . ' on line ' . $errline; if (null !== $this->logger) { switch ($errno) { case E_CORE_ERROR: case E_COMPILE_ERROR: case E_COMPILE_WARNING: $this->logger->emergency($message); break; case E_ERROR: case E_USER_ERROR: case E_PARSE: case E_RECOVERABLE_ERROR: $this->logger->error($message); break; case E_WARNING: case E_USER_WARNING: $this->logger->warning($message); break; case E_NOTICE: case E_USER_NOTICE: $this->logger->notice($message); break; case E_DEPRECATED: case E_USER_DEPRECATED: case E_STRICT: $this->logger->notice($message); break; default: $this->logger->error("Unknown error type: " . $errno . ": " . $message); break; } } }
/** * @param string $request * * @throws \Ndm\JsonRpc2\Client\Exception\TransportException * @throws \Ndm\JsonRpc2\Client\Exception\HttpTransportException * * @return string */ public function send($request) { $defaults = array('method' => 'POST', 'header' => array('Content-Type: application/json', 'Connection: close'), 'content' => $request, 'protocol_version' => 1.0, 'ignore_errors' => true); $options = $this->getContextOptions($defaults); $this->logger->info('Sending Request', array('url' => $this->url, 'context_options' => $options)); // create the context $context = stream_context_create($options); // connect and open the stream $stream = fopen($this->url, 'r', false, $context); // get the response headers etc. $headers = stream_get_meta_data($stream); // actual data at $url $content = stream_get_contents($stream); fclose($stream); $this->logger->info('Received Reply', array('headers' => $headers, 'content' => $content)); if (!isset($headers['wrapper_data'])) { throw new Exception\TransportException("Failed to connect to URL {$this->url}"); } // check the status code of the response list($successful, $statusCode, $statusMessage) = $this->checkStatus($headers['wrapper_data']); if (!$successful) { $this->logger->error('Request was not successful', array('url' => $this->url, 'context_options' => $options, 'headers' => $headers, 'content' => $content)); throw new Exception\HttpTransportException($statusCode, $statusMessage, $content); } return $content; }
/** * @param Job $syncJob Laravel queue job * @param $arguments * @return bool * @throws \Unifact\Connector\Exceptions\HandlerException */ public function fire(Job $syncJob, $arguments) { try { $job = $this->jobRepo->findById($arguments['job_id']); $job->setPreviousStatus($arguments['previous_status']); $handler = forward_static_call([$job->handler, 'make']); $this->logger->debug("Preparing Job.."); if (!$handler->prepare()) { $this->logger->error('Handler returned FALSE in prepare() method, see log for details'); // delete Laravel queue job $syncJob->delete(); return false; } $this->logger->debug("Handling Job.."); if ($handler->handle($job) === false) { $this->logger->error('Handler returned FALSE in handle() method, see log for details'); // delete Laravel queue job $syncJob->delete(); return false; } $this->logger->debug("Completing Job.."); $handler->complete(); $this->logger->info('Finished Job successfully'); } catch (\Exception $e) { $this->oracle->exception($e); $this->logger->error('Exception was thrown in JobQueueHandler::fire method.'); $this->jobRepo->update($arguments['job_id'], ['status' => 'error']); // delete Laravel queue job $syncJob->delete(); return false; } // delete Laravel queue job $syncJob->delete(); return true; }
public function sendSms(SendSmsCommand $command) { $this->logger->info('Requesting Gateway to send SMS'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'message' => ['originator' => $command->originator, 'recipient' => $command->recipient, 'body' => $command->body]]; $response = $this->guzzleClient->post('api/send-sms', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $this->logger->error(sprintf('SMS sending failed, error: [%s] %s', $response->getStatusCode(), $response->getReasonPhrase()), ['http-body' => $response->getBody() ? $response->getBody()->getContents() : '']); return false; } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('SMS sending failed; server responded with malformed JSON.'); return false; } if (!isset($result['status'])) { $this->logger->error('SMS sending failed; server responded without status report.'); return false; } if ($result['status'] !== 'OK') { $this->logger->error('SMS sending failed; server responded with non-OK status report.'); return false; } return true; }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); $code = $exception->getCode(); $debug = array('class' => get_class($exception), 'code' => $code, 'message' => $exception->getMessage()); $this->logger->error(print_r($debug, true)); // HttpExceptionInterface est un type d'exception spécial qui // contient le code statut et les détails de l'entête if ($exception instanceof NotFoundHttpException) { $data = array('error' => array('code' => $code ? $code : -3, 'message' => $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); $response->headers->set('Content-Type', 'application/json'); } elseif ($exception instanceof HttpExceptionInterface) { $data = array('error' => array('code' => $code ? $code : -2, 'message' => $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode($exception->getStatusCode()); $response->headers->replace($exception->getHeaders()); $response->headers->set('Content-Type', 'application/json'); } else { $data = array('error' => array('code' => $code ? $code : -1, 'message' => 'Internal Server Error / ' . $exception->getMessage())); $response = new JsonResponse($data); $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } // envoie notre objet réponse modifié à l'évènement $event->setResponse($response); }
/** * @param ConsoleExceptionEvent $event * * @return void */ public function onConsoleException(ConsoleExceptionEvent $event) { $command = $event->getCommand(); $exception = $event->getException(); $message = sprintf('%s: %s (uncaught exception) at %s line %s while running console command `%s`', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine(), $command->getName()); $this->logger->error($message); }
/** * {@inheritdoc} */ public function log($message, $level) { $message .= ' ' . $this->request->getRequestUri(); if ($this->logLevel >= $level) { switch ($level) { case self::EMERGENCY: $this->logger->emergency($message); break; case self::ALERT: $this->logger->alert($message); break; case self::CRITICAL: $this->logger->critical($message); break; case self::ERROR: $this->logger->error($message); break; case self::WARNING: $this->logger->warning($message); break; case self::NOTICE: $this->logger->notice($message); break; case self::INFO: $this->logger->info($message); break; default: $this->logger->debug($message); } } }
/** * {@inheritdoc} */ public function handle(ServerRequestInterface $request, $exception) { if ($exception instanceof HttpException) { if ($this->logger) { $this->logger->notice($this->prettifyRequest($request)); $this->logger->notice($exception); } return $exception; } if ($this->config->get('debug', true)) { $whoops = $this->getWhoops($request); return create($whoops->handleException($exception), 500); } $statusCode = 500; $reasonPhrase = 'Internal Server Error'; if ($exception instanceof RouteNotFoundException) { $statusCode = 404; $reasonPhrase = "Not Found"; } elseif ($exception instanceof RouteMethodException) { $statusCode = 405; $reasonPhrase = 'Method Not Allowed'; } if ($this->logger) { $this->logger->error($this->prettifyRequest($request)); $this->logger->error($exception); } if ($this->isAjax($request)) { return json(['status' => $statusCode, 'reason' => $reasonPhrase], $statusCode); } return create("{$statusCode} {$reasonPhrase}", $statusCode); }
public function onKernelController(FilterControllerEvent $event) { if (!$this->isTrackingEnabled) { return; } $controller = $event->getController(); /* * $controller passed can be either a class or a Closure. * This is not usual in Symfony but it may happen. * If it is a class, it comes in array format * @link http://symfony.com/doc/current/event_dispatcher/before_after_filters.html#creating-an-event-listener */ if (!is_array($controller)) { return; } $controller = $controller[0]; if ($controller instanceof Controller) { $request = $event->getRequest(); $path = $request->getRequestUri(); $host = $request->getHost(); $title = get_class($controller); $data = ['dh' => $host, 'dp' => $path, 'dt' => $title]; try { $this->tracker->send($data, 'pageview'); } catch (\Exception $e) { $this->logger->error('Failed to send tracking data.', ['exception' => $e]); } } }
/** * Notifies the task manager given a message constant, see MESSAGE_* constants. * * @param string $message * * @return mixed|null The return value of the task manager. * * @throws RuntimeException in case notification did not occur within the timeout. */ public function notify($message) { try { $command = $this->createCommand($message); $this->socket->send($command); $result = false; $limit = microtime(true) + $this->timeout; while (microtime(true) < $limit && false === ($result = $this->socket->recv(\ZMQ::MODE_NOBLOCK))) { usleep(1000); } if (false === $result) { $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout)); throw new RuntimeException('Unable to retrieve information.'); } $data = @json_decode($result, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException('Invalid task manager response : invalid JSON.'); } if (!isset($data['reply']) || !isset($data['request']) || $command !== $data['request']) { throw new RuntimeException('Invalid task manager response : missing fields.'); } return $data['reply']; } catch (\ZMQSocketException $e) { $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout), ['exception' => $e]); throw new RuntimeException('Unable to retrieve information.', $e->getCode(), $e); } }
/** * @param VerifyYubikeyOtpCommand $command * @return YubikeyVerificationResult */ public function verify(VerifyYubikeyOtpCommand $command) { $this->logger->info('Verifying Yubikey OTP'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'otp' => ['value' => $command->otp]]; $response = $this->guzzleClient->post('api/verify-yubikey', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $type = $statusCode >= 400 && $statusCode < 500 ? 'client' : 'server'; $this->logger->info(sprintf('Yubikey OTP verification failed; %s error', $type)); return new YubikeyVerificationResult(true, false); } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('Yubikey OTP verification failed; server responded with malformed JSON.'); return new YubikeyVerificationResult(false, true); } if (!isset($result['status'])) { $this->logger->error('Yubikey OTP verification failed; server responded without status report.'); return new YubikeyVerificationResult(false, true); } if ($result['status'] !== 'OK') { $this->logger->error('Yubikey OTP verification failed; server responded with non-OK status report.'); return new YubikeyVerificationResult(false, true); } return new YubikeyVerificationResult(false, false); }
/** * Start the backup. * * @return bool */ public function execute() { $successful = true; try { // Dump all databases $this->dbm->dump(); // Backup folders if specified $this->logger->info('[dizda-backup] Copying folders.'); $this->processor->copyFolders(); // Compress everything $this->logger->info(sprintf('[dizda-backup] Compressing to archive using %s', $this->processor->getName())); $this->processor->compress(); // Transfer with all clients $this->cm->upload($this->processor->getArchivePath()); } catch (\Exception $e) { // Write log $this->logger->critical('[dizda-backup] Unexpected exception.', array('exception' => $e)); $successful = false; } try { // If we catch an exception or not, we would still like to try cleaning up after us $this->logger->info('[dizda-backup] Cleaning up after us.'); $this->processor->cleanUp(); } catch (IOException $e) { $this->logger->error('[dizda-backup] Cleaning up failed.'); return false; } return $successful; }
/** * Request the page from IMDb * @param $url * @return string Page html. Empty string on failure * @throws Exception\Http */ protected function requestPage($url) { $this->logger->info("[Page] Requesting [{$url}]"); $req = $this->buildRequest($url); if (!$req->sendRequest()) { $this->logger->error("[Page] Failed to connect to server when requesting url [{$url}]"); if ($this->config->throwHttpExceptions) { throw new Exception\Http("Failed to connect to server when requesting url [{$url}]"); } else { return ''; } } if (200 == $req->getStatus()) { return $req->getResponseBody(); } elseif ($redirectUrl = $req->getRedirect()) { $this->logger->debug("[Page] Following redirect from [{$url}] to [{$redirectUrl}]"); return $this->requestPage($redirectUrl); } else { $this->logger->error("[Page] Failed to retrieve url [{url}]. Response headers:{headers}", array('url' => $url, 'headers' => $req->getLastResponseHeaders())); if ($this->config->throwHttpExceptions) { $exception = new Exception\Http("Failed to retrieve url [{$url}]. Status code [{$req->getStatus()}]"); $exception->HTTPStatusCode = $req->getStatus(); throw new $exception(); } else { return ''; } } }
/** * Report or log an exception. * * @param \Exception $e * @return void */ public function report(Exception $e) { if ($this->shouldntReport($e)) { return; } $this->log->error((string) $e); }
/** * Detects if there is a custom controller to use to render a Block. * * @param FilterControllerEvent $event * * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException */ public function getController(FilterControllerEvent $event) { $request = $event->getRequest(); // Only taking page related controller (i.e. ez_page:viewBlock or ez_page:viewBlockById) if (strpos($request->attributes->get('_controller'), 'ez_page:') === false) { return; } try { if ($request->attributes->has('id')) { $valueObject = $this->pageService->loadBlock($request->attributes->get('id')); $request->attributes->set('block', $valueObject); } elseif ($request->attributes->get('block') instanceof Block) { $valueObject = $request->attributes->get('block'); $request->attributes->set('id', $valueObject->id); } } catch (UnauthorizedException $e) { throw new AccessDeniedException(); } if (!isset($valueObject)) { $this->logger->error('Could not resolve a page controller, invalid value object to match.'); return; } $controllerReference = $this->controllerManager->getControllerReference($valueObject, 'block'); if (!$controllerReference instanceof ControllerReference) { return; } $request->attributes->set('_controller', $controllerReference->controller); $event->setController($this->controllerResolver->getController($request)); }
/** * @param $jobs * @throws UnauthorizedCommandException */ protected function runJobs($jobs) { foreach ($jobs as $job) { /** * @var \WeavingTheWeb\Bundle\ApiBundle\Entity\Job $job */ $command = $job->getValue(); try { $this->validateCommand($command); $job->setStatus(JobInterface::STATUS_STARTED); $this->updateJob($job); $command = $this->getApplication()->get($command); $success = $command->run(new ArrayInput(['command' => $command, '--job' => $job->getId()]), $this->output); if (intval($success) === 0) { $job->setStatus(JobInterface::STATUS_FINISHED); } else { $job->setStatus(JobInterface::STATUS_FAILED); } $this->updateJob($job); } catch (UnauthorizedCommandException $exception) { $message = $this->translator->trans('job.run.unauthorized', ['{{ command }}' => $command], 'job'); $this->logger->error($exception->getMessage()); $this->output->writeln($message); $job->setStatus(JobInterface::STATUS_FAILED); $this->updateJob($job); continue; } catch (\Exception $exception) { $this->logger->error($exception->getMessage()); continue; } } }
/** * Log fatal error to Mautic's logs and throw exception for the parent generic error page to catch * * @throws \Exception */ public function handleFatal() { $error = error_get_last(); if ($error !== null) { $name = $this->getErrorName($error['type']); $this->logger->error("{$name}: {$error['message']} - in file {$error['file']} - at line {$error['line']}"); if ($error['type'] === E_ERROR || $error['type'] === E_CORE_ERROR || $error['type'] === E_USER_ERROR) { defined('MAUTIC_OFFLINE') or define('MAUTIC_OFFLINE', 1); if (MAUTIC_ENV == 'dev') { $message = "<pre>{$error['message']} - in file {$error['file']} - at line {$error['line']}</pre>"; // Get a trace ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $trace = ob_get_contents(); ob_end_clean(); // Remove first item from backtrace as it's this function which // is redundant. $trace = preg_replace('/^#0\\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1); // Renumber backtrace items. $trace = preg_replace('/^#(\\d+)/me', '\'#\' . ($1 - 1)', $trace); $submessage = "<pre>{$trace}</pre>"; } else { $message = 'The site is currently offline due to encountering an error. If the problem persists, please contact the system administrator.'; $submessage = 'System administrators, check server logs for errors.'; } include __DIR__ . '/../../../../offline.php'; } } }
/** * Detects if there is a custom controller to use to render a Location/Content. * * @param FilterControllerEvent $event * * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException */ public function getController(FilterControllerEvent $event) { $request = $event->getRequest(); // Only taking content related controller (i.e. ez_content:viewLocation or ez_content:viewContent) if (strpos($request->attributes->get('_controller'), 'ez_content:') === false) { return; } try { if ($request->attributes->has('locationId')) { $valueObject = $this->repository->getLocationService()->loadLocation($request->attributes->get('locationId')); } elseif ($request->attributes->get('location') instanceof Location) { $valueObject = $request->attributes->get('location'); $request->attributes->set('locationId', $valueObject->id); } elseif ($request->attributes->has('contentId')) { $valueObject = $this->repository->sudo(function (Repository $repository) use($request) { return $repository->getContentService()->loadContentInfo($request->attributes->get('contentId')); }); } elseif ($request->attributes->get('contentInfo') instanceof ContentInfo) { $valueObject = $request->attributes->get('contentInfo'); $request->attributes->set('contentId', $valueObject->id); } } catch (UnauthorizedException $e) { throw new AccessDeniedException(); } if (!isset($valueObject)) { $this->logger->error('Could not resolver a view controller, invalid value object to match.'); return; } $controllerReference = $this->controllerManager->getControllerReference($valueObject, $request->attributes->get('viewType')); if (!$controllerReference instanceof ControllerReference) { return; } $request->attributes->set('_controller', $controllerReference->controller); $event->setController($this->controllerResolver->getController($request)); }