info() public method

Example: User logs in, SQL logs.
public info ( string $message, array $context = [] ) : null
$message string
$context array
return null
Example #1
2
 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;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $this->getEntity()->delete();
     $this->logger->info('Payment status %label (@id) has been deleted.', ['@id' => $this->getEntity()->id(), '%label' => $this->getEntity()->label()]);
     drupal_set_message($this->t('%label has been deleted.', array('%label' => $this->getEntity()->label())));
     $form_state->setRedirectUrl($this->getEntity()->urlInfo('collection'));
 }
Example #3
0
 /**
  * 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 '';
         }
     }
 }
 /**
  * Process a single group.
  *
  * Without queuedjobs, it's necessary to shell this out to a background task as this is
  * very memory intensive.
  *
  * The sub-process will then invoke $processor->runGroup() in {@see Solr_Reindex::doReindex}
  *
  * @param LoggerInterface $logger
  * @param SolrIndex $indexInstance Index instance
  * @param array $state Variant state
  * @param string $class Class to index
  * @param int $groups Total groups
  * @param int $group Index of group to process
  * @param string $taskName Name of task script to run
  */
 protected function processGroup(LoggerInterface $logger, SolrIndex $indexInstance, $state, $class, $groups, $group, $taskName)
 {
     // Build state
     $statevar = json_encode($state);
     if (strpos(PHP_OS, "WIN") !== false) {
         $statevar = '"' . str_replace('"', '\\"', $statevar) . '"';
     } else {
         $statevar = "'" . $statevar . "'";
     }
     // Build script
     $indexName = $indexInstance->getIndexName();
     $scriptPath = sprintf("%s%sframework%scli-script.php", BASE_PATH, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
     $scriptTask = "php {$scriptPath} dev/tasks/{$taskName}";
     $cmd = "{$scriptTask} index={$indexName} class={$class} group={$group} groups={$groups} variantstate={$statevar}";
     $cmd .= " verbose=1 2>&1";
     $logger->info("Running '{$cmd}'");
     // Execute script via shell
     $res = $logger ? passthru($cmd) : `{$cmd}`;
     if ($logger) {
         $logger->info(preg_replace('/\\r\\n|\\n/', '$0  ', $res));
     }
     // If we're in dev mode, commit more often for fun and profit
     if (Director::isDev()) {
         Solr::service($indexName)->commit();
     }
     // This will slow down things a tiny bit, but it is done so that we don't timeout to the database during a reindex
     DB::query('SELECT 1');
 }
 /**
  * @param Request $request
  *
  * @Rest\View(statusCode=204)
  * @Rest\Post("/webhook", defaults={"_format": "json"})
  *
  * @throws ResourceConflictException
  * @throws \Exception
  * @return null
  */
 public function handleWebHookAction(Request $request)
 {
     $this->logger->info($request->getContent());
     try {
         $event = null;
         $store = $this->storeService->getStoreByRequest($request);
         $eventId = $this->shopifyEventRetriever->verifyWebhookRequest($request, $store);
         $event = $this->shopifyEventRetriever->retrieve($eventId);
         if ($event) {
             throw new EventAlreadyProcessed(sprintf('Event Id %s has already been processed', $eventId));
         }
         //Save the event so we don't process this again
         $event = Event::createFromRequest($request, $eventId);
         $this->eventRepository->save($event);
         $cmd = $this->commandFactory->create($event, $store);
         $handler = $this->handlerFactory->create($event);
         $handler->execute($cmd);
         $event->updateStatus(Event::STATUS_PROCESSED);
         $this->logger->alert(sprintf('Completed Processing event id %s', $eventId));
     } catch (\Exception $e) {
         if ($event instanceof Event) {
             $event->updateStatus(Event::STATUS_FAILED);
         }
         $this->logger->alert($e->getMessage());
     } finally {
         if ($event instanceof Event) {
             $this->eventRepository->update($event);
         }
         return new Response('', 201);
     }
 }
 /**
  * Execute the next task on the queue
  *
  * @param string $queue
  * @param int $timeout
  * @throws \Exception
  * @throws \mcfedr\Queue\JobManagerBundle\Exception\UnrecoverableException
  * @throws \mcfedr\Queue\JobManagerBundle\Exception\ExecuteException
  */
 public function execute($queue = null, $timeout = null)
 {
     $job = $this->manager->get($queue, $timeout);
     if (!$job) {
         return;
     }
     $task = json_decode($job->getData(), true);
     $this->logger->info('Got task', ['task' => $task['name'], 'options' => $task['options']]);
     try {
         /** @var Worker $worker */
         $worker = $this->container->get($task['name']);
         foreach ($this->preListeners as $listener) {
             $listener->preTask($worker, $task['options']);
         }
         $worker->execute($task['options']);
         foreach ($this->postListeners as $listener) {
             $listener->postTask($worker, $task['options']);
         }
         $this->manager->delete($job);
     } catch (ServiceNotFoundException $e) {
         $this->manager->delete($job);
         $throw = new UnrecoverableException("Service for job not found", 0, $e);
         $throw->setJob($job);
         throw $throw;
     } catch (UnrecoverableException $e) {
         $this->manager->delete($job);
         $e->setJob($job);
         throw $e;
     } catch (\Exception $e) {
         throw new ExecuteException($job, $e);
     }
 }
 /**
  * Create an express view from the given XML view, will utilize the cache directory
  * to dump and load a template compiled into plain PHP code.
  * 
  * @param ExpressViewRenderer $renderer
  * @param string $resource The resource to be compiled into a view.
  * @return string The fully-qualified name of the compiled view.
  * 
  * @throws \RuntimeException When the given resource could not be found.
  */
 public function createView(ExpressViewRenderer $renderer, $resource)
 {
     $resource = (string) $resource;
     if (!is_file($resource)) {
         throw new \RuntimeException(sprintf('Express view not found: "%s"', $resource));
     }
     $key = $this->createKey($resource);
     $typeName = $this->createTypeName($resource);
     if (class_exists($typeName, false)) {
         return $typeName;
     }
     $file = $this->cachePath . '/' . $key . '.php';
     if (!is_file($file) || filemtime($file) < filemtime($resource)) {
         $time = microtime(true);
         try {
             $code = $this->parseView($renderer, file_get_contents($resource), $resource)->generateCode($key);
         } catch (\Exception $e) {
             throw new \RuntimeException(sprintf('Unable to parse express view "%s"', $resource), 0, $e);
         }
         Filesystem::writeFile($file, $code);
         $diff = sprintf('%.2f', microtime(true) - $time);
         if ($this->logger) {
             $this->logger->info('Compiled express view {view}, time spent {time} seconds', ['view' => $resource, 'time' => $diff]);
         }
     }
     require_once $file;
     if (!class_exists($typeName, false)) {
         throw new \RuntimeException(sprintf('Unable to load compiled express view "%s"', $resource));
     }
     return $typeName;
 }
 /**
  * Create new depended period and calculation or return existing data.
  *
  * This function is created for CRAP reducing and is used from this class only.
  *
  * @param \Praxigento\BonusBase\Service\Period\Response\GetForDependentCalc $result
  * @param string $baseCalcTypeCode
  * @param string $baseDsBegin
  * @param string $baseDsEnd
  * @param string $dependentCalcTypeCode
  * @param int $dependentCalcTypeId
  * @param string $dependentDsBegin
  * @param string $dependentDsEnd
  */
 public function _getDependedCalcForExistingPeriod(\Praxigento\BonusBase\Service\Period\Response\GetForDependentCalc $result, $baseCalcTypeCode, $baseDsBegin, $baseDsEnd, $dependentCalcTypeCode, $dependentCalcTypeId, $dependentDsBegin, $dependentDsEnd)
 {
     if ($dependentDsBegin == $baseDsBegin && $dependentDsEnd == $baseDsEnd) {
         /* dependent period has the same begin/end as related base period, get calc data */
         $this->_logger->info("There is base '{$baseCalcTypeCode}' period for dependent '{$dependentCalcTypeCode}' period ({$dependentDsBegin}-{$dependentDsEnd}).");
         $this->_analyzeDependedCalc($result, $dependentCalcTypeCode, $dependentCalcTypeId, $dependentDsBegin, $dependentDsEnd);
     } else {
         /* dependent period has different begin/end than related base period */
         $this->_logger->warning("There is no period for '{$dependentCalcTypeCode}' calculation based on '{$baseCalcTypeCode}' ({$baseDsBegin}-{$baseDsEnd}). New period and related calculation will be created.");
         /* create new depended period & calc */
         $period = new EPeriod();
         $period->setCalcTypeId($dependentCalcTypeId);
         $period->setDstampBegin($baseDsBegin);
         $period->setDstampEnd($baseDsEnd);
         $periodId = $this->_repoPeriod->create($period);
         $period->setId($periodId);
         /* create related calculation */
         $calc = new ECalculation();
         $calc->setPeriodId($periodId);
         $dateStarted = $this->_toolDate->getUtcNowForDb();
         $calc->setDateStarted($dateStarted);
         $calc->setState(Cfg::CALC_STATE_STARTED);
         $calcId = $this->_repoCalc->create($calc);
         $calc->setId($calcId);
         /* place new objects into response */
         $result->setDependentPeriodData($period);
         $result->setDependentCalcData($calc);
     }
 }
 /**
  * updates Activity Document Link
  * @param array                $documentLink
  * @param ActivityDocumentLink $activityDocumentLink
  * @return bool
  */
 public function update(array $documentLink, ActivityDocumentLink $activityDocumentLink)
 {
     try {
         $this->database->beginTransaction();
         $documentLinkExists = $activityDocumentLink->exists;
         $activityId = $activityDocumentLink->activity_id;
         $documentManager = app(DocumentManager::class);
         if ($documentLinkExists) {
             $url = $activityDocumentLink->document_link['url'];
             $document = $documentManager->getDocument(session('org_id'), $url);
             $activities = (array) $document->activities;
             unset($activities[$activityId]);
             $document->activities = $activities;
             $documentManager->update($document);
         }
         $url = $documentLink[0]['url'];
         $document = $documentManager->getDocument(session('org_id'), $url);
         $activities = (array) $document->activities;
         $identifier = $activityDocumentLink->activity->identifier['activity_identifier'];
         $activities[$activityId] = $identifier;
         $document->activities = $activities;
         $documentManager->update($document);
         $this->DocumentLinkRepo->update($documentLink, $activityDocumentLink);
         $this->database->commit();
         $this->logger->info(sprintf('Activity Document Link %s!', $documentLinkExists ? 'updated' : 'saved'), ['for' => $documentLink]);
         $this->dbLogger->activity(sprintf("activity.document_link_%s", $documentLinkExists ? 'updated' : 'saved'), ['activity_id' => $activityDocumentLink->activity_id, 'document_link_id' => $activityDocumentLink->id, 'organization' => $this->auth->user()->organization->name, 'organization_id' => $this->auth->user()->organization->id]);
         return true;
     } catch (\Exception $exception) {
         $this->database->rollback();
         $this->logger->error($exception, ['documentLink' => $documentLink]);
     }
     return false;
 }
 protected function r4_add_record(CreatedDomain $domain, Record $record)
 {
     if ($this->logger) {
         $this->logger->info("Adding " . $record->name);
     }
     return $domain->add_record($record, $this->api);
 }
Example #11
0
 /**
  * @param $message
  * @param $context
  */
 private function log($message, $context = [])
 {
     if ($this->logger instanceof LoggerInterface) {
         $context['class'] = self::class;
         $this->logger->info($message, $context);
     }
 }
Example #12
0
 /**
  * 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);
     }
 }
Example #13
0
 public static function info($msg, $context = array())
 {
     if (!self::$_impl) {
         return;
     }
     self::$_impl->info($msg, $context);
 }
 public function runCrons()
 {
     $entityManager = $this->managerRegistry->getManagerForClass('DspSoftsCronManagerBundle:CronTask');
     $cronTaskRepo = $entityManager->getRepository('DspSoftsCronManagerBundle:CronTask');
     $cronTasks = $cronTaskRepo->findCronsToLaunch();
     foreach ($cronTasks as $cronTask) {
         $run = true;
         if (!$cronTask->getRelaunch()) {
             $run = $this->planificationChecker->isExecutionDue($cronTask->getPlanification());
         }
         if ($run) {
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Running Cron Task <info>%s</info>', $cronTask->getName()));
             }
             $cli = 'exec ' . $this->kernelRootDir . DIRECTORY_SEPARATOR . 'console dsp:cron:runjob -c ' . $cronTask->getId() . ' &';
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Command line : <info>%s</info>', $cli));
             }
             $process = new Process($cli);
             $process->setTimeout(0);
             $process->start();
         } else {
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Skipping Cron Task <info>%s</info>', $cronTask->getName()));
             }
         }
     }
 }
Example #15
0
 public function inlineQuery(Update $update) : unreal4uBot
 {
     $this->logger->info(sprintf('Received inline query. User id %d (username: %s). Query: "%s", inline query id: %s', $update->inline_query->from->id, $update->inline_query->from->username, $update->inline_query->query, $update->inline_query->id));
     $query = $update->inline_query->query;
     if (empty($query)) {
         $query = 'What is lmgtfy?';
     }
     // Number of results
     $i = 1;
     $inlineQueryResultArticle = new Article();
     $inlineQueryResultArticle->url = 'http://lmgtfy.com/?q=' . urlencode($query);
     $inlineQueryResultArticle->title = $inlineQueryResultArticle->url;
     //'Forward this message to anyone you would like (Title)';
     $inlineQueryResultArticle->hide_url = true;
     $inputMessageContentText = new Text();
     $inputMessageContentText->message_text = $inlineQueryResultArticle->url;
     $inputMessageContentText->disable_web_page_preview = true;
     $inlineQueryResultArticle->input_message_content = $inputMessageContentText;
     // @TODO find a way to compress this all into an identifiable 64bit ascii string, maybe with pack()?
     $inlineQueryResultArticle->id = md5(json_encode(['uid' => $update->inline_query->from->id, 'iqid' => $update->inline_query->id, 'rid' => $i]));
     $answerInlineQuery = new AnswerInlineQuery();
     $answerInlineQuery->inline_query_id = $update->inline_query->id;
     $answerInlineQuery->addResult($inlineQueryResultArticle);
     $tgLog = new TgLog($this->token, $this->logger);
     //$tgLog->logger = $this->logger;
     $tgLog->performApiRequest($answerInlineQuery);
     $this->logger->info(sprintf('Sent API response to Telegram, all done'));
     return $this;
 }
 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;
 }
Example #17
0
 public function triggerWebtreesAdminTasks()
 {
     $settings = new Settings();
     $this->logger = \Piwik\Container\StaticContainer::get('Psr\\Log\\LoggerInterface');
     $this->logger->info('Webtrees Admin Task triggered');
     $rooturl = $settings->getSetting('webtreesRootUrl');
     if (!$rooturl || strlen($rooturl->getValue()) === 0) {
         return;
     }
     $token = $settings->getSetting('webtreesToken');
     if (!$token || strlen($token->getValue()) === 0) {
         return;
     }
     $taskname = $settings->getSetting('webtreesTaskName');
     if (!$taskname || strlen($taskname->getValue()) === 0) {
         return;
     }
     $url = sprintf('%1$s/module.php?mod=perso_admintasks&mod_action=trigger&force=%2$s&task=%3$s', $rooturl->getValue(), $token->getValue(), $taskname->getValue());
     $this->logger->info('webtrees url : {url}', array('url' => $url));
     try {
         \Piwik\Http::sendHttpRequest($url, Webtrees::SOCKET_TIMEOUT);
     } catch (Exception $e) {
         $this->logger->warning('an error occured', array('exception' => $e));
     }
 }
Example #18
0
 /**
  * @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;
 }
 /**
  * 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;
 }
Example #20
0
 /**
  * {@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);
         }
     }
 }
Example #21
0
 /**
  * check $configuration, get client related to connection config, create vhost, then process exchange and queue
  * @param $vhostName
  * @param array $configuration
  */
 public function processVhost($vhostName, array $configuration)
 {
     $client = $this->clientPool->getClientByName($configuration['connection']);
     $vhostName = urlencode($vhostName);
     $client->query(ClientInterface::METHOD_PUT, sprintf('/api/vhosts/%s', $vhostName), []);
     $this->logger->info(sprintf('Create vhost: <info>%s</info>', urldecode($vhostName)));
     //process parameters
     if (isset($configuration['parameters']) && count($configuration['parameters'])) {
         $this->parameterManager->setClient($client)->setVhost($vhostName);
         foreach ($configuration['parameters'] as $paramType => $parameters) {
             foreach ($parameters as $paramName => $paramOptions) {
                 $this->parameterManager->create($paramType, $paramName, $paramOptions);
             }
         }
     }
     //process exchanges
     if (isset($configuration['exchanges']) && count($configuration['exchanges'])) {
         $this->process($this->exchangeManager, $client, $vhostName, $configuration['exchanges']);
     }
     //process queues
     if (isset($configuration['queues']) && count($configuration['queues'])) {
         $this->process($this->queueManager, $client, $vhostName, $configuration['queues']);
     }
     //process policies
     if (isset($configuration['policies']) && count($configuration['policies'])) {
         $this->process($this->policyManager, $client, $vhostName, $configuration['policies']);
     }
 }
 /**
  * @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);
 }
 /**
  * @param VerifyYubikeyPublicIdCommand $command
  * @return VerificationResult
  */
 public function verifyYubikeyPublicId(VerifyYubikeyPublicIdCommand $command)
 {
     $verifyOtpCommand = new VerifyYubikeyOtpCommand();
     $verifyOtpCommand->otp = $command->otp;
     $verifyOtpCommand->identityId = $command->identityId;
     $verifyOtpCommand->institution = $command->institution;
     $verificationResult = $this->yubikeyService->verify($verifyOtpCommand);
     if (YubikeyOtp::isValid($command->otp)) {
         $otp = YubikeyOtp::fromString($command->otp);
         $publicId = YubikeyPublicId::fromOtp($otp);
     } else {
         $publicId = null;
     }
     if ($verificationResult->isServerError()) {
         return new VerificationResult(VerificationResult::RESULT_OTP_VERIFICATION_FAILED, $publicId);
     } elseif ($verificationResult->isClientError()) {
         return new VerificationResult(VerificationResult::RESULT_OTP_INVALID, $publicId);
     }
     if ($publicId->getYubikeyPublicId() !== $command->expectedPublicId) {
         $this->logger->notice('Yubikey used by registrant during vetting did not match the one used during registration.');
         return new VerificationResult(VerificationResult::RESULT_PUBLIC_ID_DID_NOT_MATCH, $publicId);
     }
     $this->logger->info('Yubikey used by registrant during vetting matches the one used during registration.');
     return new VerificationResult(VerificationResult::RESULT_PUBLIC_ID_MATCHED, $publicId);
 }
Example #24
0
 /**
  * @param callable $migration Closure that receives the table to operate on.
  *
  *  <example>
  *  $migration->execute(function($table) {
  *      $table
  *          ->removeColumn('name')
  *          ->save();
  *  });
  *  </example>
  */
 public function execute(callable $migration)
 {
     $this->logger->info("Starting LHM run on table={$this->origin->getName()}");
     $sqlHelper = new SqlHelper($this->adapter);
     if (!isset($options['atomic_switch'])) {
         if ($sqlHelper->supportsAtomicSwitch()) {
             $this->options['atomic_switch'] = true;
         } else {
             $version = $sqlHelper->versionString();
             throw new \RuntimeException("Using mysql {$version}. You must explicitly set `options['atomic_switch']` (re SqlHelper::supportsAtomicSwitch)");
         }
     }
     if (!$this->destination) {
         $this->destination = $this->temporaryTable();
     }
     $this->setSessionLockWaitTimeouts();
     $entangler = new Entangler($this->adapter, $this->origin, $this->destination, $sqlHelper);
     $entangler->setLogger($this->logger);
     if ($this->options['atomic_switch']) {
         $switcher = new AtomicSwitcher($this->adapter, $this->origin, $this->destination, $this->options);
     } else {
         $switcher = new LockedSwitcher($this->adapter, $this->origin, $this->destination, $this->options);
     }
     $switcher->setLogger($this->logger);
     $chunker = new Chunker($this->adapter, $this->origin, $this->destination, $sqlHelper, $this->options);
     $chunker->setLogger($this->logger);
     $migration($this->destination);
     $entangler->run(function () use($chunker, $switcher) {
         $chunker->run();
         $switcher->run();
     });
 }
 /**
  * @param bool $dryRun
  */
 public function execute($dryRun = false)
 {
     if ($this->logger === null) {
         throw new \RuntimeException('No logger defined');
     }
     $this->processor->setCurrentWorkingDirectory($this->getCurrentWorkingDirectory());
     if (!isset($this->getConfig()->path) || !isset($this->getConfig()->match)) {
         throw new ConfigurationException('Config `path` and `match` are required to cleanup directories');
     }
     $path = $this->getConfig()->path;
     $match = $this->getConfig()->match;
     if (isset($this->getConfig()->recursive) && $this->getConfig()->recursive === true) {
         $recursive = true;
     } else {
         $recursive = false;
     }
     $shouldBeRemoved = $this->getListForRemoval($path, $match, $recursive);
     foreach ($shouldBeRemoved as $item) {
         if (file_exists($item->getPathname())) {
             $date = date('Y-m-d H:i:s', $item->getMTime());
             $this->logger->info("[Removing] {$item->getPathname()} (Modified At: {$date})");
             if (!$dryRun) {
                 $this->processor->execute("rm -Rf {$item->getPathname()}");
             }
         }
     }
 }
Example #26
0
 /**
  * Returns the archives IDs that have already been invalidated and have been since re-processed.
  *
  * These archives { archive name (includes segment hash) , idsite, date, period } will be deleted.
  *
  * @param string $archiveTable
  * @param array $idSites
  * @return array
  * @throws Exception
  */
 public function getInvalidatedArchiveIdsSafeToDelete($archiveTable, array $idSites)
 {
     try {
         Db::get()->query('SET SESSION group_concat_max_len=' . 128 * 1024);
     } catch (\Exception $ex) {
         $this->logger->info("Could not set group_concat_max_len MySQL session variable.");
     }
     $idSites = array_map(function ($v) {
         return (int) $v;
     }, $idSites);
     $sql = "SELECT idsite, date1, date2, period, name,\n                       GROUP_CONCAT(idarchive, '.', value ORDER BY ts_archived DESC) as archives\n                  FROM `{$archiveTable}`\n                 WHERE name LIKE 'done%'\n                   AND value IN (" . ArchiveWriter::DONE_INVALIDATED . ',' . ArchiveWriter::DONE_OK . ',' . ArchiveWriter::DONE_OK_TEMPORARY . ")\n                   AND idsite IN (" . implode(',', $idSites) . ")\n                 GROUP BY idsite, date1, date2, period, name";
     $archiveIds = array();
     $rows = Db::fetchAll($sql);
     foreach ($rows as $row) {
         $duplicateArchives = explode(',', $row['archives']);
         $firstArchive = array_shift($duplicateArchives);
         list($firstArchiveId, $firstArchiveValue) = explode('.', $firstArchive);
         // if the first archive (ie, the newest) is an 'ok' or 'ok temporary' archive, then
         // all invalidated archives after it can be deleted
         if ($firstArchiveValue == ArchiveWriter::DONE_OK || $firstArchiveValue == ArchiveWriter::DONE_OK_TEMPORARY) {
             foreach ($duplicateArchives as $pair) {
                 if (strpos($pair, '.') === false) {
                     $this->logger->info("GROUP_CONCAT cut off the query result, you may have to purge archives again.");
                     break;
                 }
                 list($idarchive, $value) = explode('.', $pair);
                 if ($value == ArchiveWriter::DONE_INVALIDATED) {
                     $archiveIds[] = $idarchive;
                 }
             }
         }
     }
     return $archiveIds;
 }
Example #27
0
 /**
  * @param string $name
  * @param mixed $data
  * @param int $priority
  * @param string $unique
  * @return string $jobHandle
  */
 public function background($name, $data = null, $priority = self::NORMAL, $unique = null)
 {
     $client = $this->getClient()->getClient();
     if (null !== $this->logger) {
         $this->logger->debug("Sent background job \"{$name}\" to GearmanClient");
     }
     $jobHandle = null;
     switch ($priority) {
         case self::LOW:
             $jobHandle = $client->doLowBackground($name, self::serialize($data), $unique);
             break;
         case self::HIGH:
             $jobHandle = $client->doHighBackground($name, self::serialize($data), $unique);
             break;
         default:
             $jobHandle = $client->doBackground($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->info("Sent job \"{$jobHandle}\" to GearmanWorker");
     }
     return $jobHandle;
 }
 /**
  * {@inheritdoc}
  */
 public function render(BlockContextInterface $blockContext, Response $response = null)
 {
     $block = $blockContext->getBlock();
     if ($this->logger) {
         $this->logger->info(sprintf('[cms::renderBlock] block.id=%d, block.type=%s ', $block->getId(), $block->getType()));
     }
     try {
         $service = $this->blockServiceManager->get($block);
         $service->load($block);
         $response = $service->execute($blockContext, $this->createResponse($blockContext, $response));
         if (!$response instanceof Response) {
             $response = null;
             throw new \RuntimeException('A block service must return a Response object');
         }
         $response = $this->addMetaInformation($response, $blockContext, $service);
     } catch (\Exception $exception) {
         if ($this->logger) {
             $this->logger->critical(sprintf('[cms::renderBlock] block.id=%d - error while rendering block - %s', $block->getId(), $exception->getMessage()));
         }
         // reseting the state object
         $this->lastResponse = null;
         $response = $this->exceptionStrategyManager->handleException($exception, $blockContext->getBlock(), $response);
     }
     return $response;
 }
Example #29
0
 /**
  * logs request api call including options
  *
  * @param string $scope
  * @param string $name
  * @param array $opts
  * @return boolean
  */
 public function log($scope, $name, $opts)
 {
     // stop measure the response time
     $this->stop();
     $this->logger->info(sprintf('%s to %s (%2.4fs)', Config::getInstance()->http_post ? 'POST' : 'GET', $this->formatUrl($scope, $name, $opts), $this->responseTime));
     return true;
 }
 private function subscribePlatform($platform, $topic)
 {
     foreach ($this->sns->getListEndpointsByPlatformApplicationIterator(['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         $this->logger && $this->logger->info('Subscribing device to topic', ['device' => $endpoint['EndpointArn'], 'topic' => $topic, 'platform' => $platform]);
         $this->topics->registerDeviceOnTopic($endpoint['EndpointArn'], $topic);
     }
 }