Generate a thumbnail image for a file.

@param MediaFile $media_file
@param array     $params

@return ResponseInterface
977914
private function generateImage(MediaFile $media_file, array $params): ResponseInterface
    {
        try {
            // Validate HTTP signature
            $signature = $this->glideSignature();

            $signature->validateRequest(parse_url(WT_BASE_URL . 'index.php', PHP_URL_PATH), $params);

            $server = $this->glideServer($media_file->folder());
            $path   = $server->makeImage($media_file->filename(), $params);

            return response($server->getCache()->read($path), StatusCodeInterface::STATUS_OK, [
                'Content-Type'   => $server->getCache()->getMimetype($path),
                'Content-Length' => $server->getCache()->getSize($path),
                'Cache-Control'  => 'max-age=31536000, public',
                'Expires'        => date_create('+1 years')->format('D, d M Y H:i:s') . ' GMT',
            ]);
        } catch (SignatureException $ex) {
            return $this->httpStatusAsImage(StatusCodeInterface::STATUS_FORBIDDEN);
        } catch (FileNotFoundException $ex) {
            return $this->httpStatusAsImage(StatusCodeInterface::STATUS_NOT_FOUND);
        } catch (Throwable $ex) {
            Log::addErrorLog('Cannot create thumbnail ' . $ex->getMessage());

            return $this->httpStatusAsImage(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
        }
    }
961782
public function generate()
    {
        $return = '';

        if (empty($this->thumbnailSize)) {
            $this->thumbnailSize = [
                Config::get('imageWidth'),
                Config::get('imageHeight'),
                'box',
            ];
        }

        $file = FilesModel::findByPk($this->varValue);
        if (null === $file && null !== $this->fallbackImage) {
            $file = FilesModel::findByPk($this->fallbackImage);
        }
        if (null !== $file) {
            $altTag = $file->name;
            $size   = deserialize($this->thumbnailSize);
            $image  = Image::create($file->path, $size)->executeResize();

            $return .= sprintf(
                '<img src="%s" width="%s" height="%s" alt="%s" class="uploaded-image">',
                $image->getResizedPath(),
                $image->getTargetWidth(),
                $image->getTargetHeight(),
                $altTag
            );
        }

        if ($this->addMetaWizard) {
//@todo add meta wizard here
        }

        $return .= parent::generate();

        if ($this->enableReset) {
            $return .= sprintf(
                '<input type="checkbox" name="%s" class="checkbox" value=""><label>%s</label> ',
                $this->strName.'_reset',
                'Reset'
            );
        }

        return $return;
    }
1318604
public function renderImage(MediaInterface $image, array $params = [])
    {
        if ($image->getType() !== MediaTypes::IMAGE) {
            throw new \InvalidArgumentException('Expected media with "image" type.');
        }

        $params = array_merge([
            'filter' => 'media_front',
            'attr' => [
                'id' => 'media-image-' . $image->getId(),
            ],
        ], $params);

        if (!(array_key_exists('width', $params) && array_key_exists('height', $params))) {
            $filter = $this->filterManager->getFilterConfiguration()->get($params['filter']);
            if (array_key_exists('filters', $filter)) {
                $width = $height = 0;
                foreach ($filter['filters'] as $cfg) {
                    if (array_key_exists('size', $cfg)) {
                        if (array_key_exists('width', $cfg['size']) && $width < $cfg['size']['width']) {
                            $width = $cfg['size']['width'];
                        }
                        if (array_key_exists('height', $cfg['size']) && $width < $cfg['size']['height']) {
                            $width = $cfg['size']['height'];
                        }
                    }
                }
                $params = array_merge([
                    'attr' => [
                        'width'  => $width,
                        'height' => $height,
                    ],
                ], $params);
            }
        }

        return $this->elementTemplate->renderBlock('image', [
            'filter' => $params['filter'],
            'path'   => $image->getPath(),
            'alt'    => $image->getTitle(),
            'attr'   => $params['attr'],
        ]);
    }
1291221
public function outputImage($params = array())
    {
        $param_defaults = array(
            'width' => 120,
            'height' => 40,
            // 'length' => 6
        );
        $params = \array_merge($param_defaults, $params);
        $code = $this->generateCode($this->length);
        $font_size = $params['height'] * $this->font_scale;
        $image = @\imagecreate($params['width'], $params['height']) or die('Cannot initialize new GD image stream');
        // set the colors
        $color_bkg = \imagecolorallocate($image, 0, 0, 0);
        // $color_text = imagecolorallocate($image, 20, 40, 100);
        $color_text = \imagecolorallocate($image, 200, 200, 200);
        $color_noise = \imagecolorallocate($image, 150, 150, 150);
        // generate random dots in background
        for ($i=0; $i<($params['width']*$params['height'])/$this->dot_divisor; $i++) {
            \imagefilledellipse($image, \mt_rand(0, $params['width']), \mt_rand(0, $params['height']), 1, 1, $color_noise);
        }
        // generate random lines in background
        for ($i=0; $i<($params['width']*$params['height'])/$this->line_divisor; $i++) {
            \imageline($image, \mt_rand(0, $params['width']), \mt_rand(0, $params['height']), \mt_rand(0, $params['width']), \mt_rand(0, $params['height']), $color_noise);
        }
        // create textbox and add text
        $textbox = \imagettfbbox($font_size, 0, $this->font, $code); // or die('Error in imagettfbbox function');
        $x = ($params['width'] - $textbox[4])/2;
        $y = ($params['height'] - $textbox[5])/2;
        \imagettftext($image, $font_size, 0, $x, $y, $color_text, $this->font, $code); // or die('Error in imagettftext function');
        // output captcha image to browser
        \header('Last-Modified: '.\date('r'));
        \header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        \header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        \header('Content-Type: image/jpeg');
        \header('Pragma: no-cache');
        \imagejpeg($image);
        \imagedestroy($image);
    }
305615
public function renderVideo(MediaInterface $video, array $params = [])
    {
        if ($video->getType() !== MediaTypes::VIDEO) {
            throw new \InvalidArgumentException('Expected media with "video" type.');
        }

        $params = array_merge([
            'responsive'   => false,
            'aspect_ratio' => '16by9',
            'attr'         => [
                'id'     => 'media-video-' . $video->getId(),
                'class'  => 'video-js vjs-default-skin vjs-big-play-centered',
                'height' => '100%',
                'width'  => '100%',
            ],
        ], $params);

        return $this->elementTemplate->renderBlock('video', [
            'responsive'   => $params['responsive'],
            'aspect_ratio' => $params['aspect_ratio'],
            'src'          => $this->getDownloadUrl($video),
            'mime_type'    => $this->getMimeType($video),
            'attr'         => $params['attr'],
        ]);
    }
724273
private static function uploadImage(MediaService $mediaService, $url)
    {
        // Creates an image and upload it to the server.
        $image = new Image();
        $image->setData(file_get_contents($url));
        $image->setType(MediaMediaType::IMAGE);

        return $mediaService->upload([$image])[0];
    }
966960
private function generateFileThumb(MediaInterface $media)
    {
        $extension   = $media->guessExtension();
        $thumbPath   = sprintf('/%s/%s.jpg', $this->thumbsDirectory, $extension);
        $destination = $this->webRootDirectory . $thumbPath;

        if (file_exists($destination)) {
            return $thumbPath;
        }

        $backgroundColor = MediaTypes::getColor($media->getType());

        $iconPath = sprintf('%s/%s.png', $this->iconsSourcePath, $extension);
        if (! file_exists($iconPath)) {
            $iconPath = $this->iconsSourcePath.'/default.png';
        }

        $this->checkDir(dirname($destination));
        try {
            $palette = new RGB();
            $thumb = $this->imagine->create(new Box(120, 90), $palette->color($backgroundColor));

            $icon = $this->imagine->open($iconPath);
            $iconSize = $icon->getSize();
            $start = new Point(120/2 - $iconSize->getWidth()/2, 90/2 - $iconSize->getHeight()/2);

            $thumb->paste($icon, $start);
            $thumb->save($destination);

            return $thumbPath;
        } catch (ImagineException $e) {
            // Image thumb generation failed
        }

        return null;
    }
1224040
function (media_id, copy_options, cb) {

            if (copy_options) {
                copy_options._method = 'POST';
            }

            _util.buildQuery('medias/' + media_id + '/copy', copy_options, function (error, data) {

                return cb(error, data);

            });

        }
470372
public function thumbnail($media, $format, $options = [])
    {
        return $this->getTwigExtension()->thumbnail($media, $format, $options);
    }
480383
public function renderMedia(MediaInterface $media, array $params = [])
    {
        switch ($media->getType()) {
            case MediaTypes::VIDEO :
                return $this->renderVideo($media, $params);
            case MediaTypes::FLASH :
                return $this->renderFlash($media, $params);
            case MediaTypes::AUDIO :
                return $this->renderAudio($media, $params);
            case MediaTypes::IMAGE :
                return $this->renderImage($media, $params);
            default:
                return $this->renderFile($media, $params);
        }
    }
1096951
public function process(Media $media)
    {
        if ($this->request->getMethod() == 'POST')
        {
            $this->form->handleRequest($this->request);
            if ($this->form->isValid())
            {
                $file = $this->form->get('media')->getData();
                if (!is_null($file))
                {
                    $media->setMediaType($file->getMimeType());
                    $media->setOriginalName($file->getClientOriginalName());
                    $filename = $this->mediaLibraryService->add($file, $media);
                    if ($filename)
                    {
                        // New media
                        if ($media->getId() == 0)
                        {
                            if (is_a($this->user, 'Symfony\Component\Security\Core\User\UserInterface')
                                    && method_exists($this->user, 'getId'))
                            {
                                $media->setOwnerId($this->user->getId());
                            }
                        }
                        else
                        {
                            // We remove old files
                            $this->mediaLibraryService->remove($media);
                        }

                        // We set new file
                        $media->setFullPath($filename);

                        $em = $this->doctrine->getManager();
                        $em->persist($media);
                        $em->flush();
                        return TRUE;
                    }
                }
            }
        }
        return FALSE;
    }
195277
private function createMedia(Media $media)
    {
        $request = $this->getRequest();
        $thumbSizes = $this->container->getParameter('fulgurio_light_cms.thumbs');
        $form = $this->createForm(new AdminMediaType($this->container), $media);
        $formHandler = new AdminMediaHandler();
        $formHandler->setForm($form)
                ->setRequest($request)
                ->setDoctrine($this->getDoctrine())
                ->setUser($this->getUser())
                ->setMediaLibraryService($this->get('fulgurio_light_cms.media_library'));
        if ($formHandler->process($media))
        {
            if ($request->isXmlHttpRequest())
            {
                return $this->jsonResponse((object) array('files' => array(
                    (object) array(
                        'id' => $media->getId(),
                        'name' => $media->getOriginalName(),
                        'url' => $media->getFullPath(),
                        'thumbnail_url' => LightCMSUtils::getThumbFilename($media->getFullPath(), $media->getMediaType(), $thumbSizes['medium']),
                        'delete_url' => $this->generateUrl('AdminMediasRemove', array('mediaId' => $media->getId(), 'confirm' => 'yes')),
                        'delete_type' => 'GET'
                    )
                )));
            }
            $this->get('session')->getFlashBag()->add(
                'success',
                $this->get('translator')->trans(
                    isset($options['pageId']) ? 'fulgurio.lightcms.medias.edit_form.success_msg' : 'fulgurio.lightcms.medias.add_form.success_msg',
                    array(),
                    'admin'
                )
            );
            return $this->redirect($this->generateUrl('AdminMedias'));
        }
        else if ($request->isXmlHttpRequest())
        {
            //@todo : well, we only manage one error, not the others ...
            return $this->jsonResponse((object) array('files' => array(
                    (object) array(
                            'error' => $this->get('translator')->trans('fulgurio.lightcms.medias.add_form.error_msg', array('%MAX_FILE_SIZE%' => ini_get('upload_max_filesize')), 'admin'),
                    )
            )));
        }
        $options['form'] = $form->createView();
        return $this->render('FulgurioLightCMSBundle:AdminMedia:add.html.twig', $options);
    }
1368144
public function regenerate($args, $assoc_args) {
		/** @var StorageTool $storageTool */
		$storageTool = ToolsManager::instance()->tools['storage'];

		if (!$storageTool || !$storageTool->enabled()) {
			Command::Error('Storage tool is not enabled in Media Cloud or the settings are incorrect.');
			return;
		}

		$postArgs = [
			'post_type' => 'attachment',
			'post_status' => 'inherit',
			'nopaging' => true,
			'post_mime_type' => 'image',
			'fields' => 'ids',
		];

		$query = new \WP_Query($postArgs);

		if($query->post_count > 0) {
            BatchManager::instance()->reset('thumbnails');

            BatchManager::instance()->setStatus('thumbnails', true);
            BatchManager::instance()->setTotalCount('thumbnails', $query->post_count);
            BatchManager::instance()->setCurrent('thumbnails', 1);
            BatchManager::instance()->setShouldCancel('thumbnails', false);

			Command::Info("Total posts found: %Y{$query->post_count}.", true);

			$pd = new DefaultProgressDelegate();

			for($i = 1; $i <= $query->post_count; $i++) {
				$postId = $query->posts[$i - 1];
				$upload_file = get_attached_file($postId);
				$fileName = basename($upload_file);

                BatchManager::instance()->setCurrentFile('thumbnails', $fileName);
                BatchManager::instance()->setCurrent('thumbnails', $i);

				Command::Info("%w[%C{$i}%w of %C{$query->post_count}%w] %NRegenerating thumbnails for %Y$fileName%N %w(%N$postId%w)%N ... ");
				$storageTool->regenerateFile($postId);
				Command::Info("%YDone%N.", true);
			}

            BatchManager::instance()->reset('thumbnails');
		}

	}
1169829
protected function _makeRequest($url, $params = array(), $photos = array())
    {
        // if any photos exist, let's merge them into the params
        if (count($photos)) {
            $params = array_merge($params, $photos);
        }

        foreach ($params as $key => $value) {
            if (is_array($value)) {
                $flattened = $this->_flattenMultiDimensionalParams($params);
                $params = $flattened;
            }
        }

        // send along some headers for reporting
        $headers = array(
            'X-WRAPPER: ' . $this->_version
        );

        // init curl to make the request
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        // the API response
        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        $error = curl_error($curl);
        $errno = curl_errno($curl);

        if ($error) {
            throw new Sp_CurlException($error, $errno);
        }

        if (!$response) {
            throw new Sp_NoResponseException('The API did not return any response. Error #' . $info['http_code']);
        }

        $json = json_decode($response, true);

        if ($json['stat'] != 'ok') {
            throw new Sp_Exception(
                'The API did not return an OK response. ' . $json['msg'],
                0,
                $response
            );
        }

        return $json;
    }
243199
public function fetchTemporaryThumbnail ($mediaID, $into = null)
    {
        return new Downloaded\Thumbnail($mediaID, $this->doTemporaryFetchToStream($mediaID, $into));
    }
193062
private function thumbnail(array $params)
    {
        $mode = isset($params['mode']) ? $params['mode'] : self::THUMBNAIL_OUTBOUND;

        $width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
        $height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;

        if (is_null($width) || is_null($height)) {
            throw new Exception('Wrong thumbnail width or height');
        }

        $this->image = $this->image->thumbnail(new Box($width, $height), $mode);
    }
1074747
public function renderFlash(MediaInterface $flash, array $params = [])
    {
        if ($flash->getType() !== MediaTypes::FLASH) {
            throw new \InvalidArgumentException('Expected media with "flash" type.');
        }

        $params = array_merge([
            //'responsive' => false,
            'attr'       => [
                'id'     => 'media-flash-' . $flash->getId(),
                'class'  => 'swf-object',
                //'classid' => 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
                'height' => '100%',
                'width'  => '100%',
            ],
        ], $params);

        return $this->elementTemplate->renderBlock('flash', [
            'src'  => $this->getDownloadUrl($flash),
            'attr' => $params['attr'],
        ]);
    }