Issues (7)

Security Analysis    no request data  

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/Command/WeburgDownload.php (3 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
namespace Popstas\Transmission\Console\Command;
4
5
use Popstas\Transmission\Console\WeburgClient;
6
use Symfony\Component\Console\Helper\ProgressBar;
7
use Symfony\Component\Console\Input\ArrayInput;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class WeburgDownload extends Command
13
{
14
    protected function configure()
15
    {
16
        parent::configure();
17
        $this
18
            ->setName('weburg-download')
19
            ->setAliases(['wd'])
20
            ->setDescription('Download torrents from weburg.net')
21
            ->addOption('download-torrents-dir', null, InputOption::VALUE_OPTIONAL, 'Torrents destination directory')
22
            ->addOption('days', null, InputOption::VALUE_OPTIONAL, 'Max age of series torrent')
23
            ->addOption('popular', null, InputOption::VALUE_NONE, 'Download only popular')
24
            ->addOption('series', null, InputOption::VALUE_NONE, 'Download only tracked series')
25
            ->addOption('query', null, InputOption::VALUE_OPTIONAL, 'Search and download movie from Weburg')
26
            ->addOption('movies-url', null, InputOption::VALUE_OPTIONAL, 'URL with movies on Weburg')
27
            ->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Limit torrent list')
28
            ->addOption('yes', 'y', InputOption::VALUE_NONE, 'Don\'t ask confirmation')
29
            ->addArgument('movie-id', null, 'Movie ID or URL')
30
            ->setHelp(<<<EOT
31
## Download torrents from Weburg.net
32
33
You can automatically download popular torrents from http://weburg.net/movies/new out of the box, use command:
34
```
35
transmission-cli weburg-download --download-torrents-dir=/path/to/torrents/directory [--limit=10]
36
```
37
38
or define `download-torrents-dir` in config and just:
39
```
40
transmission-cli weburg-download
41
```
42
43
You can automatically download new series, for add series to tracked list see `transmission-cli weburg-series-add`.
44
It is pretty simple:
45
```
46
transmission-cli weburg-series-add http://weburg.net/series/info/12345
47
```
48
49
After that command `weburg-download` also will download series from list for last day.
50
If you don't want to download popular torrents, but only new series, use command:
51
```
52
transmission-cli weburg-download --download-torrents-dir=/path/to/torrents/directory --series
53
```
54
55
## Add downloaded torrents to Transmission
56
57
After download all torrents, command call `torrent-add` command for each transmission-host from config.
58
If was defined `--transmission-host` option, then `torrent-add` will called only for this host.
59
EOT
60
            );
61
    }
62
63
    protected function execute(InputInterface $input, OutputInterface $output)
64
    {
65
        $config = $this->getApplication()->getConfig();
66
        $weburgClient = $this->getApplication()->getWeburgClient();
67
68
        try {
69
            list($torrentsDir, $downloadDir) = $this->getTorrentsDirectory($input);
70
71
            $daysMax = $config->overrideConfig($input, 'days', 'weburg-series-max-age');
72
            $allowedMisses = $config->get('weburg-series-allowed-misses');
73
74
            $movieArgument = $input->getArgument('movie-id');
75
            if (isset($movieArgument)) {
76
                $torrentsUrls = $this->getMovieTorrentsUrls(
77
                    $weburgClient,
78
                    $movieArgument,
79
                    $daysMax,
80
                    $allowedMisses
81
                );
82
            } else {
83
                $torrentsUrls = $this->getTorrentsUrls(
84
                    $input,
85
                    $output,
86
                    $weburgClient,
87
                    $downloadDir,
88
                    $daysMax,
89
                    $allowedMisses
90
                );
91
            }
92
93
            $this->dryRun($input, $output, function () use (
94
                $input,
95
                $output,
96
                $weburgClient,
97
                $torrentsDir,
98
                $torrentsUrls
99
            ) {
100
                if (empty($torrentsUrls)) {
101
                    $output->writeln("\nNo torrents for download");
102
                    return;
103
                }
104
105
                $limit = $input->getOption('limit');
106
                if ($limit && count($torrentsUrls) > $limit) {
107
                    $output->writeln("\nLimit list from " . count($torrentsUrls) . " to $limit");
108
                    $torrentsUrls = array_slice($torrentsUrls, 0, $limit);
0 ignored issues
show
Consider using a different name than the imported variable $torrentsUrls, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
109
                }
110
111
                $downloadedFiles = [];
112
                foreach ($torrentsUrls as $torrentUrl) {
113
                    $downloadedFiles[] = $weburgClient->downloadTorrent($torrentUrl, $torrentsDir);
114
                }
115
116
                $downloadedFiles = $this->filterByLists($downloadedFiles);
117
                if (!empty($downloadedFiles)) {
118
                    $this->addTorrents($input, $output, $downloadedFiles);
119
                } else {
120
                    $output->writeln("\nAll torrents filtered by black/whitelists");
121
                }
122
            }, 'dry-run, don\'t really download');
123
        } catch (\RuntimeException $e) {
124
            $output->writeln($e->getMessage());
125
            return 1;
126
        }
127
128
        return 0;
129
    }
130
131
    private function getTorrentsUrls(
132
        InputInterface $input,
133
        OutputInterface $output,
134
        WeburgClient $weburgClient,
135
        $downloadDir,
136
        $daysMax,
137
        $allowedMisses
138
    ) {
139
        $torrentsUrls = [];
140
141
        if ($input->getOption('query')) {
142
            $torrentsUrls = array_merge(
143
                $torrentsUrls,
144
                $this->getTorrentsUrlByQuery($output, $weburgClient, $downloadDir, $input->getOption('query'))
145
            );
146
        }
147
148
        if (!$input->getOption('popular') && !$input->getOption('series') && !$input->getOption('query')) {
149
            $input->setOption('popular', true);
150
            $input->setOption('series', true);
151
        }
152
153
        if ($input->getOption('popular')) {
154
            $moviesUrl = $input->getOption('movies-url');
155
            $torrentsUrls = array_merge(
156
                $torrentsUrls,
157
                $this->getPopularTorrentsUrls($output, $weburgClient, $downloadDir, $moviesUrl)
158
            );
159
        }
160
161
        if ($input->getOption('series')) {
162
            $torrentsUrls = array_merge(
163
                $torrentsUrls,
164
                $this->getTrackedSeriesUrls($output, $weburgClient, $daysMax, $allowedMisses)
165
            );
166
        }
167
168
        return $torrentsUrls;
169
    }
170
171
    public function getTorrentsUrlByQuery(OutputInterface $output, WeburgClient $weburgClient, $downloadDir, $query)
172
    {
173
        $torrentsUrls = [];
174
175
        $logger = $this->getApplication()->getLogger();
176
177
        $movieId = $weburgClient->getMovieIdByQuery($query);
178
        if (!$movieId) {
179
            $output->writeln("\nNot found any for query $query");
180
        }
181
182
        $downloadedLogfile = $downloadDir . '/' . $movieId;
183
184
        $isDownloaded = file_exists($downloadedLogfile);
185
        if ($isDownloaded) {
186
            $output->writeln("\nMovie $query was downloaded before");
187
        }
188
189
        $movieInfo = $weburgClient->getMovieInfoById($movieId);
190 View Code Duplication
        foreach (array_keys($movieInfo) as $infoField) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
191
            if (!isset($movieInfo[$infoField])) {
192
                $logger->warning('Cannot find ' . $infoField . ' in movie ' . $movieId);
193
            }
194
        }
195
196
        $movieUrls = $weburgClient->getMovieTorrentUrlsById($movieId);
197
        $torrentsUrls = array_merge($torrentsUrls, $movieUrls);
198
        $logger->info('Download movie ' . $movieId . ': ' . $movieInfo['title']);
199
200
        file_put_contents(
201
            $downloadedLogfile,
202
            date('Y-m-d H:i:s') . "\n" . implode("\n", $torrentsUrls)
203
        );
204
205
        return $torrentsUrls;
206
    }
207
208
    public function getPopularTorrentsUrls(
209
        OutputInterface $output,
210
        WeburgClient $weburgClient,
211
        $downloadDir,
212
        $moviesUrl = null
213
    ) {
214
        $torrentsUrls = [];
215
216
        $config = $this->getApplication()->getConfig();
217
        $logger = $this->getApplication()->getLogger();
218
219
        $moviesIds = $weburgClient->getMoviesIds($moviesUrl);
220
221
        $output->writeln("\nDownloading popular torrents");
222
223
        $progress = new ProgressBar($output, count($moviesIds));
224
        $progress->start();
225
226
        foreach ($moviesIds as $movieId) {
227
            $progress->setMessage('Check movie ' . $movieId . '...');
228
            $progress->advance();
229
230
            $downloadedLogfile = $downloadDir . '/' . $movieId;
231
232
            $isDownloaded = file_exists($downloadedLogfile);
233
            if ($isDownloaded) {
234
                continue;
235
            }
236
237
            $movieInfo = $weburgClient->getMovieInfoById($movieId);
238 View Code Duplication
            foreach (array_keys($movieInfo) as $infoField) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
                if (!isset($movieInfo[$infoField])) {
240
                    $logger->warning('Cannot find ' . $infoField . ' in movie ' . $movieId);
241
                }
242
            }
243
244
            $isTorrentPopular = $weburgClient->isTorrentPopular(
245
                $movieInfo,
246
                $config->get('download-comments-min'),
247
                $config->get('download-imdb-min'),
248
                $config->get('download-kinopoisk-min'),
249
                $config->get('download-votes-min')
250
            );
251
252
            if ($isTorrentPopular) {
253
                $progress->setMessage('Download movie ' . $movieId . '...');
254
255
                $movieUrls = $weburgClient->getMovieTorrentUrlsById($movieId);
256
                $torrentsUrls = array_merge($torrentsUrls, $movieUrls);
257
                $logger->info('Download movie ' . $movieId . ': ' . $movieInfo['title']);
258
259
                file_put_contents(
260
                    $downloadedLogfile,
261
                    date('Y-m-d H:i:s') . "\n" . implode("\n", $torrentsUrls)
262
                );
263
            }
264
        }
265
266
        $progress->finish();
267
268
        return $torrentsUrls;
269
    }
270
271
    /**
272
     * @param OutputInterface $output
273
     * @param WeburgClient $weburgClient
274
     * @param $daysMax
275
     * @param $allowedMisses
276
     * @return array
277
     */
278
    public function getTrackedSeriesUrls(OutputInterface $output, WeburgClient $weburgClient, $daysMax, $allowedMisses)
279
    {
280
        $torrentsUrls = [];
281
282
        $config = $this->getApplication()->getConfig();
283
284
        $seriesList = $config->get('weburg-series-list');
285
        if (!$seriesList) {
286
            return [];
287
        }
288
289
        $output->writeln("\nDownloading tracked series");
290
291
        $progress = new ProgressBar($output, count($seriesList));
292
        $progress->start();
293
294
        foreach ($seriesList as $seriesItem) {
295
            if (is_array($seriesItem)) {
296
                $seriesId = $seriesItem['id'];
297
                $seriesTitle = isset($seriesItem['title']) && $seriesItem['title'] ? $seriesItem['title'] : $seriesId;
298
            } else {
299
                $seriesId = $seriesTitle = $seriesItem;
300
            }
301
            $progress->setMessage('Check series ' . $seriesTitle . '...');
302
            $progress->advance();
303
304
            $movieInfo = $weburgClient->getMovieInfoById($seriesId);
305
            $seriesUrls = $weburgClient->getSeriesTorrents($seriesId, $movieInfo['hashes'], $daysMax, $allowedMisses);
306
            $torrentsUrls = array_merge($torrentsUrls, $seriesUrls);
307
        }
308
309
        $progress->finish();
310
311
        return $torrentsUrls;
312
    }
313
314
    /**
315
     * @param WeburgClient $weburgClient
316
     * @param $movieId
317
     * @param $daysMax
318
     * @param $allowedMisses
319
     * @return array
320
     */
321
    public function getMovieTorrentsUrls(WeburgClient $weburgClient, $movieId, $daysMax, $allowedMisses)
322
    {
323
        $torrentsUrls = [];
324
        $logger = $this->getApplication()->getLogger();
325
326
        $movieId = $weburgClient->cleanMovieId($movieId);
327
        if (!$movieId) {
328
            throw new \RuntimeException($movieId . ' seems not weburg movie ID or URL');
329
        }
330
331
        $movieInfo = $weburgClient->getMovieInfoById($movieId);
332
        $logger->info('Search series ' . $movieId);
333
        if (!empty($movieInfo['hashes'])) {
334
            $seriesUrls = $weburgClient->getSeriesTorrents($movieId, $movieInfo['hashes'], $daysMax, $allowedMisses);
335
            $torrentsUrls = array_merge($torrentsUrls, $seriesUrls);
336
337
            if (count($seriesUrls)) {
338
                $logger->info('Download series ' . $movieId . ': '
339
                    . $movieInfo['title'] . ' (' . count($seriesUrls) . ')');
340
            }
341
        } else {
342
            $torrentsUrls = array_merge($torrentsUrls, $weburgClient->getMovieTorrentUrlsById($movieId));
343
        }
344
345
        return $torrentsUrls;
346
    }
347
348
    /**
349
     * @param InputInterface $input
350
     * @return array
351
     * @throws \RuntimeException
352
     */
353
    private function getTorrentsDirectory(InputInterface $input)
354
    {
355
        $config = $this->getApplication()->getConfig();
356
357
        $torrentsDir = $config->overrideConfig($input, 'download-torrents-dir');
358
        if (!$torrentsDir) {
359
            throw new \RuntimeException('Destination directory not defined. '
360
                . 'Use command with --download-torrents-dir=/path/to/dir parameter '
361
                . 'or define destination directory \'download-torrents-dir\' in config file.');
362
        }
363
364
        if (!file_exists($torrentsDir)) {
365
            throw new \RuntimeException('Destination directory not exists: ' . $torrentsDir);
366
        }
367
368
        $downloadDir = $torrentsDir . '/downloaded';
369
        if (!file_exists($downloadDir)) {
370
            mkdir($downloadDir, 0777);
371
        }
372
373
        return [$torrentsDir, $downloadDir];
374
    }
375
376
    private function filterByLists(array $torrentFiles)
377
    {
378
        $config = $this->getApplication()->getConfig();
379
        $logger = $this->getApplication()->getLogger();
380
381
        $whitelist = $config->get('download-filename-whitelist');
382
        $blacklist = $config->get('download-filename-blacklist');
383
384
        $torrentFiles = array_filter($torrentFiles, function ($torrentFile) use ($whitelist, $blacklist, $logger) {
385
            if (!empty($whitelist)) {
386
                $matched = false;
387
                foreach ($whitelist as $white) {
388
                    if (preg_match('/' . $white . '/i', $torrentFile)) {
389
                        $logger->info($torrentFile . ' matched whitelist: ' . $white);
390
                        $matched = true;
391
                    }
392
                }
393
                if (!$matched) {
394
                    $logger->info($torrentFile . ' not matched any whitelist: ' . implode(', ', $whitelist));
395
                    return false;
396
                }
397
            }
398
            if (!empty($blacklist)) {
399
                foreach ($blacklist as $black) {
400
                    if (preg_match('/' . $black . '/i', $torrentFile)) {
401
                        $logger->info($torrentFile . ' matched blacklist: ' . $black);
402
                        return false;
403
                    }
404
                }
405
            }
406
            return true;
407
        });
408
        return $torrentFiles;
409
    }
410
411
    private function addTorrents(InputInterface $input, OutputInterface $output, array $torrentFiles)
412
    {
413
        $config = $this->getApplication()->getConfig();
414
        $hosts = [];
415
416
        if (empty($input->getOption('transmission-host'))) {
417
            $transmissionConnects = $config->get('transmission');
418
            foreach ($transmissionConnects as $transmissionConnect) {
419
                $hosts[] = $transmissionConnect['host'];
420
            }
421
        } else {
422
            $hosts[] = $config->get('transmission-host');
423
        }
424
425
        foreach ($hosts as $host) {
426
            $command = $this->getApplication()->find('torrent-add');
427
            $arguments = array(
428
                'command'             => 'torrent-add',
429
                'torrent-files'       => $torrentFiles,
430
                '--transmission-host' => $host,
431
                '--yes'               => $input->getOption('yes'),
432
                '--dry-run'           => $input->getOption('dry-run'),
433
            );
434
435
            $addInput = new ArrayInput($arguments);
436
            $output->writeln("\nAdd " . count($torrentFiles) . " torrents to " . $host);
437
            $command->run($addInput, $output);
438
        }
439
    }
440
}
441