public function indexAction() { /** @var \Zend\Http\Request $request */ $request = $this->getRequest(); try { if ($request->isPost()) { $this->form->setData($request->getPost()->toArray() ?: array()); if ($this->form->isValid()) { $mailer = $this->getPluginManager()->get('Mailer'); $url = $this->plugin('url'); // we cannot check reCaptcha twice (security protection) so we have to remove it $filter = $this->form->getInputFilter()->remove('captcha'); $this->service->proceed($filter, $mailer, $url); $this->notification()->success('An Email with an activation link has been sent, please try to check your email box'); } else { $this->notification()->danger('Please fill form correctly'); } } } catch (Exception\UserAlreadyExistsException $e) { $this->notification()->danger('User with this email address already exists'); } catch (\Exception $e) { $this->logger->crit($e); $this->notification()->danger('An unexpected error has occurred, please contact your system administrator'); } $this->form->setAttribute('action', $this->url()->fromRoute('lang/register')); return array('form' => $this->form); }
public function run() { $endTime = time() + $this->lifetime; $this->logger->info(sprintf('Started listening with a lifetime of %d seconds.', $this->lifetime)); while (time() < $endTime) { try { /** @var \Pheanstalk\Job $job */ $job = $this->pheanstalk->reserve(1); } catch (Exception $exception) { } if ($job) { $this->logger->info(sprintf('Reserved job #%d: %s', $job->getId(), $job->getData())); try { $data = json_decode($job->getData(), true); /** @var WorkerInterface $worker */ $worker = $this->workerManager->get($data['worker'], $data['params']); $worker->run(new Context($this, $this->logger, $data['params'])); $this->logger->info(sprintf('Finished job #%d', $job->getId())); $this->pheanstalk->delete($job); } catch (Exception $exception) { $this->logger->emerg('Failed to execute job #' . $job->getId(), ['exception' => $exception]); $this->pheanstalk->bury($job); } } usleep($this->interval); } }
public function __construct(TransportInterface $carrierProtocol, LoopInterface $loop, LoggerInterface $logger) { $that = $this; $this->logger = $logger; $this->loop = $loop; $this->carrierProtocol = $carrierProtocol; $this->actionEmitter = new EventEmitter(); $deferreds =& $this->deferred; $timers =& $this->timers; $carrierProtocol->on("message", function (MessageInterface $message) use(&$deferreds, &$timers, &$loop, $that, $logger) { $string = $message->getData(); try { $jsonMessage = RemoteEventMessage::fromJson($string); $tag = $jsonMessage->getTag(); if (array_key_exists($tag, $deferreds)) { $deferred = $deferreds[$tag]; unset($deferreds[$tag]); if (array_key_exists($tag, $timers)) { $loop->cancelTimer($timers[$tag]); unset($timers[$tag]); } $deferred->resolve($jsonMessage); } else { $that->remoteEvent()->emit($jsonMessage->getEvent(), array($jsonMessage)); } $that->emit("message", array($jsonMessage)); } catch (\Exception $e) { $logger->err("Exception while parsing JsonMessage: " . $e->getMessage()); } }); }
/** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $context * @return null * @throws InvalidArgumentException if log level is not recognized */ public function log($level, $message, array $context = []) { if (!array_key_exists($level, $this->psrPriorityMap)) { throw new InvalidArgumentException(sprintf('$level must be one of PSR-3 log levels; received %s', var_export($level, 1))); } $priority = $this->psrPriorityMap[$level]; $this->logger->log($priority, $message, $context); }
/** * @param string $message */ public function logDebug($message) { if (!is_null($this->getLogger())) { $this->logger->debug($message); } if (!is_null($this->getConsoleOutput())) { $this->consoleOutput->writeln("<info>>>> " . $message . "</info>"); } }
/** * @param string $messageBody * @param array $attributes * @param array $options * @return MessageSentInterface */ public function sendMessage($messageBody, array $attributes = [], array $options = []) { $message = <<<EOT Send message called with : - Message : %s - Attributes : %s - Options : %s EOT; $this->logger->info(sprintf($message, $messageBody, json_encode($attributes), json_encode($options))); return (new Message())->setId('Fake received message')->setBody($messageBody)->setAttributes($attributes); }
/** * Manage database schema */ public function schemaManagerAction() { $request = $this->getRequest(); // Set up logger. Log level is already validated by route. $priority = \Zend\Filter\StaticFilter::execute($request->getParam('loglevel', 'info'), 'Library\\LogLevel'); $writer = new \Zend\Log\Writer\Stream('php://stderr'); $writer->addFilter('priority', array('priority' => $priority)); $writer->setFormatter('simple', array('format' => '%priorityName%: %message%')); $this->_logger->addWriter($writer); $this->_schemaManager->updateAll($request->getParam('prune')); }
/** * @param MvcEvent $event * @return void */ public function onError(MvcEvent $event) { if (!$this->options->getExceptionsLoggingEnabled()) { return; } $exception = $event->getParam('exception'); if (!$exception) { return; } $message = $exception->getFile() . ":" . $exception->getLine() . ": " . $exception->getMessage(); $this->logger->err($message, array('exception' => $exception)); }
private function onData($data) { try { $this->_lastChanged = time(); if ($this->_transport) { $this->emit('data', array($data, $this)); } else { $this->establishConnection($data); } } catch (Exception $e) { $this->logger->err("Error while handling incoming data. Exception message is: " . $e->getMessage()); $this->close(); } }
public function indexAction() { $userId = $this->params()->fromRoute('userId', null); try { $this->service->proceed($userId); $this->notification()->info('User email verified successfully. You need to set a password to log in.'); return $this->redirect()->toRoute('lang/my', array('action' => 'password')); } catch (Exception\UserNotFoundException $e) { $this->notification()->danger('User cannot be found'); } catch (\Exception $e) { $this->logger->crit($e); $this->notification()->danger('An unexpected error has occurred, please contact your system administrator'); } return $this->redirect()->toRoute('lang/register'); }
/** * @param string $command * @param [] $args * @return mixed */ protected function commit($command, array $args) { if ($this->logger) { $this->logger->debug(__CLASS__ . ' >> ' . $command, $args); } return $this->client->{$command}($args); }
public function setUp() { $configFile = __DIR__ . '/../../config.yml'; $value = Yaml::parse(file_get_contents($configFile)); $this->ariAddress = $value['tests']['ari_address']; $this->amiAddress = $value['tests']['ami_address']; $this->dialString = $value['tests']['dial_string']; $this->logger = new Log\Logger(); $logWriter = new Log\Writer\Stream("php://output"); $this->logger->addWriter($logWriter); $filter = new Log\Filter\SuppressFilter(true); //$filter = new Log\Filter\Priority(\Zend\Log\Logger::NOTICE); $logWriter->addFilter($filter); $this->client = new Phparia($this->logger); $this->client->connect($this->ariAddress, $this->amiAddress); }
/** * {@inheritdoc} */ public function report($priority, $message, $extra = []) { if ($this->log === null) { return; } switch ($priority) { case Logger::EMERG: $this->log->emerg($message, $extra); break; case Logger::ERR: $this->log->err($message, $extra); break; default: break; } }
/** * Connect to ARI. * * @param string $address Example ws://localhost:8088/ari/events?api_key=username:password&app=stasis_app_name */ public function connect($address) { $components = parse_url($address); $host = $components['host']; $port = $components['port']; $path = $components['path']; $query = $components['query']; $queryParts = []; parse_str($query, $queryParts); $this->stasisApplicationName = $queryParts['app']; $apiKey = $queryParts['api_key']; list($username, $password) = explode(':', $apiKey); $this->endpoint = new PestJSON('http://' . $host . ':' . $port . dirname($path)); $this->endpoint->setupAuth($username, $password, 'basic'); $this->wsClient = new WebSocket($address, $this->eventLoop, $this->logger); $this->wsClient->on("message", function (WebSocketMessage $rawMessage) { $message = new Message($rawMessage->getData()); $eventType = '\\phparia\\Events\\' . $message->getType(); if (class_exists($eventType)) { $event = new $eventType($this, $rawMessage->getData()); } else { $this->logger->warn("Event: '{$eventType}' not implemented"); // @todo Create a generic event for any that are not implemented return; } // Emit the specific event (just to get it back to where it came from) if ($event instanceof IdentifiableEventInterface) { $this->logger->notice("Emitting ID event: {$event->getEventId()}"); $this->wsClient->emit($event->getEventId(), array('event' => $event)); } // Emit the general event $this->logger->notice("Emitting event: {$message->getType()}"); $this->wsClient->emit($message->getType(), array('event' => $event)); }); }
/** * Connect to AMI and start emitting events. * * @param string $address Example uaername:password@localhost:5038 * @return \React\Promise\Promise */ public function connect($address) { $factory = new Factory($this->eventLoop); return $factory->createClient($address)->then(function (Client $client) { $this->amiClient = $client; $this->actionSender = new ActionSender($client); $this->actionSender->events(true); $client->on('close', function () { $this->logger->debug('AMI connection closed'); }); $client->on('event', function (Event $event) { $this->wsClient->emit($event->getName(), (array) $event); }); }, function (\Exception $e) { $this->logger->err('Connection error: ' . $e->getMessage()); }); }
/** * Print a message if debug is enabled. * * @param string $msg Message to print * * @return void */ protected function debugPrint($msg) { if ($this->logger) { $this->logger->debug("{$msg}\n"); } else { parent::debugPrint($msg); } }
public function indexAction() { $userId = $this->params()->fromRoute('userId', null); $token = $this->params()->fromRoute('token', null); try { $this->service->proceed($userId, $token); return $this->redirect()->toRoute('lang/my', array('action' => 'password')); } catch (Exception\TokenExpirationDateExpiredException $e) { $this->notification()->danger('Cannot proceed, token expired'); } catch (Exception\UserNotFoundException $e) { $this->notification()->danger('User cannot be found for specified token'); } catch (\Exception $e) { $this->logger->crit($e); $this->notification()->danger('An unexpected error has occurred, please contact your system administrator'); } return $this->redirect()->toRoute('lang/forgot-password'); }
public function receive(callable $callback, callable $error) { $should_close = false; $this->client->on('request', function () { $this->logger->notice('Request object created!'); }); $this->client->on('handshake', function () { $this->logger->notice('Handshake received!'); }); $this->client->on('connect', function () { $this->logger->notice('Connected!'); }); $this->client->on('error', function () use($error) { // Call the error callback. $error(); // Reopen the connection. $this->client->close(); $this->client->open(self::TIMEOUT); }); $this->client->on('close', function () use($should_close) { // Reopen the connection. if (!$should_close) { $this->client->open(self::TIMEOUT); } }); $this->client->on('message', function (WebSocketMessageInterface $message) use($callback, &$should_close) { // Wait for the message to be finalized. if (!$message->isFinalised()) { return; } // Get the contents. $contents = json_decode($message->getData(), true); if (!$contents) { return; } // Handle the contents. $value = $this->handleContents($contents); // Call the callback with the value. $result = $callback($value); // If the callback returns true, close the connection. if ($result === true) { $should_close = true; $this->client->close(); } }); }
/** * Logout * * Redirects To: Route 'home' */ public function logoutAction() { $auth = $this->auth; $this->logger->info('User ' . ($auth->getUser()->login == '' ? $auth->getUser()->info->displayName : $auth->getUser()->login) . ' logged out'); $auth->clearIdentity(); unset($_SESSION['HA::STORE']); $this->notification()->success('You are now logged out'); return $this->redirect()->toRoute('lang', array('lang' => $this->params('lang'))); }
public function indexAction() { if (!$this->options->getEnableRegistration()) { $this->notification()->info('Registration is disabled'); return $this->redirect()->toRoute('lang'); } /** @var \Zend\Http\Request $request */ $request = $this->getRequest(); $viewModel = new ViewModel(); try { if ($request->isPost()) { $this->form->setData($request->getPost()->toArray() ?: array()); if ($this->form->isValid()) { $mailer = $this->getPluginManager()->get('Mailer'); $url = $this->plugin('url'); // we cannot check reCaptcha twice (security protection) so we have to remove it $filter = $this->form->getInputFilter()->remove('captcha'); $this->service->proceed($filter, $mailer, $url); $this->notification()->success('An Email with an activation link has been sent, please try to check your email box'); $viewModel->setTemplate('auth/register/completed'); } else { $viewModel->setTemplate(null); $this->notification()->danger('Please fill form correctly'); } } else { /* @var $register \Zend\Form\Fieldset */ $register = $this->form->get('register'); $register->get('role')->setValue($this->params('role')); } } catch (Exception\UserAlreadyExistsException $e) { $this->notification()->danger('User with this email address already exists'); } catch (\Auth\Exception\UserDeactivatedException $e) { $this->notification()->danger('User with this email address already exists'); } catch (\Exception $e) { $this->logger->crit($e); $this->notification()->danger('An unexpected error has occurred, please contact your system administrator'); } $this->form->setAttribute('action', $this->url()->fromRoute('lang/register')); $viewModel->setVariable('form', $this->form); return $viewModel; }
/** * @param Event $e * @return void */ public function onNotify(Event $e) { /* @var $user \User\Entity\UserInterface */ $user = $e->getParam('user'); $notifications = $e->getParam('notifications'); if (!$notifications instanceof Collection) { $notifications = new ArrayCollection($notifications); } $subject = new ViewModel(); $body = new ViewModel(['user' => $user, 'notifications' => $notifications]); $subject->setTemplate('mailman/messages/notification/subject'); $body->setTemplate('mailman/messages/notification/body'); try { $subjectHtml = $this->getRenderer()->render($subject); $bodyHtml = $this->getRenderer()->render($body); $this->getMailman()->send($user->getEmail(), $this->getMailman()->getDefaultSender(), $subjectHtml, $bodyHtml); } catch (\Exception $e) { // TODO: Persist email and try resending it later $log = $this->exceptionToString($e); $this->logger->crit($log); var_dump($e->getMessage(), $e->getTraceAsString()); } }
/** * Generates the request url for querying the Google Geocoder API. * * @param string $address * @param string $format * @return string */ protected function generateRequestUrl($address, $format) { $url = self::GEOCODER_API_URI; $url .= $format; $queryParams = ['address' => $address]; $key = $this->getKey(); if (null != $key) { $queryParams['key'] = $key; } $queryString = http_build_query($queryParams); $url .= '?' . $queryString; if (true === isset($queryParams['key'])) { $queryParams['key'] = mb_substr($key, 0, 2) . str_repeat('x', strlen($key) - 4) . mb_substr($key, -2); $queryString = http_build_query($queryParams); } $this->logger->debug(sprintf('Generated url: %s.', self::GEOCODER_API_URI . '?' . $queryString)); return $url; }
public function testSpecifyingLoggingThresholds() { $bridge = new ZendFrameworkTwoTimerBridge($this->log, array(1 => 'debug', 2 => 'warn', '3.5' => 'alert')); $this->log->expects($this->at(0))->method('debug')->with('fXmlRpc call took 0.1000000000s', array('xmlrpcMethod' => 'method', 'xmlrpcArguments' => array('arg1', 'arg2'))); $this->log->expects($this->at(1))->method('debug')->with('fXmlRpc call took 1.1000000000s', array('xmlrpcMethod' => 'method', 'xmlrpcArguments' => array('arg1', 'arg2'))); $this->log->expects($this->at(2))->method('warn')->with('fXmlRpc call took 2.5000000000s', array('xmlrpcMethod' => 'method', 'xmlrpcArguments' => array('arg1', 'arg2'))); $this->log->expects($this->at(3))->method('alert')->with('fXmlRpc call took 3.5000000000s', array('xmlrpcMethod' => 'method', 'xmlrpcArguments' => array('arg1', 'arg2'))); $this->log->expects($this->at(4))->method('alert')->with('fXmlRpc call took 5.5000000000s', array('xmlrpcMethod' => 'method', 'xmlrpcArguments' => array('arg1', 'arg2'))); $bridge->recordTiming(0.1, 'method', array('arg1', 'arg2')); $bridge->recordTiming(1.1, 'method', array('arg1', 'arg2')); $bridge->recordTiming(2.5, 'method', array('arg1', 'arg2')); $bridge->recordTiming(3.5, 'method', array('arg1', 'arg2')); $bridge->recordTiming(5.5, 'method', array('arg1', 'arg2')); }
public function __construct($server, LoggerInterface $logger) { $this->server = $server; $this->logger = $logger; $this->handlers = new \SplObjectStorage(); $this->membership = new \SplObjectStorage(); /** * @var $membership \SplObjectStorage|WebSocketUriHandlerInterface[] */ $membership = $this->membership; $that = $this; $server->on("connect", function (WebSocketTransportInterface $client) use($that, $logger, $membership) { $handler = $that->matchConnection($client); if ($handler) { $logger->notice("Added client {$client->getId()} to " . get_class($handler)); $membership->attach($client, $handler); $handler->emit("connect", array("client" => $client)); $handler->addConnection($client); } else { $logger->err("Cannot route {$client->getId()} with request uri {$client->getHandshakeRequest()->getUriString()}"); } }); $server->on('disconnect', function (WebSocketTransportInterface $client) use($that, $logger, $membership) { if ($membership->contains($client)) { $handler = $membership[$client]; $membership->detach($client); $logger->notice("Removed client {$client->getId()} from" . get_class($handler)); $handler->removeConnection($client); $handler->emit("disconnect", array("client" => $client)); } else { $logger->warn("Client {$client->getId()} not attached to any handler, so cannot remove it!"); } }); $server->on("message", function (WebSocketTransportInterface $client, WebSocketMessageInterface $message) use($that, $logger, $membership) { if ($membership->contains($client)) { $handler = $membership[$client]; $handler->emit("message", compact('client', 'message')); } else { $logger->warn("Client {$client->getId()} not attached to any handler, so cannot forward the message!"); } }); }
/** * Logs a message using the logger. * * @param string $message */ public function warn($message) { if (isset($this->logger)) { $this->logger->warn($message); } }
/** * @param EventInterface $event */ public function onError(EventInterface $event) { if ($exception = $event->getParam('exception')) { $this->logger->err($exception); } }
public function execute(MvcEvent $e) { if ($exception = $e->getParam('exception')) { $this->logger->crit($exception); } }
/** * Start the server */ public function bind() { $err = $errno = 0; $this->flashPolicyFile = str_replace('to-ports="*', 'to-ports="' . $this->uri->getPort() ?: 80, $this->flashPolicyFile); $serverSocket = stream_socket_server($this->uri->toString(), $errno, $err, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $this->context); $this->logger->notice(sprintf("phpws listening on %s", $this->uri->toString())); if ($serverSocket == false) { $this->logger->err("Error: {$err}"); return; } $timeOut =& $this->purgeUserTimeOut; $sockets = $this->streams; $that = $this; $logger = $this->logger; $this->loop->addReadStream($serverSocket, function ($serverSocket) use($that, $logger, $sockets) { $newSocket = stream_socket_accept($serverSocket); if (false === $newSocket) { return; } stream_set_blocking($newSocket, 0); $client = new WebSocketConnection($newSocket, $that->loop, $logger); $sockets->attach($client); $client->on("handshake", function (Handshake $request) use($that, $client) { $that->emit("handshake", [$client->getTransport(), $request]); }); $client->on("connect", function () use($that, $client, $logger) { $con = $client->getTransport(); $that->getConnections()->attach($con); $that->emit("connect", ["client" => $con]); }); $client->on("message", function ($message) use($that, $client, $logger) { $connection = $client->getTransport(); $that->emit("message", ["client" => $connection, "message" => $message]); }); $client->on("close", function () use($that, $client, $logger, &$sockets, $client) { $sockets->detach($client); $connection = $client->getTransport(); if ($connection) { $that->getConnections()->detach($connection); $that->emit("disconnect", ["client" => $connection]); } }); $client->on("flashXmlRequest", function () use($that, $client) { $client->getTransport()->sendString($that->flashPolicyFile); $client->close(); }); }); $this->loop->addPeriodicTimer(5, function () use($timeOut, $sockets, $that) { # Lets send some pings foreach ($that->getConnections() as $c) { if ($c instanceof WebSocketTransportHybi) { $c->sendFrame(WebSocketFrame::create(WebSocketOpcode::PING_FRAME)); } } $currentTime = time(); if ($timeOut == null) { return; } foreach ($sockets as $s) { if ($currentTime - $s->getLastChanged() > $timeOut) { $s->close(); } } }); }
/** * Show a debug message. * * @param string $msg Debug message. * * @return void */ protected function debug($msg) { if ($this->logger) { $this->logger->debug($msg); } }
/** * Log information about a database query * @param \Application\Service\EventInterface $e */ public function logQuery(EventInterface $e) { $text = $e->getParam('query'); $this->logger->debug($text); }