The message MUST be a string or object implementing __toString(). The message MAY contain placeholders in the form: {foo} where foo will be replaced by the context data in key "foo". The context array can contain arbitrary data, the only assumption that can be made by implementors is that if an Exception instance is given to produce a stack trace, it MUST be in a key named "exception".
Exemplo n.º 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;
 }
Exemplo n.º 2
1
 /**
  * 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;
 }
Exemplo n.º 3
0
 /**
  * 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));
 }
Exemplo n.º 4
0
 /**
  * @param string $pid
  */
 public function setPid($pid)
 {
     if (null !== $this->logger) {
         $this->logger->debug("Started GearmanWorker Daemon {$pid}");
     }
     file_put_contents($this->getPidFile(), $pid);
 }
Exemplo n.º 5
0
 /**
  * {@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;
 }
 /**
  * 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));
 }
Exemplo n.º 7
0
 public function filter($tempMinifiedFilename)
 {
     $originalFilename = $this->srcFile->getPath();
     $jarPath = $this->externalLibPath . '/closurecompiler/compiler.jar';
     $command = "java -jar {$jarPath} --warning_level QUIET --language_in ECMASCRIPT5 --compilation_level SIMPLE_OPTIMIZATIONS --js {$originalFilename} --js_output_file {$tempMinifiedFilename}";
     //SIMPLE_OPTIMIZATIONS
     //ADVANCED_OPTIMIZATIONS
     //java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js hello.js
     $output = system($command, $returnValue);
     if ($returnValue != 0) {
         @unlink($tempMinifiedFilename);
         $logging = "command is {$command} <br/>";
         $logging .= "curr dir " . getcwd() . "<br/>";
         $logging .= "returnValue {$returnValue} <br/>";
         $logging .= "result is: ";
         $logging .= "Output is: " . $output . "<br/>";
         $this->logger->critical("Failed to generate minified Javascript: " . $logging);
         header("Content-type: text/javascript");
         header("Cache-Control: no-cache, must-revalidate");
         // HTTP/1.1
         header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
         // Date in the past
         echo "alert('Javacript not generated. Someone please tell the server dude \"{$originalFilename}\" failed.')";
         exit(0);
     }
 }
Exemplo n.º 8
0
 public function testBeforeDispatchWithException()
 {
     $exception = new LocalizedException(new Phrase('Phrase'));
     $this->themeRegistration->expects($this->once())->method('register')->willThrowException($exception);
     $this->logger->expects($this->once())->method('critical');
     $this->plugin->beforeDispatch($this->abstractAction, $this->request);
 }
Exemplo n.º 9
0
 /**
  * Handle exception
  *
  * @param \Exception $e
  * @return void
  */
 protected function handleException($e)
 {
     $needToMaskDisplayMessage = !$e instanceof \Magento\Framework\Exception\LocalizedException && $this->appState->getMode() != State::MODE_DEVELOPER;
     $displayMessage = $needToMaskDisplayMessage ? (string) new \Magento\Framework\Phrase('An error occurred while processing your request') : $e->getMessage();
     $this->messageManager->addError($displayMessage);
     $this->logger->critical($e->getMessage());
 }
Exemplo n.º 10
0
 /**
  * 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));
     }
 }
Exemplo n.º 11
0
 /**
  * @param \Magento\Framework\HTTP\Adapter\Curl $subject
  * @param $result
  * @return mixed
  */
 public function afterRead(\Magento\Framework\HTTP\Adapter\Curl $subject, $result)
 {
     try {
         /* @var $curlLog \Foggyline\Sentinel\Model\CurlLog */
         $curlLog = $this->curlLog->create();
         $curlLog->setRequestId($this->helper->getHttpRequestUniqueId());
         $curlLog->setResult($result);
         $curlLog->setMethod($this->cUrlMethod);
         $curlLog->setUrl($this->cUrlUrl);
         $curlLog->setHttpVer($this->cUrlHttpVer);
         $curlLog->setHeaders(serialize($this->cUrlHeaders));
         $curlLog->setBody($this->cUrlBody);
         $curlLog->setHttpCode($subject->getInfo(CURLINFO_HTTP_CODE));
         $curlLog->setTotalTime($subject->getInfo(CURLINFO_TOTAL_TIME));
         $curlLog->setNameLookupTime($subject->getInfo(CURLINFO_NAMELOOKUP_TIME));
         $curlLog->setPrimaryIp($subject->getInfo(CURLINFO_PRIMARY_IP));
         $curlLog->setPrimaryPort($subject->getInfo(CURLINFO_PRIMARY_PORT));
         $curlLog->setLocalIp($subject->getInfo(CURLINFO_LOCAL_IP));
         $curlLog->setLocalPort($subject->getInfo(CURLINFO_LOCAL_PORT));
         $curlLog->setSizeUpload($subject->getInfo(CURLINFO_SIZE_UPLOAD));
         $curlLog->setSizeDownload($subject->getInfo(CURLINFO_SIZE_DOWNLOAD));
         $curlLog->setSpeedUpload($subject->getInfo(CURLINFO_SPEED_UPLOAD));
         $curlLog->setSpeedDownload($subject->getInfo(CURLINFO_SPEED_DOWNLOAD));
         $curlLog->setContentType($subject->getInfo(CURLINFO_CONTENT_TYPE));
         $curlLog->save();
     } catch (\Exception $e) {
         $this->logger->critical($e);
     }
     return $result;
 }
Exemplo n.º 12
0
 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]);
         }
     }
 }
Exemplo n.º 13
0
 /**
  * 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);
     }
 }
Exemplo n.º 14
0
 /**
  * @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()));
     }
 }
Exemplo n.º 15
0
 private function fetchGitTemplate($gitUrl)
 {
     $this->logger->notice('Fetching template from {url}', ['url' => $gitUrl]);
     $directory = $this->createTempDirectory('couscous_template_');
     $this->git->cloneRepository($gitUrl, $directory);
     return $directory;
 }
Exemplo n.º 16
0
 /**
  * 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);
 }
Exemplo n.º 17
0
 /**
  * @param LoggerInterface $logger
  * @param bool $dryRun
  */
 protected function doExecute(LoggerInterface $logger, $dryRun = false)
 {
     $duplicateEntitiesQuery = 'SELECT
             DISTINCT t2.id
         FROM
             orocrm_campaign_email_stats AS t1
         LEFT JOIN orocrm_campaign_email_stats AS t2
             ON t1.email_campaign_id = t2.email_campaign_id
             AND t1.marketing_list_item_id = t2.marketing_list_item_id
             AND t2.id > t1.id
         WHERE t2.id IS NOT NULL';
     // Done in 2 queries for cross DB support.
     $idsToRemove = array_map(function ($item) {
         if (is_array($item) && array_key_exists('id', $item)) {
             return $item['id'];
         }
         return null;
     }, $this->connection->fetchAll($duplicateEntitiesQuery));
     if ($idsToRemove) {
         $query = 'DELETE FROM orocrm_campaign_email_stats WHERE id IN (?)';
         $logger->notice($query);
         if (!$dryRun) {
             $this->connection->executeQuery($query, [$idsToRemove], [Connection::PARAM_INT_ARRAY]);
         }
     }
 }
Exemplo n.º 18
0
 /**
  * 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);
     }
 }
 /**
  * @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)));
 }
Exemplo n.º 20
0
 /**
  * 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;
 }
Exemplo n.º 21
0
 /**
  * @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);
     }
 }
Exemplo n.º 22
0
 /**
  * Logs with an arbitrary level.
  *
  * @param  mixed  $level
  * @param  string $message
  * @param  array  $context
  * @return null
  */
 public function log($level, $message, array $context = array())
 {
     if (null === $this->logger) {
         return;
     }
     $add = true;
     $stackTrace = $this->getStackTrace();
     if (null !== $this->stopwatch) {
         $trace = debug_backtrace();
         $method = $trace[3]['function'];
         $watch = 'Propel Query ' . (count($this->queries) + 1);
         if ('prepare' === $method) {
             $this->isPrepared = true;
             $this->stopwatch->start($watch, 'propel');
             $add = false;
         } elseif ($this->isPrepared) {
             $this->isPrepared = false;
             $event = $this->stopwatch->stop($watch);
         }
     }
     // $trace[2] has no 'object' key if an exception is thrown while executing a query
     if ($add && isset($event) && isset($trace[2]['object'])) {
         $connection = $trace[2]['object'];
         $this->queries[] = array('sql' => $message, 'connection' => $connection->getName(), 'time' => $event->getDuration() / 1000, 'memory' => $event->getMemory(), 'stackTrace' => $stackTrace);
     }
     $this->logger->log($level, $message, $context);
 }
Exemplo n.º 23
0
 /**
  * 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 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));
 }
Exemplo n.º 25
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     if (!is_file($file)) {
         throw new RuntimeException('File does not exists');
     }
     $verbose = $output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL;
     if (!$verbose) {
         $this->logger->pushHandler(new NullHandler());
     }
     try {
         $this->connection->beginTransaction();
         $result = $this->importService->import(file_get_contents($file));
         $this->connection->commit();
         $output->writeln('Import successful!');
         $output->writeln('The following actions were done:');
         $output->writeln('');
         foreach ($result as $message) {
             $output->writeln('- ' . $message);
         }
     } catch (\Exception $e) {
         $this->connection->rollback();
         $output->writeln('An exception occured during import. No changes are applied to the database.');
         $output->writeln('');
         $output->writeln('Message: ' . $e->getMessage());
         $output->writeln('Trace: ' . $e->getTraceAsString());
     }
     if (!$verbose) {
         $this->logger->popHandler();
     }
 }
Exemplo n.º 26
0
 /**
  * Записывает сообщение в лог.
  * @param string $level уровень критичности сообщения
  * @param string $message сообщение, поддерживает плейсхолдеры в формате {placeholder}
  * @param array $placeholders список плейсхолдеров
  * @return $this
  */
 protected function log($level, $message, array $placeholders = [])
 {
     if ($this->traitLogger) {
         $this->traitLogger->log($level, $message, $placeholders);
     }
     return $this;
 }
Exemplo n.º 27
0
 /**
  * @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 bool $rapidFail if true, render a form as a fail page rather than redirect
  * @param string $failPage either a wiki page title, or a URL to an external wiki
  *                         page title.
  * @param array $data information about the current request.
  *                    language, gateway, payment_method, and payment_submethod must be set
  * @param Psr\Log\LoggerInterface $logger
  * @return string full URL of the fail page, or just form name in case of rapidFail
  */
 private static function getFailPageFromParams($rapidFail, $failPage, $data, LoggerInterface $logger)
 {
     if (isset($data['language'])) {
         $language = $data['language'];
     } else {
         $language = WmfFramework::getLanguageCode();
     }
     // Prefer RapidFail.
     if ($rapidFail) {
         // choose which fail page to go for.
         try {
             $fail_ffname = GatewayFormChooser::getBestErrorForm($data['gateway'], $data['payment_method'], $data['payment_submethod']);
             return $fail_ffname;
         } catch (Exception $e) {
             $logger->error('Cannot determine best error form. ' . $e->getMessage());
         }
     }
     if (filter_var($failPage, FILTER_VALIDATE_URL)) {
         return self::appendLanguageAndMakeURL($failPage, $language);
     }
     // FIXME: either add Special:FailPage to avoid depending on wiki content,
     // or update the content on payments to be consistent with the /lang
     // format of ThankYou pages so we can use appendLanguageAndMakeURL here.
     $failTitle = Title::newFromText($failPage);
     $url = wfAppendQuery($failTitle->getFullURL(), array('uselang' => $language));
     return $url;
 }
Exemplo n.º 29
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();
     });
 }
Exemplo n.º 30
0
 /**
  * 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;
 }