/** * Assigns the currently logged in user to a Comment. * * @param \FOS\CommentBundle\Event\CommentEvent $event * @return void */ public function blame(CommentEvent $event) { $comment = $event->getComment(); if (null === $this->securityContext) { if ($this->logger) { $this->logger->debug("Comment Blamer did not receive the security.context service."); } return; } if (!$comment instanceof SignedCommentInterface) { if ($this->logger) { $this->logger->debug("Comment does not implement SignedCommentInterface, skipping"); } return; } if (null === $this->securityContext->getToken()) { if ($this->logger) { $this->logger->debug("There is no firewall configured. We cant get a user."); } return; } if (null === $comment->getAuthor() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $comment->setAuthor($this->securityContext->getToken()->getUser()); } }
public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/'; if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) { // Deny authentication with a '403 Forbidden' HTTP response $response = new Response(); $response->setStatusCode(403); $event->setResponse($response); return; } $token = new WsseUserToken(); $token->setUser($matches[1]); $token->digest = $matches[2]; $token->nonce = $matches[3]; $token->created = $matches[4]; try { $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); return; } catch (AuthenticationException $failed) { // ... you might log something here $failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '. Why ? ' . $failed->getMessage(); $this->logger->err($failedMessage); //To deny the authentication clear the token. This will redirect to the login page. //Make sure to only clear your token, not those of other authentication listeners. $this->securityContext->setToken(null); // Deny authentication with a '403 Forbidden' HTTP response $response = new Response(); $response->setStatusCode(403); $response->setContent($failedMessage); $event->setResponse($response); return; } }
/** * Cache an array of resources into the given cache * @param array $resources * @return void */ public function cacheResources(array $resources) { $cache = new ConfigCache($this->getCacheFileLocation(), $this->debug); $content = sprintf('<?php return %s;', var_export($resources, true)); $cache->write($content); $this->logger->debug('Writing translation resources to cache file.'); }
/** * @param string $action * @return object */ private function findControllerWithAction($action) { $this->logger->debug('Trying method "' . $action . '"'); if (method_exists($this->getControllerObject(), $action)) { return array($this->getControllerObject(), $action); } return null; }
public function spamCheck(CommentPersistEvent $event) { $comment = $event->getComment(); if ($this->spamDetector->isSpam($comment)) { if (null !== $this->logger) { $this->logger->info('Comment is marked as spam from detector, aborting persistence.'); } $event->abortPersistence(); } }
/** * @param mixed $level * @param string $message * @param array $context * @return null * @throws PsrInvalidArgumentException */ public function log($level, $message, array $context = array()) { switch ($level) { case PsrLogLevel::ALERT: $this->symfonyLogger->alert($message, $context); break; case PsrLogLevel::CRITICAL: $this->symfonyLogger->crit($message, $context); break; case PsrLogLevel::DEBUG: $this->symfonyLogger->debug($message, $context); break; case PsrLogLevel::EMERGENCY: $this->symfonyLogger->emerg($message, $context); break; case PsrLogLevel::ERROR: $this->symfonyLogger->err($message, $context); break; case PsrLogLevel::INFO: $this->symfonyLogger->info($message, $context); break; case PsrLogLevel::NOTICE: $this->symfonyLogger->notice($message, $context); break; case PsrLogLevel::WARNING: $this->symfonyLogger->warn($message, $context); break; default: throw new PsrInvalidArgumentException(sprintf('Loglevel "%s" not valid, use constants from "%s"', $level, "Psr\\Log\\LogLevel")); break; } return null; }
public function onAuthenticationSuccess(Request $request, TokenInterface $token) { $this->logger->debug('After login'); $path = $this->defaultPath; if ($request->getSession()->has('order')) { $this->logger->debug('Order to authenticate'); $request->getSession()->get('order')->authenticateWith($token->getUser()); $path = $this->orderNextStepRoute; } $this->logger->debug("Redirect to {$path}"); return $this->httpUtils->createRedirectResponse($request, $path); }
/** * Log a resource unsubscription attempt. * @param boolean $successful Whether the attempt succeeded. * @param array $url The resource URLs. */ public function logUnsubscribeAttempt($successful, array $urls) { // Write the actual logs foreach ($urls as $url) { if ($successful) { $this->logger->info(sprintf('Unsubscribed from resource "%s"', $url)); } else { $this->logger->warn(sprintf('Unsuccessful unsubscription attempt from resource "%s"', $url)); } } // Store the data directly $this->unsubscribeAttempts[] = new UnsubscribeAttempt($successful, $urls); }
/** * Returns true if Akismet believes the data is a spam * * @param array data only the model data. The request data is added automatically. * Exemple: * array( * 'comment_author' => 'Jack', * 'comment_content' => 'The moon core is made of cheese' * ) * * @return bool true if it is spam */ public function isSpam(array $data) { $fullData = array_merge($this->getRequestData(), $data); if ($this->throwExceptions) { return $this->adapter->isSpam($fullData); } try { return $this->adapter->isSpam($fullData); } catch (\Exception $e) { if ($this->logger) { $this->logger->warn(sprintf('%s: %s(%s)', get_class($this), get_class($e), $e->getMessage())); } return false; } }
/** * @param GetResponseEvent $event * * @return GetResponseEvent */ public function onKernelRequest(GetResponseEvent $event) { try { $this->routerListener->onKernelRequest($event); } catch (NotFoundHttpException $e) { if (null !== $this->logger) { $this->logger->info('Request handled by the ' . $this->legacyKernel->getName() . ' kernel.'); } $response = $this->legacyKernel->handle($event->getRequest(), $event->getRequestType(), true); if ($response->getStatusCode() !== 404) { $event->setResponse($response); return $event; } } }
/** * @param string $value value to geocode * @param float $duration geocoding duration * @param string $providerClass Geocoder provider class name * @param \SplObjectStorage|Geocoded $results */ public function logRequest($value, $duration, $providerClass, $results) { if (null !== $this->logger) { $this->logger->info(sprintf("%s %0.2f ms (%s)", $value, $duration, $providerClass)); } $data = array(); if ($results instanceof \SplObjectStorage) { $data = array(); foreach ($results as $result) { $data[] = $result->toArray(); } } else { $data = $results->toArray(); } $this->requests[] = array('value' => $value, 'duration' => $duration, 'providerClass' => $providerClass, 'result' => json_encode($data)); }
/** * Saves a Profile. * * @param Profile $profile A Profile instance * * @return Boolean */ public function saveProfile(Profile $profile) { if (!($ret = $this->storage->write($profile)) && null !== $this->logger) { $this->logger->warn('Unable to store the profiler information.'); } return $ret; }
/** * A convenience function for logging a debug event. * * @param mixed $message the message to log. */ public function debug($message) { $this->queries[] = $message; if (null !== $this->logger) { $this->logger->debug($message); } }
/** * @param bool $isFolder = true * @param GoogleDriveListParameters $optParams * @param string $parentFolderId * @param string $filter * * @link https://developers.google.com/drive/web/search-parameters * * @throws HttpException * * @return \Google_Service_Drive_FileList */ public function getFiles($isFolder = true, GoogleDriveListParameters $optParams = null, $parentFolderId = "", $filter = null) { $result = array(); $optParams = empty($optParams) ? new GoogleDriveListParameters() : $optParams; if (0 < strlen($optParams->getQuery())) { $optParams->setQuery(sprintf("%s and (%s)", GoogleDriveListParameters::NO_TRASH, $optParams->getQuery())); } else { $optParams->setQuery(GoogleDriveListParameters::NO_TRASH, $optParams->getQuery()); } // Filters $filters = array(); $filters['type'] = !is_null($filter) ? $this->buildTypeFilter($filter) : null; if (empty($filters['type'])) { $filters['type'] = $isFolder ? GoogleDriveListParameters::FOLDERS : GoogleDriveListParameters::NO_FOLDERS; } if (!empty($parentFolderId)) { $filters['parentFolder'] = sprintf('"%s" in parents', $parentFolderId); } foreach ($filters as $filter) { $optParams->setQuery(sprintf("%s and (%s)", $optParams->getQuery(), $filter)); } $this->container->get('monolog.logger.queries')->info($optParams->getJson()); try { $files = $this->service->files->listFiles($optParams->getArray()); $result['query'] = $optParams->getQuery(); $result['nextPageToken'] = $files->getNextPageToken(); $result['result'] = $files; } catch (\Exception $ge) { $errorMessage = sprintf("%s.\n%s.", $this->translator->trans('Google Drive cannot authenticate our [email / .p12 key file]'), $this->translator->trans('Please check the parameters.yml file')); $this->logger->error($errorMessage); throw new HttpException(500, $errorMessage, $ge); } return $result; }
/** * @param string $calledMethod * @param ConnectionInterface $conn * @param Topic $topic * @param null $payload * @param null $exclude * @param null $eligible * * @return bool */ public function dispatch($calledMethod, ConnectionInterface $conn, Topic $topic, WampRequest $request, $payload = null, $exclude = null, $eligible = null) { $dispatched = false; foreach ((array) $request->getRoute()->getCallback() as $callback) { $appTopic = $this->topicRegistry->getTopic($callback); if ($topic) { if ($appTopic instanceof TopicPeriodicTimerInterface) { $appTopic->setPeriodicTimer($this->topicPeriodicTimer); if (false === $this->topicPeriodicTimer->isRegistered($appTopic) && 0 !== count($topic)) { $appTopic->registerPeriodicTimer($topic); } } if ($calledMethod === static::UNSUBSCRIPTION && 0 === count($topic)) { $this->topicPeriodicTimer->clearPeriodicTimer($appTopic); } try { if ($payload) { //its a publish call. $appTopic->{$calledMethod}($conn, $topic, $request, $payload, $exclude, $eligible); } else { $appTopic->{$calledMethod}($conn, $topic, $request); } } catch (\Exception $e) { $this->logger->error($e->getMessage(), ['code' => $e->getCode(), 'file' => $e->getFile(), 'trace' => $e->getTraceAsString()]); $conn->callError($topic->getId(), $topic, $e->getMessage(), ['topic' => $topic, 'request' => $request, 'event' => $calledMethod]); return; } $dispatched = true; } } return $dispatched; }
/** * @throws \ErrorException When error_reporting returns error */ public function handle($level, $message, $file, $line, $context) { if (0 === $this->level) { return false; } if ($level & (E_USER_DEPRECATED | E_DEPRECATED)) { if (null !== self::$logger) { $deprecation = array('type' => self::TYPE_DEPRECATION, 'file' => $file, 'line' => $line, 'stack' => version_compare(PHP_VERSION, '5.4', '<') ? array_slice(debug_backtrace(false), 0, 10) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10)); self::$logger->warn($message, $deprecation); } return true; } if (error_reporting() & $level && $this->level & $level) { throw new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line), 0, $level, $file, $line); } return false; }
public function getHDMovieNotViewed($channel, $codec, $order = 'create', $sens = 'DESC') { $qb = $this->queryHDMovies(); $qb->andWhere($qb->expr()->notIn('mov.mapper', $this->queryNotViewed()->getDQL())); $this->queryAudio($qb, $channel, $codec); $this->logger->debug('VALUE field in HDNotView : ' . $order); $this->queryOrderField($qb, $order, $sens); return $qb->getQuery()->getResult(); }
/** * Assigns the currently logged in user to a Comment. * * @param \FOS\CommentBundle\Event\CommentEvent $event */ public function blame(CommentEvent $event) { $comment = $event->getComment(); if (!$comment instanceof SignedCommentInterface) { if ($this->logger) { $this->logger->debug("Comment does not implement SignedCommentInterface, skipping"); } return; } if (null === $this->tokenStorage->getToken()) { if ($this->logger) { $this->logger->debug("There is no firewall configured. We cant get a user."); } return; } if (null === $comment->getAuthor() && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $comment->setAuthor($this->tokenStorage->getToken()->getUser()); } }
public function onResponse(Event $event) { $response = $event->getResponse(); /* @var $response \Symfony\Component\HttpFoundation\Response */ $session = $event->getRequest()->getSession(); /* @var $session \Symfony\Component\HttpFoundation\Session */ $response->headers->setCookie(new Cookie('locale', $session->get('localeIdentified'))); if (null !== $this->logger) { $this->logger->info(sprintf('Locale Cookie set to: [ %s ]', $session->get('localeIdentified'))); } }
public function addDcIfNotExist($dn, $name) { if (!$this->ldap->isEntityExist($dn)) { $data = array(); $data['dc'] = $name; $data['o'] = $name; $data['objectclass'] = array('top', 'organization', 'dcObject'); $this->ldap->add($dn, $data); $this->logger->info("Created Dc:'" . $dn . "''"); } }
/** * Executes the block as specified in the content. * * @param array $block An array including the block name * * @return string the rendered block */ protected function embeddedRender($block) { try { return $this->sonataBlock->render(array('name' => trim($block[1]))); } catch (\Exception $e) { if ($this->logger) { $this->logger->warn('Failed to render block "' . $block[1] . '" embedded in content: ' . $e->getTraceAsString()); } } return ''; }
/** * {@inheritDoc} */ public function execute(AMQPMessage $msg) { if ($this->logger) { $this->logger->info('[GithubHookConsumer] Received a github post push hook'); } if (null === ($message = json_decode($msg->body))) { if ($this->logger) { $this->logger->err('[GithubHookConsumer] Unable to decode payload'); } return; } $payload = $message->payload; $bundle = $this->manager->getRepository('KnpBundlesBundle:Bundle')->findOneBy(array('name' => $payload->repository->name, 'ownerName' => $payload->repository->owner->name)); if (!$bundle) { if ($this->logger) { $this->logger->warn(sprintf('[GithubHookConsumer] unknown bundle %s/%s', $payload->repository->name, $payload->repository->owner->name)); } return; } $this->producer->publish(serialize(array('bundle_id' => $bundle->getId()))); }
/** * {@inheritDoc} */ public function store(Response $response, $targetPath, $filter) { $storageResponse = $this->storage->create_object($this->bucket, $targetPath, array('body' => $response->getContent(), 'contentType' => $response->headers->get('Content-Type'), 'length' => strlen($response->getContent()), 'acl' => $this->acl)); if ($storageResponse->isOK()) { $response->setStatusCode(301); $response->headers->set('Location', $this->getObjectUrl($targetPath)); } else { if ($this->logger) { $this->logger->warn('The object could not be created on Amazon S3.', array('targetPath' => $targetPath, 'filter' => $filter, 's3_response' => $storageResponse)); } } return $response; }
/** * Loops through all registered routers and returns a router if one is found. * It will always return the first route generated. * * @param string $name * @param array $parameters * @param Boolean $absolute * @throws RouteNotFoundException * @return string */ public function generate($name, $parameters = array(), $absolute = false) { foreach ($this->all() as $router) { try { return $router->generate($name, $parameters, $absolute); } catch (RouteNotFoundException $e) { if ($this->logger) { $this->logger->info($e->getMessage()); } } } throw new RouteNotFoundException(sprintf('None of the chained routers were able to generate route "%s".', $name)); }
/** * {@inheritDoc} */ public function store(Response $response, $targetPath, $filter) { try { $storageResponse = $this->storage->putObject(array('ACL' => $this->acl, 'Bucket' => $this->bucket, 'Key' => $targetPath, 'Body' => $response->getContent(), 'ContentType' => $response->headers->get('Content-Type'))); } catch (\Exception $e) { if ($this->logger) { $this->logger->warn('The object could not be created on Amazon S3.', array('targetPath' => $targetPath, 'filter' => $filter)); } return $response; } $response->setStatusCode(301); $response->headers->set('Location', $storageResponse->get('ObjectURL')); return $response; }
/** * Removes a specified bundle * * @param Bundle $bundle */ protected function removeBundle(Bundle $bundle) { $owner = $bundle->getOwner(); if ($owner instanceof Owner) { $owner->removeBundle($bundle); } // remove bundle from search index $this->indexer->deleteBundlesIndexes($bundle); $this->em->remove($bundle); $this->em->flush(); // @todo also delete folder if ($this->logger) { $this->logger->warn(sprintf('Bundle "%s" was deleted', $bundle->getName())); } }
/** * Logs exceptions * * @param \Exception $originalException Original exception that called the listener * @param \Exception $generatedException Generated exception * @param string|null $message Message to log */ private function logException(\Exception $originalException, \Exception $generatedException, $message = null) { if (!$message) { $message = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($generatedException), $generatedException->getMessage()); } if (null !== $this->logger) { if (!$originalException instanceof HttpExceptionInterface || $originalException->getStatusCode() >= 500) { $this->logger->crit($message); } else { $this->logger->err($message); } } else { error_log($message); } }
/** * Extract messages to MessageCatalogue. * * @return MessageCatalogue * * @throws \Exception|\RuntimeException */ public function extract() { if ($this->catalogue) { throw new \RuntimeException('Invalid state'); } $this->catalogue = new MessageCatalogue(); foreach ($this->adminPool->getAdminServiceIds() as $id) { $admin = $this->getAdmin($id); $this->translator = $admin->getTranslator(); $this->labelStrategy = $admin->getLabelTranslatorStrategy(); $this->domain = $admin->getTranslationDomain(); $admin->setTranslator($this); $admin->setSecurityHandler($this); $admin->setLabelTranslatorStrategy($this); // foreach ($admin->getChildren() as $child) { // $child->setTranslator($this); // } // call the different public method $methods = array('getShow' => array(array()), 'getDatagrid' => array(array()), 'getList' => array(array()), 'getForm' => array(array()), 'getBreadcrumbs' => array(array('list'), array('edit'), array('create'), array('update'), array('batch'), array('delete'))); if ($this->logger) { $this->logger->info(sprintf('Retrieving message from admin:%s - class: %s', $admin->getCode(), get_class($admin))); } foreach ($methods as $method => $calls) { foreach ($calls as $args) { try { call_user_func_array(array($admin, $method), $args); } catch (\Exception $e) { if ($this->logger) { $this->logger->error(sprintf('ERROR : admin:%s - Raise an exception : %s', $admin->getCode(), $e->getMessage())); } throw $e; } } } } $catalogue = $this->catalogue; $this->catalogue = false; return $catalogue; }
/** * Handle a server-initiated message by passing it to our handlers. * @param \XMPPHP_XMLObj $message The message. */ public function handleMessage(\XMPPHP_XMLObj $message) { try { $parsed = simplexml_load_string($message->toString()); $payload = $parsed->event->asXml(); } catch (\Exception $exception) { if ($this->logger !== null) { $this->logger->err("Problem parsing XML: " . $message->toString()); } throw $exception; } try { foreach ($this->handlers as $handler) { $handler->handleNotification($payload); } } catch (\Exception $exception) { // Log exceptions, but don't stop them from propagating if ($this->logger !== null) { $this->logger->err("Caught " . \get_class($exception) . " while handling notification: " . $exception->getMessage()); } throw $exception; } }
/** * A convenience function for logging a debug event. * * @param mixed $message the message to log. */ public function debug($message) { $add = true; if (null !== $this->stopwatch) { $trace = debug_backtrace(); $method = $trace[2]['args'][2]; $watch = 'Propel Query ' . (count($this->queries) + 1); if ('PropelPDO::prepare' === $method) { $this->isPrepared = true; $this->stopwatch->start($watch, 'propel'); $add = false; } elseif ($this->isPrepared) { $this->isPrepared = false; $this->stopwatch->stop($watch); } } if ($add) { $this->queries[] = $message; if (null !== $this->logger) { $this->logger->debug($message); } } }