public function onBootstrap(MvcEvent $e) { if (\Zend\Console\Console::isConsole()) { return; } $eventManager = $e->getApplication()->getEventManager(); $services = $e->getApplication()->getServiceManager(); // TODO: Löschen sobald die Lösung mit der LoginBox klappt //$eventManager->attach( // array(MvcEvent::EVENT_RENDER, MvcEvent::EVENT_RENDER_ERROR), // array(new InjectLoginInfoListener(), 'injectLoginInfo'), -1000 //); $eventManager->attach(MvcEvent::EVENT_ROUTE, function (MvcEvent $e) use($services) { /** @var CheckPermissionsListener $checkPermissionsListener */ $checkPermissionsListener = $services->get('Auth/CheckPermissionsListener'); $checkPermissionsListener->onRoute($e); }, -10); $eventManager->attach(MvcEvent::EVENT_DISPATCH, function (MvcEvent $e) use($services) { /** @var CheckPermissionsListener $checkPermissionsListener */ $checkPermissionsListener = $services->get('Auth/CheckPermissionsListener'); $checkPermissionsListener->onDispatch($e); }, 10); $unauthorizedAccessListener = $services->get('UnauthorizedAccessListener'); $unauthorizedAccessListener->attach($eventManager); $sharedManager = $eventManager->getSharedManager(); $defaultlistener = $services->get('Auth/Listener/AuthAggregateListener'); $defaultlistener->attachShared($sharedManager); }
public function onBootstrap(MvcEvent $mvcEvent) { if (Console::isConsole()) { return; } $application = $mvcEvent->getApplication(); $serviceLocator = $application->getServiceManager(); $strategy = $serviceLocator->get(AccessListener::class); $eventManager = $application->getEventManager(); $strategy->attach($eventManager); // try { // $remote = new RemoteAddress; // $remote->setUseProxy(true); // $mapper = $serviceManager->get(UserAuthenticationLogMapper::class); // $logEntity = new UserAuthenticationLog( // $authEvent->getIdentity(), // new \DateTime("now"), // $remote->getIpAddress() // ); // $mapper->save($logEntity); // // } catch (\Exception $x) { // // } // }); }
/** * Construct the cookie manager. * * @param ServiceManager $sm Service manager. * * @return \VuFind\Cookie\CookieManager */ public static function getCookieManager(ServiceManager $sm) { if (Console::isConsole()) { return false; } return parent::getCookieManager($sm); }
/** * Create and return the router * * Retrieves the "router" key of the Config service, and uses it * to instantiate the router. Uses the TreeRouteStack implementation by * default. * * @param ServiceLocatorInterface $serviceLocator * @param string|null $cName * @param string|null $rName * @return \Zend\Mvc\Router\RouteStackInterface */ public function createService(ServiceLocatorInterface $serviceLocator, $cName = null, $rName = null) { $config = $serviceLocator->get('Config'); $routePluginManager = $serviceLocator->get('RoutePluginManager'); if ($rName === 'ConsoleRouter' || $cName === 'router' && Console::isConsole()) { // We are in a console, use console router. if (isset($config['console']) && isset($config['console']['router'])) { $routerConfig = $config['console']['router']; } else { $routerConfig = array(); } $router = new ConsoleRouter($routePluginManager); } else { // This is an HTTP request, so use HTTP router $router = new HttpRouter($routePluginManager); $routerConfig = isset($config['router']) ? $config['router'] : array(); } if (isset($routerConfig['route_plugins'])) { $router->setRoutePluginManager($routerConfig['route_plugins']); } if (isset($routerConfig['routes'])) { $router->addRoutes($routerConfig['routes']); } if (isset($routerConfig['default_params'])) { $router->setDefaultParams($routerConfig['default_params']); } return $router; }
public function onBootstrap(MvcEvent $e) { $app = $e->getApplication(); $eventManager = $app->getEventManager(); $sm = $app->getServiceManager(); // initialize SessionManager $this->bootstrapSession($e); // Attach UserListener for role and UserProfile handling $listener = $sm->get(UserListener::class); $eventManager->attach($listener); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'initTranslator'), -100); $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'setUserLanguage')); // Enable BjyAuthorize when not in console mode if (!\Zend\Console\Console::isConsole()) { // Add ACL information to the Navigation view helper $authorize = $sm->get(Authorize::class); $acl = $authorize->getAcl(); $role = $authorize->getIdentity(); Navigation::setDefaultAcl($acl); Navigation::setDefaultRole($role); } /* @var $translator \Zend\I18n\Translator\Translator */ $translator = $e->getApplication()->getServiceManager()->get('MvcTranslator'); // add Db Loader factory $translator->getPluginManager()->setFactory(I18n\Translator\Loader\Db::class, I18n\Translator\Loader\Factory\DbFactory::class); if ($e->getRouter() instanceof \Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack) { $e->getRouter()->setTranslator($translator); } }
/** * @param ContainerInterface $container * @return ConsoleRequest|HttpRequest */ public function __invoke(ContainerInterface $container) { if (Console::isConsole()) { return new ConsoleRequest(); } return new HttpRequest(); }
public function onBootstrap(MvcEvent $e) { if (\Zend\Console\Console::isConsole()) { return; } $eventManager = $e->getApplication()->getEventManager(); $services = $e->getApplication()->getServiceManager(); $eventManager->attach(MvcEvent::EVENT_ROUTE, function (MvcEvent $e) use($services) { /* @var $checkPermissionsListener \Acl\Listener\CheckPermissionsListener */ $checkPermissionsListener = $services->get('Auth/CheckPermissionsListener'); $checkPermissionsListener->onRoute($e); }, -10); $eventManager->attach(MvcEvent::EVENT_DISPATCH, function (MvcEvent $e) use($services) { /** @var CheckPermissionsListener $checkPermissionsListener */ $checkPermissionsListener = $services->get('Auth/CheckPermissionsListener'); $checkPermissionsListener->onDispatch($e); }, 10); $unauthorizedAccessListener = $services->get('UnauthorizedAccessListener'); $unauthorizedAccessListener->attach($eventManager); $deactivatedUserListener = $services->get('DeactivatedUserListener'); $deactivatedUserListener->attach($eventManager); $sharedManager = $eventManager->getSharedManager(); $defaultlistener = $services->get('Auth/Listener/AuthAggregateListener'); $defaultlistener->attachShared($sharedManager); $socialProfilesUnconfiguredErrorListener = new SocialProfilesUnconfiguredErrorListener(); $socialProfilesUnconfiguredErrorListener->attach($eventManager); }
/** * Return a ConsoleViewManager if in a Console environment. * * @param ContainerInterface $container * @param string $name * @param callable $callback * @param null|array $options * @return \Zend\Mvc\Console\View\ViewManager|Zend\Mvc\View\Http\ViewManager */ public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null) { if (!Console::isConsole() || !$container->has('ConsoleViewManager')) { return $callback(); } return $container->get('ConsoleViewManager'); }
public function passwordAction() { $request = $this->getRequest(); // Make sure that we are running in a console and the user has not // tricked our // application into running this action from a public web server. if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Get user email from console and check if the user used --verbose or // -v flag $userEmail = $request->getParam('userEmail'); $verbose = $request->getParam('verbose'); // reset new password $newPassword = Rand::getString(16); $console = Console::getInstance(); if (Confirm::prompt('Is this the correct answer? [y/n]', 'y', 'n')) { $console->write("You chose YES\n"); } else { $console->write("You chose NO\n"); } if (!$verbose) { return "Done! {$userEmail} has received an email with his new password.\n"; } else { return "Done! New password for user {$userEmail} is '{$newPassword}'. It has also been emailed to him. \n"; } }
public static function getIP($just_remote = true) { if (Console::isConsole()) { return '127.0.0.1'; } // O único realmente seguro de se confiar é o REMOTE_ADDR $validator = new \Zend\Validator\Ip(); $remote = $_SERVER['REMOTE_ADDR']; if (!$validator->isValid($remote)) { throw new \RuntimeException("Endereço de IP '{$remote}' inválido"); } if ($just_remote) { return $remote; } $ips = [$remote]; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; if ($validator->isValid($ip)) { $ips[2] = $ip; } } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; if ($validator->isValid($ip)) { $ips[1] = $ip; } } return $ips; }
/** * Create and return a request instance, according to current environment. * * @param ServiceLocatorInterface $serviceLocator * @return ConsoleRequest|HttpRequest */ public function createService(ServiceLocatorInterface $serviceLocator) { if (Console::isConsole()) { return new ConsoleRequest(); } return new HttpRequest(); }
/** * Create and return a request instance, according to current environment. * * @param \Zend\ServiceManager\ServiceLocatorInterface $services * @return ConsoleRequest|HttpRequest */ public function __invoke($services) { if (Console::isConsole()) { return new ConsoleRequest(); } return new HttpRequest(); }
/** * Create and return a request instance, according to current environment. * * @param ServiceLocatorInterface $serviceLocator * @return HttpViewManager */ public function createService(ServiceLocatorInterface $serviceLocator) { if (Console::isConsole()) { return new ConsoleViewManager(); } return new HttpViewManager(); }
/** * Create and return the view manager for the console environment * * @param ServiceLocatorInterface $serviceLocator * @return ConsoleViewManager */ public function createService(ServiceLocatorInterface $serviceLocator) { if (!Console::isConsole()) { throw new ServiceNotCreatedException('ConsoleViewManager requires a Console environment; console environment not detected'); } return new ConsoleViewManager(); }
/** * * @return ConsoleAdapter */ public function getConsoleAdapter() { if (null === $this->consoleAdapter) { $this->consoleAdapter = Console::getInstance(); } return $this->consoleAdapter; }
/** * Логгируем информацию об исключении * * @param \Exception $e */ public function logException(\Exception $e) { do { $context = Console::isConsole() ? $_ENV : $_SERVER; $this->getLogger()->crit($e->__toString(), ['context' => print_r($context, true)]); } while ($e = $e->getPrevious()); }
/** * Initialize the application * * Creates a RouteCollection and populates it with the $routes provided. * * Sets the banner to call showVersion(). * * If no help command is defined, defines one. * * If no version command is defined, defines one. * * @param string $name Application name * @param string $version Application version * @param array|Traversable $routes Routes/route specifications to use for the application * @param Console $console Console adapter to use within the application * @param Dispatcher $dispatcher Configured dispatcher mapping routes to callables */ public function __construct($name, $version, $routes, Console $console = null, Dispatcher $dispatcher = null) { if (!is_array($routes) && !$routes instanceof Traversable) { throw new InvalidArgumentException('Routes must be provided as an array or Traversable object'); } $this->name = $name; $this->version = $version; if (null === $console) { $console = DefaultConsole::getInstance(); } $this->console = $console; if (null === $dispatcher) { $dispatcher = new Dispatcher(); } $this->dispatcher = $dispatcher; $this->routeCollection = $routeCollection = new RouteCollection(); $this->setRoutes($routes); $this->banner = [$this, 'showVersion']; if (!$routeCollection->hasRoute('help')) { $this->setupHelpCommand($routeCollection, $dispatcher); } if (!$routeCollection->hasRoute('version')) { $this->setupVersionCommand($routeCollection, $dispatcher); } if (!$routeCollection->hasRoute('autocomplete')) { $this->setupAutocompleteCommand($routeCollection, $dispatcher); } }
/** * Create and return a Console adapter instance. * In case we're not in a Console environment, return a dummy stdClass object. * * In order to disable adapter auto-detection and use a specific adapter (and charset), * add the following fields to application configuration, for example: * * 'console' => array( * 'adapter' => 'MyConsoleAdapter', // always use this console adapter * 'charset' => 'MyConsoleCharset', // always use this console charset * ), * 'service_manager' => array( * 'invokables' => array( * 'MyConsoleAdapter' => 'Zend\Console\Adapter\Windows', * 'MyConsoleCharset' => 'Zend\Console\Charset\DESCG', * ) * ) * * @param ServiceLocatorInterface $serviceLocator * @return AdapterInterface|stdClass */ public function createService(ServiceLocatorInterface $serviceLocator) { // First, check if we're actually in a Console environment if (!Console::isConsole()) { // SM factory cannot currently return null, so we return dummy object return new stdClass(); } // Read app config and determine Console adapter to use $config = $serviceLocator->get('Config'); if (!empty($config['console']) && !empty($config['console']['adapter'])) { // use the adapter supplied in application config $adapter = $serviceLocator->get($config['console']['adapter']); } else { // try to detect best console adapter $adapter = Console::detectBestAdapter(); $adapter = new $adapter(); } // check if we have a valid console adapter if (!$adapter instanceof AdapterInterface) { // SM factory cannot currently return null, so we convert it to dummy object return new stdClass(); } // Optionally, change Console charset if (!empty($config['console']) && !empty($config['console']['charset'])) { // use the charset supplied in application config $charset = $serviceLocator->get($config['console']['charset']); $adapter->setCharset($charset); } return $adapter; }
/** * Create and return a view manager based on detected environment * * @param ServiceLocatorInterface $serviceLocator * @return ConsoleViewManager|HttpViewManager */ public function createService(ServiceLocatorInterface $serviceLocator) { if (Console::isConsole()) { return $serviceLocator->get('ConsoleViewManager'); } return $serviceLocator->get('HttpViewManager'); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $serviceManager = $e->getApplication()->getServiceManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); if (!Console::isConsole()) { $viewHelperManager = $serviceManager->get('ViewHelperManager'); $formElementErrors = $viewHelperManager->get('formElementErrors'); $formElementErrors->setMessageOpenFormat('<div class="zui-error">'); $formElementErrors->setMessageSeparatorString('</div><div class="zui-error">'); $formElementErrors->setMessageCloseString('</div>'); $flashMessenger = $viewHelperManager->get('flashMessenger'); $flashMessenger->setMessageOpenFormat('<div class="zui-alert zui-alert-%s"><p>'); $flashMessenger->setMessageSeparatorString('</p><p>'); $flashMessenger->setMessageCloseString('</p><span class="zui-icon zui-icon-x" role="button" tabindex="0"></span></div>'); /** @var ManagerInterface $sessionManager */ $sessionManager = $serviceManager->get(ManagerInterface::class); $sessionManager->start(); } $helpers = $serviceManager->get('ViewHelperManager'); $hal = $helpers->get('Hal'); $hal->getEventManager()->attach('renderCollection.post', [$this, 'onRenderCollection']); $hal->getEventManager()->attach('renderEntity.post', [$this, 'onRenderEntity']); }
/** * Return console adapter to use when showing prompt. * * @return ConsoleAdapter */ public function getConsole() { if (!$this->console) { $this->console = Console::getInstance(); } return $this->console; }
/** * @param ContainerInterface $container * @param string $name * @param callable $callback * @param null|array $options * @return ConsoleRequest|\Zend\Http\Request */ public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null) { if (!Console::isConsole()) { return $callback(); } return new ConsoleRequest(); }
/** * Initialize the module * * @param ModuleManager $m Module manager * * @return void */ public function init(ModuleManager $m) { if (!Console::isConsole()) { $em = StaticEventManager::getInstance(); $em->attach('Zend\\Mvc\\Application', 'bootstrap', [$this, 'registerBaseUrl'], 100000); } }
/** * Creates all needed classes and fills them with random data */ public function installAction() { Time::check(); $this->createTables(); Console::getInstance()->writeLine('Tables created in ' . Time::check() . ' sec.'); $pupilService = $this->getPupilService(); $count = $this->generateItems($pupilService, $this->getRequest()->getParam('pupils', 100000), ['email', 'birthday'], function ($item) { return ['name' => $item['full'], 'email' => $item['email'], 'birthday' => $item['birthday'], 'level' => \Application\Entity\Pupil::$levels[rand(0, 5)]]; }); Console::getInstance()->writeLine($count . ' pupils generated in ' . Time::check() . ' sec.'); $teachersCount = $this->getRequest()->getParam('teachers', 10000); $teacherService = $this->getTeacherService(); $this->generateItems($teacherService, $teachersCount, ['phone'], function ($item) { $gender = $item['gender'] === \NameGenerator\Gender::GENDER_MALE ? TeacherEntity::GENDER_MALE : TeacherEntity::GENDER_FEMALE; return ['gender' => $gender, 'name' => $item['full'], 'phone' => $item['phone']]; }); Console::getInstance()->writeLine($teachersCount . ' teachers generated in ' . Time::check() . ' sec.'); $pupilMaxId = $pupilService->getMaxId(); $teacherMaxId = $teacherService->getMaxId(); $teacherPupilService = $this->getTeacherPupilService(); $linksCount = 0; for ($teacherId = 1; $teacherId < $teacherMaxId; $teacherId++) { $except = []; for ($j = 0; $j < rand(0, 3); $j++) { $pupil_id = rand(0, $pupilMaxId); if (in_array($pupil_id, $except)) { continue; } $except[] = $pupil_id; $teacherPupilService->insert(['teacher_id' => $teacherId, 'pupil_id' => $pupil_id]); $linksCount++; } } Console::getInstance()->writeLine($linksCount . ' links generated in ' . Time::check() . ' sec.'); }
/** * Create and return the router * * Retrieves the "router" key of the Config service, and uses it * to instantiate the router. Uses the TreeRouteStack implementation by * default. * * @param ServiceLocatorInterface $serviceLocator * @param string|null $cName * @param string|null $rName * @return \Zend\Mvc\Router\RouteStackInterface */ public function createService(ServiceLocatorInterface $serviceLocator, $cName = null, $rName = null) { $config = $serviceLocator->has('Config') ? $serviceLocator->get('Config') : array(); // Defaults $routerClass = 'Zend\\Mvc\\Router\\Http\\TreeRouteStack'; $routerConfig = isset($config['router']) ? $config['router'] : array(); // Console environment? if ($rName === 'ConsoleRouter' || $cName === 'router' && Console::isConsole()) { // We are in a console, use console router defaults. $routerClass = 'Zend\\Mvc\\Router\\Console\\SimpleRouteStack'; $routerConfig = isset($config['console']['router']) ? $config['console']['router'] : array(); } // Obtain the configured router class, if any if (isset($routerConfig['router_class']) && class_exists($routerConfig['router_class'])) { $routerClass = $routerConfig['router_class']; } // Inject the route plugins if (!isset($routerConfig['route_plugins'])) { $routePluginManager = $serviceLocator->get('RoutePluginManager'); $routerConfig['route_plugins'] = $routePluginManager; } // Obtain an instance $factory = sprintf('%s::factory', $routerClass); return call_user_func($factory, $routerConfig); }
/** * Create and return the view manager for the console environment * * @param ContainerInterface $container * @param string $name * @param null|array $options * @return ConsoleViewManager */ public function __invoke(ContainerInterface $container, $name, array $options = null) { if (!Console::isConsole()) { throw new ServiceNotCreatedException('ConsoleViewManager requires a Console environment; console environment not detected'); } return new ConsoleViewManager(); }
/** * Create console instance for color output of success/failure * messages. * * @param ConsoleAdapter $console */ public function __construct(ConsoleAdapter $console = null) { if (null === $console) { $this->console = Console::getInstance(); } else { $this->console = $console; } }
/** * @param ContainerInterface $container * @param string $name * @param callable $callback * @param null|array $options * @return HelperPluginManager */ public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null) { $plugins = $callback(); if (!Console::isConsole()) { return $plugins; } return $this->injectOverrideFactories($plugins, $container); }
public function __construct() { $routes = [['name' => '<config> <output_file> [--strip]', 'short_description' => "Generate class cache based on <config> file into <output_file>.", 'handler' => [$this, 'generateDump']]]; parent::__construct('Cache dumper', 1.0, $routes, Console::getInstance()); $this->removeRoute('autocomplete'); $this->removeRoute('help'); $this->removeRoute('version'); }
/** * @param MvcEvent $e * @return void|ViewModel */ public function handleDispatchErrors(MvcEvent $e) { $exception = $e->getParam('exception'); $routeMatch = $e->getRouteMatch(); if (!$routeMatch || $exception instanceof UnauthorizedException) { // We don't handle permissions errors or unmatched routes return; } // We will do the final handling here $e->stopPropagation(); if (Console::isConsole()) { return; } $error = $e->getError(); $model = new ViewModel( [ 'message' => 'An error occurred. Good luck!<br/><br/><pre>' . $exception->getMessage() . '</pre>', 'reason' => $error, 'exception' => $exception, ] ); $model->setTemplate('error/404'); $e->getViewModel()->addChild($model); $response = $e->getResponse(); $response->setStatusCode(404); return $model; }