Perform content negotiation by looking the the current URL and the Accept request header

@param EventInterface $event The event instance
509805
public function negotiate(EventInterface $event) {
        $request = $event->getRequest();
        $response = $event->getResponse();

        $formatter = null;
        $extension = $request->getExtension();
        $routeName = (string) $request->getRoute();
        $config = $event->getConfig();
        $contentNegotiateImages = $config['contentNegotiateImages'];
        $model = $response->getModel();
        $outputConverterManager = $event->getOutputConverterManager();
        $supportedTypes = array_merge($this->supportedTypes, $outputConverterManager->getMimeTypeToExtensionMap());
        $extensionsToMimeType = array_merge($this->extensionsToMimeType, $outputConverterManager->getExtensionToMimeTypeMap());

        // Populate the supported image types for this event
        $this->modelTypes['image'] = $outputConverterManager->getSupportedMimeTypes();

        if (!$extension && !$contentNegotiateImages && $model instanceof Model\Image) {
            // Configuration is telling us not to use content negotiation for images,
            // instead we want to use the original format of the image
            $formatter = $model->getExtension();
        } else if ($extension && !($model instanceof Model\Error && ($routeName === 'image' || $routeName === 'globalshorturl'))) {
            // The user agent wants a specific type. Skip content negotiation completely, but not
            // if the request is against the image resource (or the global short url resource), and
            // ended up as an error, because then Imbo would try to render the error as an image.
            $mime = $this->defaultMimeType;

            if (isset($extensionsToMimeType[$extension])) {
                $mime = $extensionsToMimeType[$extension];
            } else if ($model instanceof Model\Image) {
                // If the request is for an image, but we don't support the extension - give a 404 like the old router did.
                throw new Exception\RuntimeException('Not Found', 404);
            }

            $formatter = $supportedTypes[$mime];
        } else {
            // Set Vary to Accept since we are doing content negotiation based on Accept
            $response->setVary('Accept', false);

            // No extension have been provided
            $acceptableTypes = [];

            foreach (AcceptHeader::fromString($request->headers->get('Accept', '*/*'))->all() as $item) {
                $acceptableTypes[$item->getValue()] = $item->getQuality();
            }

            $match = false;
            $maxQ = 0;

            // Specify which types to check for since all models can't be formatted by all
            // formatters
            $modelClass = get_class($model);
            $modelType = strtolower(substr($modelClass, strrpos($modelClass, '\\') + 1));

            $types = $this->defaultModelTypes;

            if (isset($this->modelTypes[$modelType])) {
                $types = $this->modelTypes[$modelType];
            }

            // If we are dealing with images we want to make sure the original mime type of the
            // image is checked first. If the client does not really have any preference with
            // regards to the mime type (*/* or image/*) this results in the original mime type of
            // the image being sent.
            if ($model instanceof Model\Image) {
                $original = $model->getMimeType();

                if ($types[0] !== $original) {
                    $types = array_filter($types, function($type) use ($original) {
                        return $type !== $original;
                    });

                    // if the current pipeline hasn't performed any transformations, we can output the original format, even if it's not supported as a output converter.
                    // otherwise, if we support the original format, we use it
                    if (
                        !$event->getTransformationManager()->hasAppliedTransformations() ||
                        $outputConverterManager->supportsExtension($model->getExtension())
                    ) {
                        array_unshift($types, $original);
                        $supportedTypes[$original] = $model->getExtension();
                    }
                }
            }

            foreach ($types as $mime) {
                if (($q = $this->contentNegotiation->isAcceptable($mime, $acceptableTypes)) && ($q > $maxQ)) {
                    $maxQ = $q;
                    $match = true;
                    $formatter = $supportedTypes[$mime];
                }
            }

            if (!$match && !$event->hasArgument('noStrict')) {
                // No types matched with strict mode enabled. The client does not want any of Imbo's
                // supported types. Y U NO ACCEPT MY TYPES?! FFFFUUUUUUU!
                throw new Exception\RuntimeException('Not acceptable', 406);
            } else if (!$match) {
                // There was no match but we don't want to be an ass about it. Send a response
                // anyway (allowed according to RFC2616, section 10.4.7)
                $formatter = $supportedTypes[$this->defaultMimeType];
            }
        }

        $this->formatter = $formatter;
    }
821996
public function remove(EventInterface $event)
    {
        foreach ($this->events as $key => $internalEvent) {
            if ($event->getUid() === $internalEvent->getUid()) {
                unset($this->events[$key]);
            }
        }
    }
952273
public function subscribe(EventInterface $event) {
        $events = [];

        // Enable the event listener only for resources and methods specified
        foreach ($this->params['allowedMethods'] as $resource => $methods) {
            foreach ($methods as $method) {
                $eventName = $resource . '.' . strtolower($method);
                $events[$eventName] = ['invoke' => 1000];
            }

            // Always enable the listener for the OPTIONS method
            $eventName = $resource . '.options';
            $events[$eventName] = ['options' => 20];
        }

        $manager = $event->getManager();
        $manager->addCallbacks($event->getHandler(), $events);

        // Add OPTIONS to the Allow header
        $event->getResponse()->headers->set('Allow', 'OPTIONS', false);
    }
1001697
public function subscribe(EventInterface $event) {
        $resources = Resource::getAllResources();

        if ($this->params['additionalResources']) {
            $resources = array_merge($resources, $this->params['additionalResources']);
        }

        $events = [];
        foreach ($resources as $resource) {
            $events[$resource] = ['checkAccess' => 500];
        }

        $manager = $event->getManager();
        $manager->addCallbacks($event->getHandler(), $events);
    }
524794
public function onVote(EventInterface $event)
    {
        $repository = $this->repositoryResolver->getRepositoryForEvent($event);

        if (!$repository) {
            return;
        }

        $vote = $repository->countByReferenceAndByIp($event->getReference(), $event->getRequest()->getClientIp());

        if ($vote >= $this->maxNumber) {
            $event->stopPropagation();
        }
    }
1263276
public function handle(EventInterface $event)
    {

        try {
            // load the application server and the naming directory instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */
            $namingDirectory = $applicationServer->getNamingDirectory();

            // initialize configuration and schema file name
            $configurationFileName = $applicationServer->getConfigurationFilename();

            // get an instance of our configuration tester
            $configurationService = new ConfigurationService(new InitialContext(new AppserverNode()));

            // load the parsed system configuration
            /** @var \DOMDocument $doc */
            $doc = $configurationService->loadConfigurationByFilename($configurationFileName);

            // validate the configuration file with the schema
            $configurationService->validateXml($doc, null, true);

            try {
                // query whether we're in configuration test mode or not
                if ($namingDirectory->search('php:env/args/t')) {
                    echo 'Syntax OK' . PHP_EOL;
                    exit(0);
                }

            } catch (NamingException $ne) {
                // do nothing, because we're NOT in configuration test mode
            }

            // initialize the SimpleXMLElement with the content XML configuration file
            $configuration = new Configuration();
            $configuration->initFromString($doc->saveXML());

            // initialize the configuration and the base directory
            $systemConfiguration = new AppserverNode();
            $systemConfiguration->initFromConfiguration($configuration);

            // re-initialize the container service with the real system configuration
            $configurationService->setSystemConfiguration($systemConfiguration);

            // then we can replace the system properties
            $properties = $configurationService->getSystemProperties();
            $systemConfiguration->replaceProperties($properties);

            // set the system configuration in the application server instance
            $applicationServer->setSystemConfiguration($systemConfiguration);

        } catch (\Exception $e) {
            // render the validation errors and exit immediately
            echo $e . PHP_EOL;
            exit(0);
        }
    }
1080875
public function onAfterRespond(Event $event)
    {
        /** @var ResponseInterface $response */
        $response = $event['response'];

        if (strpos($response->getHeaderLine('Content-Type'), 'html') === false) {
            DebuggerHelper::disableConsole();
        }
    }
451480
public function handle(EventInterface $event)
    {

        try {
            // load the application server and the naming directory instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */
            $namingDirectory = $applicationServer->getNamingDirectory();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // deploy the applications for all containers
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
            foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) {
                // load the container instance to deploy the applications for
                /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */
                $container = $namingDirectory->search(
                    sprintf(
                        'php:services/%s/%s',
                        $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK),
                        $containerNode->getName()
                    )
                );

                // iterate over all applications and shut them down
                /** @var \AppserverIo\Psr\Application\ApplicationInterface $application */
                foreach ($container->getApplications() as $application) {
                    $application->stop();
                }
            }

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
40397
public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // load the service instance and create the SSL file if not available
            /** @var \AppserverIo\Appserver\Core\Api\ContainerService $service */
            $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\ContainerService');
            $service->createSslCertificate(new \SplFileInfo($service->getConfDir(CreateSslCertificateListener::DEFAULT_CERTIFICATE_NAME)));

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
1272361
public function autoRotate(EventInterface $event) {
        $event->getTransformationManager()
            ->getTransformation('autoRotate')
            ->setImage($event->getRequest()->getImage())
            ->transform([]);
    }
1164474
protected function triggerHandlers(EventInterface $event)
    {
        foreach ($this->getHandlers($event->getName()) as $handler) {
            call_user_func($handler, $event);
            if ($event->isPropagationStopped()) {
                break;
            }
        }
    }
89185
public function handle(EventInterface $event)
    {
        try {
            $this->getApplicationServer()->getSystemLogger()->info($event->getName());
        } catch (\Exception $e) {
             $this->getApplicationServer()->getSystemLogger()->error($e->__toString());
        }
    }
1152172
public function setEvent(EventInterface $event)
    {
        $target = $this;

        if (!($event instanceof AuthenticationEvent)) {
            $eventParams = $event->getParams();
            $eventTarget = $event->getTarget();

            if ($eventTarget) {
                $target = $eventTarget;
            }

            $event = new AuthenticationEvent();

            $event->setParams($eventParams);
        }

        $event->setIdentity(null)->setTarget($target);

        $this->event = $event;

        return $this;
    }
816510
public function put(EventInterface $event) {
        $request = $event->getRequest();
        $metadata = json_decode($request->getContent(), true);

        $event->getManager()
            ->trigger('db.metadata.delete')
            ->trigger('db.metadata.update', [
                'metadata' => $metadata,
            ]);

        $model = new Model\Metadata();
        $model->setData($metadata);

        $event->getResponse()->setModel($model);
    }
1364726
public function getImage(EventInterface $event) {
        $request = $event->getRequest();
        $route = $request->getRoute();

        $params = $event->getDatabase()->getShortUrlParams($route->get('shortUrlId'));

        if (!$params) {
            throw new ResourceException('Image not found', 404);
        }

        $route->set('user', $params['user']);
        $route->set('imageIdentifier', $params['imageIdentifier']);
        $route->set('extension', $params['extension']);

        $request->query = new ParameterBag($params['query']);
        $event->getResponse()->headers->set('X-Imbo-ShortUrl', $request->getUri());
        $event->getManager()->trigger('image.get', ['skipAccessControl' => true]);
    }
427747
public function publish(EventInterface $event)
    {
        $commandsToDispatch = $this->eventBus->publish($event);

        $commands = $this->extractCommands($commandsToDispatch);
        foreach ($commands as $command) {
            $this->dispatch($command);
        }
    }
160921
public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // print a message with the old UID/EUID
            $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());

            // extract the variables
            $uid = 0;
            extract(posix_getpwnam('root'));

            // switcht the effective UID to the passed user
            if (posix_seteuid($uid) === false) {
                $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid));
            }

            // print a message with the new UID/EUID
            $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());

            // @TODO Switch group also!!!!

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }