Handle GET requests

@param EventInterface $event The current event
335756
public function get(EventInterface $event) {
        $response = $event->getResponse();
        $response->setMaxAge(0)
                 ->setPrivate();

        $response->headers->addCacheControlDirective('no-store');

        $event->getManager()->trigger('db.stats.load');
    }
570296
public function handle(EventInterface $event)
    {

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

            // unbind the loggers from the naming directory
            foreach (array_keys($applicationServer->getLoggers()) as $name) {
                $applicationServer->getNamingDirectory()->unbind(sprintf('php:global/log/%s', $name));
            }

            // set the initialized loggers finally
            $applicationServer->setLoggers(array());

        } catch (\Exception $e) {
            error_log($e->__toString());
        }
    }
999949
public function prepareImage(EventInterface $event) {
        $request = $event->getRequest();

        // Fetch image data from input
        $imageBlob = $request->getContent();

        if (empty($imageBlob)) {
            $e = new ImageException('No image attached', 400);
            $e->setImboErrorCode(Exception::IMAGE_NO_IMAGE_ATTACHED);

            throw $e;
        }

        // Fetch mime using finfo
        $mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($imageBlob);

        if (isset(Image::$mimeTypeMapping[$mime])) {
            $mime = Image::$mimeTypeMapping[$mime];
        }

        // The loader for the format determined that the image was borked. We set up the image
        // exception here since we're catching multiple exceptions below
        $invalidImageException = new ImageException('Invalid image', 415);
        $invalidImageException->setImboErrorCode(Exception::IMAGE_INVALID_IMAGE);

        // Attempt to load the image through one of the registered loaders
        try {
            $imagick = $event->getInputLoaderManager()->load($mime, $imageBlob);

            if ($imagick) {
                $size = $imagick->getImageGeometry();
            }
        } catch (ImagickException $e) {
            throw $invalidImageException;
        } catch (LoaderException $e) {
            throw $invalidImageException;
        }

        // Unsupported image type
        if (!$imagick) {
            $e = new ImageException('Unsupported image type: ' . $mime, 415);
            $e->setImboErrorCode(Exception::IMAGE_UNSUPPORTED_MIMETYPE);

            throw $e;
        }

        // Store relevant information in the image instance and attach it to the request
        $image = new Image();
        $image->setMimeType($mime)
              ->setExtension($event->getInputLoaderManager()->getExtensionFromMimetype($mime))
              ->setBlob($imageBlob)
              ->setWidth($size['width'])
              ->setHeight($size['height'])
              ->setOriginalChecksum(md5($imageBlob));

        $request->setImage($image);
    }
287508
public function deleteMetadata(EventInterface $event) {
        $request = $event->getRequest();

        $event->getDatabase()->deleteMetadata(
            $request->getUser(),
            $request->getImageIdentifier()
        );

        $event->getDatabase()->setLastModifiedNow(
            $request->getUser(),
            $request->getImageIdentifier()
        );
    }
1008384
private function handleListenersForEvent(EventInterface $event, $listeners)
    {
        $return = array();

        foreach ($listeners as $listener) {
            $return[] = $listener->handle($event);
        }

        return $return;
    }
740403
public function deleteImage(EventInterface $event) {
        $request = $event->getRequest();
        $event->getStorage()->delete($request->getUser(), $request->getImageIdentifier());
    }
375875
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());

            // and initialize a console for each node found in the configuration
            /** @var \AppserverIo\Psr\Cli\Configuration\ConsoleConfigurationInterface $consoleNode */
            foreach ($applicationServer->getSystemConfiguration()->getConsoles() as $consoleNode) {
                /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleFactoryInterface $consoleFactory */
                $consoleFactory = $consoleNode->getFactory();

                // use the factory if available
                /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */
                $console = $consoleFactory::factory($applicationServer, $consoleNode);

                // register the console as service
                $applicationServer->bindService(ApplicationServerInterface::ADMINISTRATION, $console);
            }

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
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);
    }
631242
public function loadUser(EventInterface $event) {
        $request = $event->getRequest();
        $response = $event->getResponse();
        $user = $request->getUser();
        $database = $event->getDatabase();

        $numImages = $database->getNumImages($user);
        $lastModified = $database->getLastModified([$user]);

        $userModel = new Model\User();
        $userModel->setUserId($user)
                  ->setNumImages($numImages)
                  ->setLastModified($lastModified);

        $response->setModel($userModel)
                 ->setLastModified($lastModified);
    }
1202418
public function handle(ActionInterface $event)
    {
        $data = $event->getAction();

        $action = [
            'class_name'  => get_class($event),
            'user_id'     => $data['user']->id,
            'username'    => $data['user']->username,
            'description' => $data['description'],
        ];

        if (isset($data['information'])) {
            $action['information'] = $data['information'];
        }

        Action::create($action);
    }
388847
public function loadImages(EventInterface $event) {
        $query = $this->getImagesQuery();
        $params = $event->getRequest()->query;
        $returnMetadata = false;

        if ($params->has('page')) {
            $query->page($params->get('page'));
        }

        if ($params->has('limit')) {
            $query->limit($params->get('limit'));
        }

        if ($params->has('metadata')) {
            $query->returnMetadata($params->get('metadata'));
            $returnMetadata = true;
        }

        if ($params->has('from')) {
            $query->from($params->get('from'));
        }

        if ($params->has('to')) {
            $query->to($params->get('to'));
        }

        if ($params->has('sort')) {
            $sort = $params->get('sort');

            if (is_array($sort)) {
                $query->sort($sort);
            }
        }

        if ($params->has('ids')) {
            $ids = $params->get('ids');

            if (is_array($ids)) {
                $query->imageIdentifiers($ids);
            }
        }

        if ($params->has('checksums')) {
            $checksums = $params->get('checksums');

            if (is_array($checksums)) {
                $query->checksums($checksums);
            }
        }

        if ($params->has('originalChecksums')) {
            $checksums = $params->get('originalChecksums');

            if (is_array($checksums)) {
                $query->originalChecksums($checksums);
            }
        }

        if ($event->hasArgument('users')) {
            $users = $event->getArgument('users');
        } else {
            $users = $event->getRequest()->getUsers();
        }

        $response = $event->getResponse();
        $database = $event->getDatabase();

        // Create the model and set some pagination values
        $model = new Model\Images();
        $model->setLimit($query->limit())
              ->setPage($query->page());

        $images = $database->getImages($users, $query, $model);
        $modelImages = [];

        foreach ($images as $image) {
            $entry = new Model\Image();
            $entry->setFilesize($image['size'])
                  ->setWidth($image['width'])
                  ->setHeight($image['height'])
                  ->setUser($image['user'])
                  ->setImageIdentifier($image['imageIdentifier'])
                  ->setChecksum($image['checksum'])
                  ->setOriginalChecksum(isset($image['originalChecksum']) ? $image['originalChecksum'] : null)
                  ->setMimeType($image['mime'])
                  ->setExtension($image['extension'])
                  ->setAddedDate($image['added'])
                  ->setUpdatedDate($image['updated']);

            if ($returnMetadata) {
                $entry->setMetadata($image['metadata']);
            }

            $modelImages[] = $entry;
        }

        // Add images to the model
        $model->setImages($modelImages);

        if ($params->has('fields')) {
            $fields = $params->get('fields');

            if (is_array($fields)) {
                $model->setFields($fields);
            }
        }

        $lastModified = $database->getLastModified($users);

        $response->setModel($model)
                 ->setLastModified($lastModified);
    }
721267
public function post(EventInterface $event) {
        $request = $event->getRequest();

        $event->getManager()->trigger('db.metadata.update', [
            'metadata' => json_decode($request->getContent(), true),
        ]);

        $model = new Model\Metadata();
        $model->setData($event->getDatabase()->getMetadata($request->getUser(), $request->getImageIdentifier()));

        $event->getResponse()->setModel($model);
    }
297133
public function deleteImage(EventInterface $event) {
        $request = $event->getRequest();

        $event->getDatabase()->deleteImage(
            $request->getUser(),
            $request->getImageIdentifier()
        );
    }
1147408
public function updateMetadata(EventInterface $event) {
        $request = $event->getRequest();

        $event->getDatabase()->updateMetadata(
            $request->getUser(),
            $request->getImageIdentifier(),
            $event->getArgument('metadata')
        );

        $event->getDatabase()->setLastModifiedNow(
            $request->getUser(),
            $request->getImageIdentifier()
        );
    }
787657
public function getImages(EventInterface $event) {
        $acl = $event->getAccessControl();

        $missingAccess = [];
        $users = $event->getRequest()->getUsers() ?: $event->getDatabase()->getAllUsers();

        foreach ($users as $user) {
            $hasAccess = $acl->hasAccess(
                $event->getRequest()->getPublicKey(),
                'images.get',
                $user
            );

            if (!$hasAccess) {
                $missingAccess[] = $user;
            }
        }

        if (!empty($missingAccess)) {
            throw new RuntimeException(
                'Public key does not have access to the users: [' .
                implode(', ', $missingAccess) .
                ']',
                400
            );
        }

        $event->getManager()->trigger('db.images.load', [
            'users' => $users
        ]);
    }
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;
    }
45422
public function check(EventInterface $event)
    {
        // Check result
        $result = $event->getResult();
        if (!$result instanceof ViewModel) {
            return;
        }

        // Check for xhr request
        $request = $event->getRequest();
        if ($request->isXmlHttpRequest()) {

            // Set terminal
            $result->setTerminal(true);
            $event->setViewModel($result);
        }
    }