Validate metadata found in the request body

@param EventInterface $event The event instance
@throws InvalidArgumentException
776500
public function validateMetadata(EventInterface $event) {
        $request = $event->getRequest();
        $metadata = $request->getContent();

        if (empty($metadata)) {
            throw new InvalidArgumentException('Missing JSON data', 400);
        } else {
            $metadata = json_decode($metadata, true);

            if ($metadata === null) {
                throw new InvalidArgumentException('Invalid JSON data', 400);
            }

            foreach (array_keys($metadata) as $key) {
                if (strpos($key, '.') === false) {
                    continue;
                }

                throw new InvalidArgumentException('Invalid metadata. Dot characters (\'.\') are not allowed in metadata keys', 400);
            }
        }
    }
1131899
public function createShortUrl(EventInterface $event) {
        $request = $event->getRequest();
        $image = $request->getContent();

        if (empty($image)) {
            throw new InvalidArgumentException('Missing JSON data', 400);
        } else {
            $image = json_decode($image, true);

            if ($image === null || json_last_error() !== JSON_ERROR_NONE) {
                throw new InvalidArgumentException('Invalid JSON data', 400);
            }
        }

        if (!isset($image['user']) || $image['user'] !== $request->getUser()) {
            throw new InvalidArgumentException('Missing or invalid user', 400);
        }

        if (!isset($image['imageIdentifier']) || $image['imageIdentifier'] !== $request->getImageIdentifier()) {
            throw new InvalidArgumentException('Missing or invalid image identifier', 400);
        }

        $extension = isset($image['extension']) ? strtolower($image['extension']) : null;
        $outputConverterManager = $event->getOutputConverterManager();

        if ($extension !== null && !$outputConverterManager->supportsExtension($extension)) {
            throw new InvalidArgumentException('Extension provided is not a recognized format', 400);
        }

        $queryString = isset($image['query']) ? $image['query'] : null;

        if ($queryString) {
            parse_str(urldecode(ltrim($queryString, '?')), $query);
        } else {
            $query = [];
        }

        $database = $event->getDatabase();

        if (!$database->imageExists($image['user'], $image['imageIdentifier'])) {
            throw new InvalidArgumentException('Image does not exist', 404);
        }

        // See if a short URL ID already exists the for given parameters
        $exists = true;
        $shortUrlId = $database->getShortUrlId($image['user'], $image['imageIdentifier'], $extension, $query);

        if (!$shortUrlId) {
            $exists = false;

            do {
                // No short URL exists, generate an ID and insert. If the generated short URL ID
                // already exists, insert again.
                $shortUrlId = $this->getShortUrlId();
            } while($database->getShortUrlParams($shortUrlId));

            // We have an ID that does not already exist
            $database->insertShortUrl($shortUrlId, $image['user'], $image['imageIdentifier'], $extension, $query);
        }

        // Attach the header
        $model = new ArrayModel();
        $model->setData([
            'id' => $shortUrlId,
        ]);

        $event->getResponse()->setModel($model)
                             ->setStatusCode($exists ? 200 : 201);
    }
771965
public function addEvent(EventInterface $event)
    {
        if (!isset($this->events[$event->getName()])) {
            $this->events[$event->getName()] = $event;
        }

        return $this;
    }
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);
    }
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());
        }
    }
1348862
public function setEvent($event)
    {
        $allowedValues = $this->getEventAllowableValues();
        if (!in_array($event, $allowedValues)) {
            throw new \InvalidArgumentException(
                sprintf(
                    "Invalid value for 'event', must be one of '%s'",
                    implode("', '", $allowedValues)
                )
            );
        }
        $this->container['event'] = $event;

        return $this;
    }
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()
        );
    }
1106622
public function get(EventInterface $event) {
        $request = $event->getRequest();
        $response = $event->getResponse();

        $redirectUrl = $event->getConfig()['indexRedirect'];

        if ($redirectUrl) {
            $response->setStatusCode(307);
            $response->headers->set('Location', $redirectUrl);
            return;
        }

        $response->setStatusCode(200, 'Hell Yeah');

        $baseUrl = $request->getSchemeAndHttpHost() . $request->getBaseUrl();

        $model = new Model\ArrayModel();
        $model->setData([
            'site' => 'http://imbo.io',
            'source' => 'https://github.com/imbo/imbo',
            'issues' => 'https://github.com/imbo/imbo/issues',
            'docs' => 'http://docs.imbo.io',
        ]);

        $response->setModel($model);

        // Prevent caching
        $response->setMaxAge(0)
                 ->setPrivate();
        $response->headers->addCacheControlDirective('no-store');
    }
375731
public function getEventSchema(EventInterface $event)
    {
        if (!$event instanceof SchemaEvent) {
            return null;
        }

        return $this->dereferencer->dereference($event->getSchema());
    }
843902
public function serialize(EventInterface $event)
    {
        if (!$event instanceof \JsonSerializable) {
            throw new \InvalidArgumentException(sprintf('Cannot serialize %s event.', $event->getName()));
        }

        return json_encode($event);
    }
687354
public function handle(EventInterface $event)
    {

        try {
            // load the application server and system configuration instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
            $systemConfiguration = $applicationServer->getSystemConfiguration();

            // load the initial context configuration
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\InitialContextConfigurationInterface $initialContextNode */
            $initialContextNode = $systemConfiguration->getInitialContext();
            $reflectionClass = new \ReflectionClass($initialContextNode->getType());
            /** @var \AppserverIo\Psr\ApplicationServer\ContextInterface $initialContext */
            $initialContext = $reflectionClass->newInstanceArgs(array($systemConfiguration));

            // attach the registered loggers to the initial context
            $initialContext->setLoggers($applicationServer->getLoggers());
            $initialContext->setSystemLogger($applicationServer->getSystemLogger());

            // set the initial context and flush it initially
            $applicationServer->setInitialContext($initialContext);

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

        try {
            // load the application server and the naming directory 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());

            // add the configured extractors to the internal array
            /** @var \AppserverIo\Appserver\Core\Api\Node\ScannerNodeInterface $scannerNode */
            foreach ($applicationServer->getSystemConfiguration()->getScanners() as $scannerNode) {
                // load the factory class name
                $factoryClass = $scannerNode->getFactory();

                // invoke the visit method of the factory class
                /** @var \AppserverIo\Appserver\Core\Scanner\ScannerFactoryInterface $factory */
                $factoryClass::visit($applicationServer, $scannerNode);
            }

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
524692
public function record(EventInterface $event)
    {
        $eventUuid = $event->uuid();
        $this->recordedEvents[(string) $eventUuid] = $event;
    }
1372044
public function populateImagickInstance(EventInterface $event) {
        $event->getInputLoaderManager()->setImagick($this->imagick);
        $event->getOutputConverterManager()->setImagick($this->imagick);
    }
1192541
public function handle(EventInterface $event)
    {
        $headers = $this->headersfactory->headers();
        $this->publisher->publish($this->serializer->serialize($event), $event->getName(), $headers);
    }
1075425
public function process(EventInterface $event)
    {
        $events = $this->getEventManager();
        $mapper = $this->getMapper();
        $optionsProvider = $this->getOptionsProvider();
        $translator = $this->getTranslator();
        $pane = $event->getParam('pane');
        if (! $optionsProvider->hasIdentifier($pane)) {
            return;
        }
        $options = $optionsProvider->getOptions($pane);
        if ($options->getType() == 'search' || $options->getRoot() == 'site') {
            return;
        }
        try {
            $mapper->beginTransaction();
            $tid = $mapper->getTransactionIdentifier();
            $events->trigger(
                __FUNCTION__ . '.clean.pre',
                null,
                [
                    'tid' => $tid,
                ]
            );
            $mapper->clean($tid);
            $mapper->commit();
        } catch (Exception $e) {
            if (DEBUG_MODE) {
                throw new DebugException(
                    $translator->translate('Error: ') . $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            $meta = $mapper->findMetaById($id);
            $name = isset($meta['title']) ? $meta['title'] : $id;
            $this->setValue($name)->error(self::UnexpectedError);
        }

        return $this->redirect($event, 'sc-admin/file/delete');
    }