Load transformed images from the cache

@param EventInterface $event The current event
773812
public function loadFromCache(EventInterface $event) {
        $request = $event->getRequest();
        $response = $event->getResponse();

        // Generate the full file path to the response
        $path = $this->getCacheFilePath($request);

        if (is_file($path)) {
            $data = @unserialize(file_get_contents($path));

            // Make sure the data from the cache is valid
            if (
                is_array($data) &&
                isset($data['image']) &&
                isset($data['headers']) &&
                ($data['image'] instanceof Image) &&
                ($data['headers'] instanceof ResponseHeaderBag)
            ) {
                // Mark as cache hit
                $data['headers']->set('X-Imbo-TransformationCache', 'Hit');
                $data['image']->hasBeenTransformed(false);

                // Replace all headers and set the image model
                $response->headers = $data['headers'];
                $response->setModel($data['image']);

                // Stop other listeners on this event
                $event->stopPropagation();

                // Mark this as a cache hit to prevent us from re-writing the result
                $this->setCacheHit(true);

                return;
            } else {
                // Invalid data in the cache, delete the file
                unlink($path);
            }
        }

        // Mark as cache miss
        $response->headers->set('X-Imbo-TransformationCache', 'Miss');
    }
1258445
public function process(EventInterface $event)
    {
        $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') {
            $this->error(self::ReorderSearch);
            return $this->redirect($event);
        }
        if ($options->getRoot() == 'trash') {
            $this->error(self::ReorderTrash);
            return $this->redirect($event);
        }
        if ($options->getOrderBy() != 'natural') {
            $this->error(self::UnmanagedOrder);
            return $this->redirect($event);
        }

        $posNew = $event->getParam('position');
        $posOld = $event->getParam('old_position');
        if (empty($posNew) || empty($posOld)) {
            return;
        }
        $positions = array_diff_assoc($posNew, $posOld);
            foreach ($positions as $id => $position) {
                try {
                    $mapper->beginTransaction();
                    $tid = $mapper->getTransactionIdentifier();
                    $this->mapper->reorder($id, $position, $tid);
                    $mapper->commit();
                } catch (UnavailableSourceException $e) {
                    $mapper->rollBack();
                    $this->setValue($id)->error(self::SourceNotFound);
                } catch (UnavailableDestinationException $e) {
                    $mapper->rollBack();
                    $this->error(self::DestinationNotFound);

                    // the destination is not available for all elements
                    break;
                } catch (Exception $e) {
                    $mapper->rollBack();
                    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);
                    break;
                }
            }

        return $this->redirect($event);
    }
1188866
public function imagePath(Event $event) {
		$event->setData($event->getData() + [
			'image' => null,
			'version' => null,
			'options' => [],
			'pathType' => 'fullPath'
		]);

		$data = $event->getData() + [
				'image' => null,
				'version' => null,
				'options' => [],
				'pathType' => 'fullPath'
			];

		if ($event->getSubject() instanceof EntityInterface) {
			$data['image'] = $event->getSubject();
		}

		$entity = $data['image'];
		$version = $data['version'];
		$options = $data['options'];
		$type = $data['pathType'];

		if (!$entity) {
			throw new InvalidArgumentException('No image entity provided.');
		}

		$this->loadImageProcessingFromConfig();
		$path = $this->imageVersionPath($entity, $version, $type, $options);

		$event->result = $path;
		$event->setData('path', $path);
		$event->stopPropagation();
	}
1359918
public function updateModelBeforeStoring(EventInterface $event) {
        $image = $event->getRequest()->getImage();

        if ($image->hasBeenTransformed()) {
            $image->setBlob($this->imagick->getImageBlob());
        }
    }
475975
public function invoke(EventInterface $event) {
        $request = $event->getRequest();
        $resource = (string) $request->getRoute();
        $method = $request->getMethod();
        $allowed = $this->params['allowedMethods'];

        if (!isset($allowed[$resource]) || !in_array($method, $allowed[$resource])) {
            // The listener is not configured for the current method/resource combination
            return;
        }

        $origin = $request->headers->get('Origin');

        // Vary on Origin to prevent caching allowed/disallowed requests
        $event->getResponse()->setVary('Origin', false);

        // Fall back if the passed origin is not allowed
        if (!$origin || !$this->originIsAllowed($origin)) {
            return;
        }

        // Flag this as an allowed request
        $this->requestAllowed = true;

        $event->getResponse()->headers->add([
            'Access-Control-Allow-Origin' => $origin,
        ]);
    }
52200
public function load(LoadResourceEvent $event)
    {
        /** @var Shortcut $shortcut */
        $shortcut = $event->getResource();

        $this->resourceLifecycle->load($shortcut->getTarget());
    }
282875
public function loadGroups(EventInterface $event) {
        $query = new GroupQuery();
        $params = $event->getRequest()->query;

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

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

        $response = $event->getResponse();
        $aclAdapter = $event->getAccessControl();

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

        $groups = $aclAdapter->getGroups($query, $model);
        $modelGroups = [];

        foreach ($groups as $groupName => $resources) {
            $modelGroups[] = [
                'name' => $groupName,
                'resources' => $resources,
            ];
        }

        $model->setGroups($modelGroups);
        $response->setModel($model);
    }
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;
    }
466412
public function doUnserialize(EventInterface $event)/*# : bool */
    {
        /* @var CacheItem $item */
        $item = $event->getParam('item');
        $val = @unserialize($item->getStrVal());
        if (false !== $val) {
            $item->set($val);
        }
        return true;
    }
1186954
public function generateVariations(EventInterface $event) {
        $eventManager = $event->getManager();
        $transformationManager = $event->getTransformationManager();

        $request = $event->getRequest();
        $user = $request->getUser();
        $originalImage = $request->getImage();
        $imageIdentifier = $originalImage->getImageIdentifier();
        $originalWidth = $originalImage->getWidth();

        // Fetch parameters specified in the Imbo configuration related to what sort of variations
        // should be generated
        $minWidth = $this->params['minWidth'];
        $maxWidth = $this->params['maxWidth'];
        $minDiff = $this->params['minDiff'];
        $scaleFactor = $this->params['scaleFactor'];

        // Remove widths which are larger than the original image
        $widths = array_filter($this->params['widths'], function($value) use ($originalWidth) {
            return $value < $originalWidth;
        });

        if ($this->params['autoScale'] === true) {
            // Have Imbo figure out the widths to generate in addition to the ones in the "width"
            // configuration parameter
            $variationWidth = $previousWidth = $originalWidth;

            while ($variationWidth > $minWidth) {
                $variationWidth = round($variationWidth * $scaleFactor);

                if ($variationWidth > $maxWidth) {
                    // Width too big, try again
                    continue;
                }

                if ((($previousWidth - $variationWidth) < $minDiff) || ($variationWidth < $minWidth)) {
                    // The diff is too small, or the variation is too small, stop generating more widths
                    break;
                }

                $previousWidth = $variationWidth;

                $widths[] = $variationWidth;
            }
        }

        foreach ($widths as $width) {
            // Clone the image so that the resize operation will happen on the original every time
            $image = clone $originalImage;

            try {
                // Trigger a loading of the image, using the clone of the original as an argument
                $eventManager->trigger('image.loaded', [
                    'image' => $image,

                    // Don't apply any sort of optimization to the image before saving, we want
                    // as high quality on the stored variation as possible
                    'skipOptimization' => true,
                ]);

                // If configured, use a lossless variation format
                if ($this->params['lossless'] === true) {
                    $transformationManager
                        ->getTransformation('convert')
                        ->setImage($image)
                        ->transform(['type' => 'png']);
                }

                // Trigger a resize of the image (the transformation handles aspect ratio)
                $transformationManager
                    ->getTransformation('resize')
                    ->setImage($image)
                    ->transform(['width' => $width]);

                // Trigger an update of the model
                $eventManager->trigger('image.transformed', [
                    'image' => $image,
                ]);

                // Store the image
                $this->storage->storeImageVariation($user, $imageIdentifier, $image->getBlob(), $width);

                // Store some data about the variation
                $this->database->storeImageVariationMetadata($user, $imageIdentifier, $image->getWidth(), $image->getHeight());
            } catch (TransformationException $e) {
                // Could not transform the image
                trigger_error(sprintf('Could not generate image variation for %s (%s), width: %d', $user, $imageIdentifier, $width), E_USER_WARNING);
            } catch (StorageException $e) {
                // Could not store the image
                trigger_error(sprintf('Could not store image variation for %s (%s), width: %d', $user, $imageIdentifier, $width), E_USER_WARNING);
            } catch (DatabaseException $e) {
                // Could not store metadata about the variation
                trigger_error(sprintf('Could not store image variation metadata for %s (%s), width: %d', $user, $imageIdentifier, $width), E_USER_WARNING);

                try {
                    $this->storage->deleteImageVariations($user, $imageIdentifier, $width);
                } catch (StorageException $e) {
                    trigger_error('Could not remove the stored variation', E_USER_WARNING);
                }
            }
        }
    }
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');
    }
177832
public function trigger(Event $event) {
    $request = $event->getTarget();
    
    $cachedRequest = new CachedRequest($request->getURL());
    $cachedRequest->setCachedResponse($event->getData()->response);
    $cachedRequest->setHeaders($event->getData()->headers);
    
    $this->addCachedRequest($cachedRequest);
  }
1272361
public function autoRotate(EventInterface $event) {
        $event->getTransformationManager()
            ->getTransformation('autoRotate')
            ->setImage($event->getRequest()->getImage())
            ->transform([]);
    }
983090
public function deleteImageShortUrls(EventInterface $event) {
        $request = $event->getRequest();
        $user = $request->getUser();
        $imageIdentifier = $request->getImageIdentifier();

        $event->getDatabase()->deleteShortUrls(
            $user,
            $imageIdentifier
        );

        if ($event->getName() === 'shorturls.delete') {
            // If the request is against the shorturls resource directly we need to supply a
            // response model. If this method is triggered because of an image has been deleted
            // the image resource will supply the response model
            $model = new ArrayModel();
            $model->setData([
                'imageIdentifier' => $imageIdentifier,
            ]);

            $event->getResponse()->setModel($model);
        }
    }
407206
public function loadImage(EventInterface $event) {
        $storage = $event->getStorage();
        $request = $event->getRequest();
        $response = $event->getResponse();
        $user = $request->getUser();
        $imageIdentifier = $request->getImageIdentifier();

        $imageData = $storage->getImage($user, $imageIdentifier);

        // Since the image is actually valid, this means that the backend
        // were unable to read the image for some reason. Might be NFS
        // that's down, web-backed storage being unavailable or something
        // similar.
        if ($imageData === false) {
            throw new StorageException('Failed reading file from storage backend for user ' . $user . ', id: ' . $imageIdentifier, 503);
        }

        $lastModified = $storage->getLastModified($user, $imageIdentifier);

        $response->setLastModified($lastModified)
                 ->getModel()->setBlob($imageData);

        $event->getManager()->trigger('image.loaded');
    }
146452
public function get(EventInterface $event) {
        $response = $event->getResponse();
        $database = $event->getDatabase();
        $storage = $event->getStorage();

        $databaseStatus = $database->getStatus();
        $storageStatus = $storage->getStatus();

        if (!$databaseStatus || !$storageStatus) {
            if (!$databaseStatus && !$storageStatus) {
                $message = 'Database and storage error';
            } else if (!$storageStatus) {
                $message = 'Storage error';
            } else {
                $message = 'Database error';
            }

            $response->setStatusCode(503, $message);
        }

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

        $statusModel = new Model\Status();
        $statusModel->setDate(new DateTime('now', new DateTimeZone('UTC')))
                    ->setDatabaseStatus($databaseStatus)
                    ->setStorageStatus($storageStatus);

        $response->setModel($statusModel);
    }
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());
        }
    }