Issues (234)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Provider/ImageProvider.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\MediaBundle\Provider;
15
16
use Gaufrette\Filesystem;
17
use Imagine\Image\ImagineInterface;
18
use Sonata\MediaBundle\CDN\CDNInterface;
19
use Sonata\MediaBundle\Generator\GeneratorInterface;
20
use Sonata\MediaBundle\Metadata\MetadataBuilderInterface;
21
use Sonata\MediaBundle\Model\MediaInterface;
22
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
23
use Symfony\Component\HttpFoundation\File\File;
24
use Symfony\Component\HttpFoundation\File\UploadedFile;
25
26
/**
27
 * @final since sonata-project/media-bundle 3.21.0
28
 */
29
class ImageProvider extends FileProvider
30
{
31
    /**
32
     * @var ImagineInterface
33
     */
34
    protected $imagineAdapter;
35
36
    /**
37
     * @param string                   $name
38
     * @param MetadataBuilderInterface $metadata
39
     */
40
    public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, array $allowedExtensions, array $allowedMimeTypes, ImagineInterface $adapter, ?MetadataBuilderInterface $metadata = null)
41
    {
42
        parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail, $allowedExtensions, $allowedMimeTypes, $metadata);
43
44
        $this->imagineAdapter = $adapter;
45
    }
46
47
    public function getProviderMetadata()
48
    {
49
        return new Metadata(
50
            $this->getName(),
51
            $this->getName().'.description',
52
            null,
53
            'SonataMediaBundle',
54
            ['class' => 'fa fa-picture-o']
55
        );
56
    }
57
58
    public function getHelperProperties(MediaInterface $media, $format, $options = [])
59
    {
60
        if (isset($options['srcset'], $options['picture'])) {
61
            throw new \LogicException("The 'srcset' and 'picture' options must not be used simultaneously.");
62
        }
63
64
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
65
            $box = $media->getBox();
66
        } else {
67
            $resizerFormat = $this->getFormat($format);
68
            if (false === $resizerFormat) {
69
                throw new \RuntimeException(sprintf('The image format "%s" is not defined.
70
                        Is the format registered in your ``sonata_media`` configuration?', $format));
71
            }
72
73
            $box = $this->resizer->getBox($media, $resizerFormat);
74
        }
75
76
        $mediaWidth = $box->getWidth();
77
78
        $params = [
79
            'alt' => $media->getDescription() ?: $media->getName(),
80
            'title' => $media->getName(),
81
            'src' => $this->generatePublicUrl($media, $format),
82
            'width' => $mediaWidth,
83
            'height' => $box->getHeight(),
84
        ];
85
86
        if (isset($options['picture'])) {
87
            $pictureParams = [];
88
            foreach ($options['picture'] as $key => $pictureFormat) {
89
                $formatName = $this->getFormatName($media, $pictureFormat);
90
                $settings = $this->getFormat($formatName);
91
                $src = $this->generatePublicUrl($media, $formatName);
92
                $mediaQuery = \is_string($key)
93
                    ? $key
94
                    : sprintf('(max-width: %dpx)', $this->resizer->getBox($media, $settings)->getWidth());
0 ignored issues
show
It seems like $settings defined by $this->getFormat($formatName) on line 90 can also be of type false; however, Sonata\MediaBundle\Resiz...izerInterface::getBox() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
95
96
                $pictureParams['source'][] = ['media' => $mediaQuery, 'srcset' => $src];
97
            }
98
99
            unset($options['picture']);
100
            $pictureParams['img'] = $params + $options;
101
            $params = ['picture' => $pictureParams];
102
        } elseif (MediaProviderInterface::FORMAT_ADMIN !== $format) {
103
            $srcSetFormats = $this->getFormats();
104
105
            if (isset($options['srcset']) && \is_array($options['srcset'])) {
106
                $srcSetFormats = [];
107
                foreach ($options['srcset'] as $srcSetFormat) {
108
                    $formatName = $this->getFormatName($media, $srcSetFormat);
109
                    $srcSetFormats[$formatName] = $this->getFormat($formatName);
110
                }
111
                unset($options['srcset']);
112
113
                // Make sure the requested format is also in the srcSetFormats
114
                if (!isset($srcSetFormats[$format])) {
115
                    $srcSetFormats[$format] = $this->getFormat($format);
116
                }
117
            }
118
119
            if (!isset($options['srcset'])) {
120
                $srcSet = [];
121
122
                foreach ($srcSetFormats as $providerFormat => $settings) {
123
                    // Check if format belongs to the current media's context
124
                    if (0 === strpos($providerFormat, $media->getContext())) {
125
                        $width = $this->resizer->getBox($media, $settings)->getWidth();
126
127
                        $srcSet[] = sprintf('%s %dw', $this->generatePublicUrl($media, $providerFormat), $width);
128
                    }
129
                }
130
131
                // The reference format is not in the formats list
132
                $srcSet[] = sprintf(
133
                    '%s %dw',
134
                    $this->generatePublicUrl($media, MediaProviderInterface::FORMAT_REFERENCE),
135
                    $media->getBox()->getWidth()
136
                );
137
138
                $params['srcset'] = implode(', ', $srcSet);
139
            }
140
141
            $params['sizes'] = sprintf('(max-width: %1$dpx) 100vw, %1$dpx', $mediaWidth);
142
        }
143
144
        return array_merge($params, $options);
145
    }
146
147
    public function updateMetadata(MediaInterface $media, $force = true): void
148
    {
149
        try {
150
            if (!$media->getBinaryContent() instanceof \SplFileInfo) {
151
                // this is now optimized at all!!!
152
                $path = tempnam(sys_get_temp_dir(), 'sonata_update_metadata');
153
                $fileObject = new \SplFileObject($path, 'w');
154
                $fileObject->fwrite($this->getReferenceFile($media)->getContent());
155
            } else {
156
                $fileObject = $media->getBinaryContent();
157
            }
158
159
            $image = $this->imagineAdapter->open($fileObject->getPathname());
160
            $size = $image->getSize();
161
162
            $media->setSize($fileObject->getSize());
163
            $media->setWidth($size->getWidth());
164
            $media->setHeight($size->getHeight());
165
        } catch (\LogicException $e) {
166
            $media->setProviderStatus(MediaInterface::STATUS_ERROR);
167
168
            $media->setSize(0);
169
            $media->setWidth(0);
170
            $media->setHeight(0);
171
        }
172
    }
173
174
    public function generatePublicUrl(MediaInterface $media, $format)
175
    {
176
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
177
            $path = $this->getReferenceImage($media);
178
        } else {
179
            $path = $this->thumbnail->generatePublicUrl($this, $media, $format);
180
        }
181
182
        // if $path is already an url, no further action is required
183
        if (null !== parse_url($path, PHP_URL_SCHEME)) {
184
            return $path;
185
        }
186
187
        return $this->getCdn()->getPath($path, $media->getCdnIsFlushable());
188
    }
189
190
    public function generatePrivateUrl(MediaInterface $media, $format)
191
    {
192
        return $this->thumbnail->generatePrivateUrl($this, $media, $format);
193
    }
194
195
    /**
196
     * @return array<string, mixed>
0 ignored issues
show
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
197
     */
198
    public function getFormatsForContext(string $context): array
199
    {
200
        return array_filter($this->getFormats(), static function (string $providerFormat) use ($context): bool {
201
            return 0 === strpos($providerFormat, $context);
202
        }, ARRAY_FILTER_USE_KEY);
203
    }
204
205
    protected function doTransform(MediaInterface $media): void
206
    {
207
        parent::doTransform($media);
208
209
        if ($media->getBinaryContent() instanceof UploadedFile) {
210
            $fileName = $media->getBinaryContent()->getClientOriginalName();
211
        } elseif ($media->getBinaryContent() instanceof File) {
212
            $fileName = $media->getBinaryContent()->getFilename();
213
        } else {
214
            // Should not happen, FileProvider should throw an exception in that case
215
            return;
216
        }
217
218
        if (!\in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $this->allowedExtensions, true)
219
            || !\in_array($media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes, true)) {
220
            return;
221
        }
222
223
        try {
224
            $image = $this->imagineAdapter->open($media->getBinaryContent()->getPathname());
225
        } catch (\RuntimeException $e) {
226
            $media->setProviderStatus(MediaInterface::STATUS_ERROR);
227
228
            return;
229
        }
230
231
        $size = $image->getSize();
232
233
        $media->setWidth($size->getWidth());
234
        $media->setHeight($size->getHeight());
235
236
        $media->setProviderStatus(MediaInterface::STATUS_OK);
237
    }
238
}
239