Issues (74)

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/Commands/CleanCommand.php (1 issue)

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
namespace Spatie\MediaLibrary\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Console\ConfirmableTrait;
7
use Illuminate\Contracts\Filesystem\Factory;
8
use Illuminate\Database\Eloquent\Collection;
9
use Illuminate\Support\Str;
10
use Spatie\MediaLibrary\Conversion\Conversion;
11
use Spatie\MediaLibrary\Conversion\ConversionCollection;
12
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded;
13
use Spatie\MediaLibrary\FileManipulator;
14
use Spatie\MediaLibrary\MediaRepository;
15
use Spatie\MediaLibrary\Models\Media;
16
use Spatie\MediaLibrary\PathGenerator\BasePathGenerator;
17
use Spatie\MediaLibrary\ResponsiveImages\RegisteredResponsiveImages;
18
19
class CleanCommand extends Command
20
{
21
    use ConfirmableTrait;
22
23
    protected $signature = 'medialibrary:clean {modelType?} {collectionName?} {disk?}
24
    {--dry-run : List files that will be removed without removing them},
25
    {--force : Force the operation to run when in production},
26
    {--rate-limit= : Limit the number of request per second }';
27
28
    protected $description = 'Clean deprecated conversions and files without related model.';
29
30
    /** @var \Spatie\MediaLibrary\MediaRepository */
31
    protected $mediaRepository;
32
33
    /** @var \Spatie\MediaLibrary\FileManipulator */
34
    protected $fileManipulator;
35
36
    /** @var \Illuminate\Contracts\Filesystem\Factory */
37
    protected $fileSystem;
38
39
    /** @var \Spatie\MediaLibrary\PathGenerator\BasePathGenerator */
40
    protected $basePathGenerator;
41
42
    /** @var bool */
43
    protected $isDryRun = false;
44
45
    /** @var int */
46
    protected $rateLimit = 0;
47
48
    /**
49
     * @param \Spatie\MediaLibrary\MediaRepository                 $mediaRepository
50
     * @param \Spatie\MediaLibrary\FileManipulator                 $fileManipulator
51
     * @param \Illuminate\Contracts\Filesystem\Factory             $fileSystem
52
     * @param \Spatie\MediaLibrary\PathGenerator\BasePathGenerator $basePathGenerator
53
     */
54
    public function __construct(
55
        MediaRepository $mediaRepository,
56
        FileManipulator $fileManipulator,
57
        Factory $fileSystem,
58
        BasePathGenerator $basePathGenerator
59
    ) {
60
        parent::__construct();
61
62
        $this->mediaRepository = $mediaRepository;
63
        $this->fileManipulator = $fileManipulator;
64
        $this->fileSystem = $fileSystem;
65
        $this->basePathGenerator = $basePathGenerator;
66
    }
67
68
    public function handle()
69
    {
70
        if (! $this->confirmToProceed()) {
71
            return;
72
        }
73
74
        $this->isDryRun = $this->option('dry-run');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->option('dry-run') can also be of type array or string. However, the property $isDryRun is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
75
        $this->rateLimit = (int) $this->option('rate-limit');
76
77
        $this->deleteFilesGeneratedForDeprecatedConversions();
78
79
        $this->deleteOrphanedDirectories();
80
81
        $this->info('All done!');
82
    }
83
84
    public function getMediaItems(): Collection
85
    {
86
        $modelType = $this->argument('modelType');
87
        $collectionName = $this->argument('collectionName');
88
89
        if (! is_null($modelType) && ! is_null($collectionName)) {
90
            return $this->mediaRepository->getByModelTypeAndCollectionName(
91
                $modelType,
92
                $collectionName
93
            );
94
        }
95
96
        if (! is_null($modelType)) {
97
            return $this->mediaRepository->getByModelType($modelType);
98
        }
99
100
        if (! is_null($collectionName)) {
101
            return $this->mediaRepository->getByCollectionName($collectionName);
102
        }
103
104
        return $this->mediaRepository->all();
105
    }
106
107
    protected function deleteFilesGeneratedForDeprecatedConversions()
108
    {
109
        $this->getMediaItems()->each(function (Media $media) {
110
            $this->deleteConversionFilesForDeprecatedConversions($media);
111
112
            if ($media->responsive_images) {
113
                $this->deleteResponsiveImagesForDeprecatedConversions($media);
114
            }
115
116
            if ($this->rateLimit) {
117
                usleep((1 / $this->rateLimit) * 1000000 * 2);
118
            }
119
        });
120
    }
121
122
    protected function deleteConversionFilesForDeprecatedConversions(Media $media)
123
    {
124
        $conversionFilePaths = ConversionCollection::createForMedia($media)->getConversionsFiles($media->collection_name);
125
126
        $conversionPath = $this->basePathGenerator->getPathForConversions($media);
127
        $currentFilePaths = $this->fileSystem->disk($media->disk)->files($conversionPath);
128
129
        collect($currentFilePaths)
130
            ->reject(function (string $currentFilePath) use ($conversionFilePaths) {
131
                return $conversionFilePaths->contains(basename($currentFilePath));
132
            })
133
            ->each(function (string $currentFilePath) use ($media) {
134
                if (! $this->isDryRun) {
135
                    $this->fileSystem->disk($media->disk)->delete($currentFilePath);
136
137
                    $this->markConversionAsRemoved($media, $currentFilePath);
138
                }
139
140
                $this->info("Deprecated conversion file `{$currentFilePath}` ".($this->isDryRun ? 'found' : 'has been removed'));
141
            });
142
    }
143
144
    protected function deleteResponsiveImagesForDeprecatedConversions(Media $media)
145
    {
146
        $conversionNames = ConversionCollection::createForMedia($media)
147
            ->map(function (Conversion $conversion) {
148
                return $conversion->getName();
149
            })
150
            ->push('medialibrary_original');
151
152
        $responsiveImagesGeneratedFor = array_keys($media->responsive_images);
153
154
        collect($responsiveImagesGeneratedFor)
155
            ->map(function (string $generatedFor) use ($media) {
156
                return $media->responsiveImages($generatedFor);
157
            })
158
            ->reject(function (RegisteredResponsiveImages $responsiveImages) use ($conversionNames) {
159
                return $conversionNames->contains($responsiveImages->generatedFor);
160
            })
161
            ->each(function (RegisteredResponsiveImages $responsiveImages) {
162
                if (! $this->isDryRun) {
163
                    $responsiveImages->delete();
164
                }
165
            });
166
    }
167
168
    protected function deleteOrphanedDirectories()
169
    {
170
        $diskName = $this->argument('disk') ?: config('medialibrary.disk_name');
171
172
        if (is_null(config("filesystems.disks.{$diskName}"))) {
173
            throw FileCannotBeAdded::diskDoesNotExist($diskName);
174
        }
175
        $mediaClass = config('medialibrary.media_model');
176
        $mediaInstance = new $mediaClass();
177
        $keyName = $mediaInstance->getKeyName();
178
179
        $mediaIds = collect($this->mediaRepository->all()->pluck($keyName)->toArray());
180
181
        collect($this->fileSystem->disk($diskName)->directories())
182
            ->filter(function (string $directory) {
183
                return is_numeric($directory);
184
            })
185
            ->reject(function (string $directory) use ($mediaIds) {
186
                return $mediaIds->contains((int) $directory);
187
            })->each(function (string $directory) use ($diskName) {
188
                if (! $this->isDryRun) {
189
                    $this->fileSystem->disk($diskName)->deleteDirectory($directory);
190
                }
191
192
                if ($this->rateLimit) {
193
                    usleep((1 / $this->rateLimit) * 1000000);
194
                }
195
196
                $this->info("Orphaned media directory `{$directory}` ".($this->isDryRun ? 'found' : 'has been removed'));
197
            });
198
    }
199
200
    protected function markConversionAsRemoved(Media $media, string $conversionPath)
201
    {
202
        $conversionFile = pathinfo($conversionPath, PATHINFO_FILENAME);
203
204
        $generatedConversionName = null;
205
206
        $media->getGeneratedConversions()
207
            ->filter(function (bool $isGenerated, string $generatedConversionName) use ($conversionFile) {
208
                return Str::contains($conversionFile, $generatedConversionName);
209
            })
210
            ->each(function (bool $isGenerated, string $generatedConversionName) use ($media) {
211
                $media->markAsConversionGenerated($generatedConversionName, false);
212
            });
213
214
        $media->save();
215
    }
216
}
217