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; }
/** * @param $message * @param array $extra * * @return $this */ public function debug($message, $extra = []) { if (getenv('DEBUG')) { $this->logger->debug($message, $extra); } return $this; }
/** * {@inheritDoc} */ public function discover(User $user) { $client = clone $this->client; $client->setDefaultOption('headers/Authorization', 'token ' . $user->getProviderAccessToken('github')); $request = $client->get('/user/orgs'); $response = $request->send(); $data = $response->json(); $orgRequests = [$client->get('/user/repos')]; foreach ($data as $org) { $this->logger->debug(sprintf('adding "' . $org['repos_url'] . '" for crawl')); $orgRequests[] = $client->get($org['repos_url']); } $orgResponses = $client->send($orgRequests); $composerRequests = []; foreach ($orgResponses as $orgResponse) { $this->fetchRepos($orgResponse); if ($orgResponse->hasHeader('link')) { $link = $orgResponse->getHeader('link'); if (preg_match('/.* <(.+?)\\?page=(\\d+)>; rel="last"$/', $link, $matches)) { $pagesRequests = []; for ($i = 2; $i <= $matches[2]; $i++) { $this->logger->debug(sprintf('adding "' . ($matches[1] . '?page=' . $i) . '" for crawl')); $pagesRequests[] = $client->get($matches[1] . '?page=' . $i); } $pagesResponses = $client->send($pagesRequests); foreach ($pagesResponses as $pagesResponse) { $this->fetchRepos($pagesResponse); } } } } return $this->getImportableProjects(); }
/** * BC compatible version of the signature check * * @param SAML2_SignedElement $element * @param SAML2_Certificate_X509[] $pemCandidates * * @throws Exception * * @return bool */ protected function validateElementWithKeys(SAML2_SignedElement $element, $pemCandidates) { $lastException = NULL; foreach ($pemCandidates as $index => $candidateKey) { $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public')); $key->loadKey($candidateKey->getCertificate()); try { /* * Make sure that we have a valid signature on either the response or the assertion. */ $result = $element->validate($key); if ($result) { $this->logger->debug(sprintf('Validation with key "#%d" succeeded', $index)); return TRUE; } $this->logger->debug(sprintf('Validation with key "#%d" failed without exception.', $index)); } catch (Exception $e) { $this->logger->debug(sprintf('Validation with key "#%d" failed with exception: %s', $index, $e->getMessage())); $lastException = $e; } } if ($lastException !== NULL) { throw $lastException; } else { return FALSE; } }
/** * 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 ''; } } }
/** * Send request and retrieve response to the connected disque node. * * @param array $args * @return array|int|null|string * * @throws CommandException * @throws StreamException */ protected function send(array $args = []) { $this->log->debug('send()ing command', $args); $response = RespUtils::deserialize($this->stream->write(RespUtils::serialize($args))); $this->log->debug('response', [$response]); return $response; }
/** * @param Message $message * @param callable $next */ public function handle($message, callable $next) { $next($message); $this->logger->debug(sprintf('CommitsObjectManagerTransaction flushes Object manager after handling command "%s"', $message instanceof NamedMessage ? $message::messageName() : get_class($message))); $this->om->flush(); $this->logger->debug(sprintf('CommitsObjectManagerTransaction finished handling "%s"', $message instanceof NamedMessage ? $message::messageName() : get_class($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); } } }
/** * consume. * * @param array $options Parameters sent to the processor */ public function consume(array $options = array()) { if (null !== $this->logger) { $this->logger->debug(sprintf('Start consuming queue %s.', $this->messageProvider->getQueueName())); } $this->optionsResolver->setDefaults(array('poll_interval' => 50000)); if ($this->processor instanceof ConfigurableInterface) { $this->processor->setDefaultOptions($this->optionsResolver); } $options = $this->optionsResolver->resolve($options); if ($this->processor instanceof InitializableInterface) { $this->processor->initialize($options); } while (true) { while (null !== ($message = $this->messageProvider->get())) { if (false === $this->processor->process($message, $options)) { break 2; } } if ($this->processor instanceof SleepyInterface) { if (false === $this->processor->sleep($options)) { break; } } usleep($options['poll_interval']); } if ($this->processor instanceof TerminableInterface) { $this->processor->terminate($options); } }
public function parseClass(\ReflectionClass $class) { if (isset($this->logger)) { $this->logger->debug("Parsing file " . $class->getFileName() . " for " . $class->getName()); } return $this->_parse($class); }
public function onCustomListener(ActionEvent $event) { $user = $event->getUser(); $request = $event->getRequest(); $this->logger->info('--------------------------------- > The user with name: ' . $user->getUsername() . ' goint to ' . $request->getUri() . '--------------------------------->'); $this->logger->debug(json_encode($request->headers->all())); }
public function cleanUp() { foreach ($this->handlers as $handler) { $this->logger->debug('Clear monolog fingers crossed handler'); $handler->clear(); } }
/** * @param JwtContext $context * @throws \BWC\Component\JwtApiBundle\Error\JwtException */ public function handleContext(JwtContext $context) { if ($this->logger) { $this->logger->debug('ValidatorHandler', array('context' => $context)); } $this->validator->validate($context); }
/** * @param DelegatingSourceCleaner $cleaner * @param Feed $feed * @param ThresholdVoterInterface $voter * * @return bool */ public function cleanFeed(DelegatingSourceCleaner $cleaner, Feed $feed, ThresholdVoterInterface $voter) { if (null === ($expireDate = $this->getLastFullImportDate($feed))) { $this->logger->debug(sprintf('Skipping %s, because it has no recent imports', $feed)); $this->eventDispatcher->dispatch(IoEvents::FEED_CLEANUP_SKIP, new FeedCleanupEvent($feed, 0)); return false; } $this->eventDispatcher->dispatch(IoEvents::PRE_CLEAN_FEED, new FeedEvent($feed)); $this->logger->debug(sprintf('Checking sources of %s that have not been visited since %s', $feed, $expireDate->format('Y-m-d H:i:s'))); // get sources that haven't been visited since $expireDate $sourceRepo = $this->sourceManager->getRepository(); $count = $sourceRepo->countByFeedAndUnvisitedSince($feed, $expireDate); // fail safe: see if percentage of sources to be removed is not too high $total = $sourceRepo->countByFeed($feed); $max = $this->getThreshold($total); // see if threshold is reached if ($count > $max) { $message = sprintf('Stopping cleanup for %s, because %s of %s sources were to be deleted, %s is the maximum.', $feed, $count, $total, $max); if (!$voter->vote($count, $total, $max, $message)) { $this->eventDispatcher->dispatch(IoEvents::FEED_CLEANUP_HALT, new FeedCleanupHaltEvent($feed, $count, $total, $max)); return false; } } $this->logger->debug(sprintf('Cleaning %d sources for %s', $count, $feed)); $builder = $sourceRepo->queryByFeedAndUnvisitedSince($feed, $expireDate); $numCleaned = $cleaner->cleanByQuery($builder->getQuery()); $this->eventDispatcher->dispatch(IoEvents::POST_CLEAN_FEED, new FeedCleanupEvent($feed, $numCleaned)); return $numCleaned; }
/** * @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; }
/** * Returns a ControllerReference object corresponding to $valueObject and $viewType * * @param ValueObject $valueObject * @param string $viewType * * @throws \InvalidArgumentException * * @return \Symfony\Component\HttpKernel\Controller\ControllerReference|null */ public function getControllerReference(ValueObject $valueObject, $viewType) { $matchedType = null; if ($valueObject instanceof Location) { $matcherProp = 'locationMatcherFactory'; $matchedType = 'Location'; } else { if ($valueObject instanceof ContentInfo) { $matcherProp = 'contentMatcherFactory'; $matchedType = 'Content'; } else { if ($valueObject instanceof Block) { $matcherProp = 'blockMatcherFactory'; $matchedType = 'Block'; } else { throw new InvalidArgumentException('Unsupported value object to match against'); } } } $configHash = $this->{$matcherProp}->match($valueObject, $viewType); if (!is_array($configHash) || !isset($configHash['controller'])) { return; } $this->logger->debug("Matched custom controller '{$configHash['controller']}' for {$matchedType} #{$valueObject->id}"); return new ControllerReference($configHash['controller']); }
/** * @param EndRequestEvent $event */ public function onEndRequest(EndRequestEvent $event) { $this->requestLogger->endRequest($event->getDirectResponse()); if ($this->logger) { $this->logger->debug('Ext.direct response sent: {response}', ['response' => json_encode($event->getDirectResponse())]); } }
/** * @param string $pidPath * @param bool $throwException * @param LoggerInterface $logger * @param LOLClientInterface|null $client * * @throws \RuntimeException */ public static function killProcess($pidPath, $throwException, LoggerInterface $logger, LOLClientInterface $client = null) { $pid = (int) file_get_contents($pidPath); // Test if process is still running $output = []; exec('ps ' . $pid, $output); if (!isset($output[1])) { if (null != $client) { $logger->debug('Client ' . $client . ' (pid: #' . $pid . ') not running, deleting cache pid file'); } else { $logger->debug('Process #' . $pid . ' not running, deleting cache pid file'); } unlink($pidPath); return; } // Kill if (posix_kill($pid, SIGKILL)) { if (null != $client) { $logger->debug('Client ' . $client . ' (pid: #' . $pid . ') has been killed'); } else { $logger->debug('Process #' . $pid . ' has been killed'); } unlink($pidPath); } else { if ($throwException) { throw new \RuntimeException('Cannot kill the process #' . $pid . ', please kill this process manually'); } $logger->critical('Cannot kill the process #' . $pid . ', please kill this process manually'); } }
/** * Dispatches messages to the job manager. * * This method is registered as the message handler for messages with name "ConsumeJob". * * @param DefaultMessage $message */ public function consumeJob(DefaultMessage $message) { $ticket = $message->ticket; $type = $message->type; $this->logger->debug('Consume message from bernard backend', ['message' => $message]); $this->manager->onMessage(new Message($type, $ticket)); }
/** * {@inheritDoc} */ public function debug($message) { if ($this->isDebugging()) { $this->debug_logger->debug($message, ['className' => get_class($this)]); } return $this; }
/** * @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())); } }
public static function debug($msg, $context = array()) { if (!self::$_impl) { return; } self::$_impl->debug($msg, $context = array()); }
/** * Logs payment related information used for debug * * @param array $debugData * @param array $debugReplaceKeys * @param bool $debugFlag * @return void */ public function debug(array $debugData, array $debugReplaceKeys, $debugFlag) { if ($debugFlag == true && !empty($debugData) && !empty($debugReplaceKeys)) { $debugData = $this->filterDebugData($debugData, $debugReplaceKeys); $this->logger->debug(var_export($debugData, true)); } }
/** * @param string $name * @param mixed $data * @param int $priority * @param string $unique * @return mixed */ public function execute($name, $data = null, $priority = self::NORMAL, $unique = null) { $client = $this->getClient()->getClient(); if (null !== $this->logger) { $this->logger->debug("Sent job \"{$name}\" to GearmanClient"); } $result = null; switch ($priority) { case self::LOW: $result = $client->doLow($name, self::serialize($data), $unique); break; case self::HIGH: $result = $client->doHigh($name, self::serialize($data), $unique); break; default: $result = $client->doNormal($name, self::serialize($data), $unique); break; } if ($client->returnCode() !== GEARMAN_SUCCESS) { if (null !== $this->logger) { $this->logger->error("Bad return code"); } } if (null !== $this->logger) { $this->logger->debug("Job \"{$name}\" returned {$result}"); } return unserialize($result); }
/** * @param ScrapeResponseEvent $event */ public function onScrapeUrlNotOk(ScrapeResponseEvent $event) { $response = $event->getResponse(); $code = $response->getStatusCode(); $text = (new Response($code))->getReasonPhrase(); $this->logger->debug(sprintf('Server replied with response %d (%s)', $code, $text)); }
/** * Start the worker and wait for requests */ public function listen() { $context = new \ZMQContext(); $server = new \ZMQSocket($context, \ZMQ::SOCKET_PULL); $server->bind('tcp://127.0.0.1:' . ($this->defaultPort + $this->client->getId() - 1)); $this->logger->info('Client worker ' . $this->client . ' is ready'); while (true) { $request = $server->recv(); $this->logger->debug('Client worker ' . $this->client . ' receiving request : ' . $request); // Check if the input is valid, ignore if wrong $request = json_decode($request, true); if (!$this->isValidInput($request)) { $this->logger->error('Client worker ' . $this->client . ' received an invalid input'); continue; } try { // Call the right method in the client and push to redis the result $result = call_user_func_array(array($this->client, $request['command']), $request['parameters']); } catch (ClientNotReadyException $e) { $this->logger->warning('Client worker ' . $this->client . ' received a request (#' . $request['invokeId'] . ') whereas the client is not ready. This is normal in case of client reconnection process. Ignoring.'); continue; } $key = $this->key . '.client.commands.' . $request['invokeId']; $this->redis->rpush($key, serialize($result)); $this->redis->expire($key, $this->expire); } }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $this->logger->debug($this->getMimeEntityString($message)); $this->sendPerformed($message); return $this->numberOfRecipients($message); }
protected function removeInvalidSelf(LoggerInterface $logger) { // Must have "href" attribute. if (!$this->hasAttribute('href')) { $logger->debug('Removing ' . $this . '. Requires "href" attribute.'); return true; } // Must have either "rel" or "itemprop" attribute, but not both. $attrCount = 0; foreach ($this->attributes as $attribute) { if ($attribute->getName() == 'rel' || $attribute->getName() == 'itemprop') { ++$attrCount; } if ($attrCount > 1) { // If both, then we don't know which one should be kept, // so we recommend to delete the entire element. $logger->debug('Removing ' . $this . '. Requires either "rel" or "itemprop" attribute, but not both.'); return true; } } if ($attrCount == 0) { $logger->debug('Removing ' . $this . '. Requires either "rel" or "itemprop" attribute.'); return true; } // If inside "body" element, then we check if allowed. $body = new Body($this->configuration, 0, 0, 'body'); if ($this->hasAncestor($body) && !$this->isAllowedInBody()) { $logger->debug('Removing ' . $this . '. Does not have the correct attributes to be allowed inside the "body" element.'); return true; } return false; }
/** * @param string $pid */ public function setPid($pid) { if (null !== $this->logger) { $this->logger->debug("Started GearmanWorker Daemon {$pid}"); } file_put_contents($this->getPidFile(), $pid); }
/** * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) { return; } // @todo make endpoint(s) customizable if ($event->getRequest()->getMethod() !== 'POST') { return; } if ($event->getRequest()->getPathInfo() != '/xmlrpc' && $event->getRequest()->getPathInfo() != '/xmlrpc.php') { return; } try { $request = $this->requestGenerator->generateFromRequest($event->getRequest()); if (isset($this->logger)) { $this->logger->debug((string) $request); } } catch (UnexpectedValueException $e) { $event->setResponse(new Response("Invalid request XML\n" . $e->getMessage(), 400)); return; } // @todo refactor to dynamically set follow-up events instead of testing (cors bundle like) $request->attributes->set('IsXmlRpcRequest', true); $requestContext = new RequestContext(); $requestContext->fromRequest($request); $originalContext = $this->router->getContext(); $this->router->setContext($requestContext); $response = $this->httpKernel->handle($request); $event->setResponse($response); $this->router->setContext($originalContext); if ($response instanceof Response) { $event->setResponse($response); } }