Passed
Push — master ( 7c7ef1...c44bee )
by Darko
09:22
created

createGUID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
use App\Models\Release;
4
use Blacklight\NZB;
5
use Blacklight\utility\Utility;
6
use Blacklight\XXX;
7
use Colors\Color;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Cookie\CookieJar;
10
use GuzzleHttp\Cookie\SetCookie;
11
use GuzzleHttp\Exception\RequestException;
12
use Illuminate\Support\Facades\DB;
13
use Illuminate\Support\Facades\Log;
14
use Illuminate\Support\Str;
15
use sspat\ESQuerySanitizer\Sanitizer;
16
use Symfony\Component\Process\Process;
17
use Zip as ZipStream;
18
19
if (! function_exists('getRawHtml')) {
20
    /**
21
     * @param  bool  $cookie
22
     * @return bool|mixed|string
23
     */
24
    function getRawHtml($url, $cookie = false)
25
    {
26
        $cookieJar = new CookieJar;
27
        $client = new Client(['headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246']]);
28
        if ($cookie !== false) {
29
            $cookie = $cookieJar->setCookie(SetCookie::fromString($cookie));
0 ignored issues
show
Bug introduced by
$cookie of type true is incompatible with the type string expected by parameter $cookie of GuzzleHttp\Cookie\SetCookie::fromString(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

29
            $cookie = $cookieJar->setCookie(SetCookie::fromString(/** @scrutinizer ignore-type */ $cookie));
Loading history...
30
            $client = new Client(['cookies' => $cookie, 'headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246']]);
31
        }
32
        try {
33
            $response = $client->get($url)->getBody()->getContents();
34
            $jsonResponse = json_decode($response, true);
35
            if (json_last_error() === JSON_ERROR_NONE) {
36
                $response = $jsonResponse;
37
            }
38
        } catch (RequestException $e) {
39
            if (config('app.debug') === true) {
40
                Log::error($e->getMessage());
41
            }
42
            $response = false;
43
        } catch (RuntimeException $e) {
44
            if (config('app.debug') === true) {
45
                Log::error($e->getMessage());
46
            }
47
            $response = false;
48
        }
49
50
        return $response;
51
    }
52
}
53
54
if (! function_exists('makeFieldLinks')) {
55
    /**
56
     * @return string
57
     *
58
     * @throws Exception
59
     */
60
    function makeFieldLinks($data, $field, $type)
61
    {
62
        $tmpArr = explode(', ', $data[$field]);
63
        $newArr = [];
64
        $i = 0;
65
        foreach ($tmpArr as $ta) {
66
            if (trim($ta) === '') {
67
                continue;
68
            }
69
            if ($type === 'xxx' && $field === 'genre') {
70
                $ta = (new XXX)->getGenres(true, $ta);
71
                $ta = $ta['title'] ?? '';
72
            }
73
            if ($i > 7) {
74
                break;
75
            }
76
            $newArr[] = '<a href="'.url('/'.ucfirst($type).'?'.$field.'='.urlencode($ta)).'" title="'.$ta.'">'.$ta.'</a>';
77
            $i++;
78
        }
79
80
        return implode(', ', $newArr);
81
    }
82
}
83
84
if (! function_exists('getUserBrowseOrder')) {
85
    /**
86
     * @param  string  $orderBy
87
     */
88
    function getUserBrowseOrder($orderBy): array
89
    {
90
        $order = ($orderBy === '' ? 'username_desc' : $orderBy);
91
        $orderArr = explode('_', $order);
92
        $orderField = match ($orderArr[0]) {
93
            'email' => 'email',
94
            'host' => 'host',
95
            'createdat' => 'created_at',
96
            'lastlogin' => 'lastlogin',
97
            'apiaccess' => 'apiaccess',
98
            'apirequests' => 'apirequests',
99
            'grabs' => 'grabs',
100
            'roles_id' => 'users_role_id',
101
            'rolechangedate' => 'rolechangedate',
102
            default => 'username',
103
        };
104
        $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
105
106
        return [$orderField, $orderSort];
107
    }
108
}
109
110
if (! function_exists('getUserBrowseOrdering')) {
111
    function getUserBrowseOrdering(): array
112
    {
113
        return [
114
            'username_asc',
115
            'username_desc',
116
            'email_asc',
117
            'email_desc',
118
            'host_asc',
119
            'host_desc',
120
            'createdat_asc',
121
            'createdat_desc',
122
            'lastlogin_asc',
123
            'lastlogin_desc',
124
            'apiaccess_asc',
125
            'apiaccess_desc',
126
            'apirequests_asc',
127
            'apirequests_desc',
128
            'grabs_asc',
129
            'grabs_desc',
130
            'role_asc',
131
            'role_desc',
132
            'rolechangedate_asc',
133
            'rolechangedate_desc',
134
            'verification_asc',
135
            'verification_desc',
136
        ];
137
    }
138
}
139
140
if (! function_exists('getSimilarName')) {
141
    /**
142
     * @param  string  $name
143
     */
144
    function getSimilarName($name): string
145
    {
146
        return implode(' ', \array_slice(str_word_count(str_replace(['.', '_', '-'], ' ', $name), 2), 0, 2));
0 ignored issues
show
Bug introduced by
It seems like str_word_count(str_repla..., '-'), ' ', $name), 2) can also be of type integer; however, parameter $array of array_slice() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

146
        return implode(' ', \array_slice(/** @scrutinizer ignore-type */ str_word_count(str_replace(['.', '_', '-'], ' ', $name), 2), 0, 2));
Loading history...
147
    }
148
}
149
150
if (! function_exists('color')) {
151
    /**
152
     * @param  string  $string
153
     */
154
    function color($string = ''): Color
155
    {
156
        return new Color($string);
157
    }
158
}
159
160
if (! function_exists('human_filesize')) {
161
    /**
162
     * @param  int  $decimals
163
     */
164
    function human_filesize($bytes, $decimals = 0): string
165
    {
166
        $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
167
        $factor = floor((\strlen($bytes) - 1) / 3);
168
169
        return round(sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
0 ignored issues
show
Bug introduced by
sprintf('%.'.$decimals.'...ytes / 1024 ** $factor) of type string is incompatible with the type double|integer expected by parameter $num of round(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

169
        return round(/** @scrutinizer ignore-type */ sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
Loading history...
170
    }
171
}
172
173
if (! function_exists('bcdechex')) {
174
    /**
175
     * @return string
176
     */
177
    function bcdechex($dec)
178
    {
179
        $hex = '';
180
        do {
181
            $last = bcmod($dec, 16);
182
            $hex = dechex($last).$hex;
0 ignored issues
show
Bug introduced by
$last of type null|string is incompatible with the type integer expected by parameter $num of dechex(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

182
            $hex = dechex(/** @scrutinizer ignore-type */ $last).$hex;
Loading history...
183
            $dec = bcdiv(bcsub($dec, $last), 16);
184
        } while ($dec > 0);
185
186
        return $hex;
187
    }
188
}
189
190
if (! function_exists('runCmd')) {
191
    /**
192
     * Run CLI command.
193
     *
194
     *
195
     * @param  string  $command
196
     * @param  bool  $debug
197
     * @return string
198
     */
199
    function runCmd($command, $debug = false)
200
    {
201
        if ($debug) {
202
            echo '-Running Command: '.PHP_EOL.'   '.$command.PHP_EOL;
203
        }
204
205
        $process = Process::fromShellCommandline('exec '.$command);
206
        $process->setTimeout(1800);
207
        $process->run();
208
        $output = $process->getOutput();
209
210
        if ($debug) {
211
            echo '-Command Output: '.PHP_EOL.'   '.$output.PHP_EOL;
212
        }
213
214
        return $output;
215
    }
216
}
217
218
if (! function_exists('escapeString')) {
219
    /**
220
     * @return string
221
     */
222
    function escapeString($string)
223
    {
224
        return DB::connection()->getPdo()->quote($string);
225
    }
226
}
227
228
if (! function_exists('realDuration')) {
229
    /**
230
     * @return string
231
     */
232
    function realDuration($milliseconds)
233
    {
234
        $time = round($milliseconds / 1000);
235
236
        return sprintf('%02dh:%02dm:%02ds', floor($time / 3600), floor($time / 60 % 60), $time % 60);
237
    }
238
}
239
240
if (! function_exists('is_it_json')) {
241
    /**
242
     * @param  array|string  $isIt
243
     * @return bool
244
     */
245
    function is_it_json($isIt)
246
    {
247
        if (is_array($isIt)) {
248
            return false;
249
        }
250
        json_decode($isIt, true);
251
252
        return json_last_error() === JSON_ERROR_NONE;
253
    }
254
}
255
256
/**
257
 * @throws Exception
258
 */
259
function getStreamingZip(array $guids = []): STS\ZipStream\ZipStream
260
{
261
    $nzb = new NZB;
262
    $zipped = ZipStream::create(now()->format('Ymdhis').'.zip');
263
    foreach ($guids as $guid) {
264
        $nzbPath = $nzb->NZBPath($guid);
265
266
        if ($nzbPath) {
267
            $nzbContents = Utility::unzipGzipFile($nzbPath);
268
269
            if ($nzbContents) {
270
                $filename = $guid;
271
                $r = Release::query()->where('guid', $guid)->first();
272
                if ($r !== null) {
273
                    $filename = $r->searchname;
0 ignored issues
show
Bug introduced by
The property searchname does not seem to exist on App\Models\Release. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
274
                }
275
                $zipped->addRaw($nzbContents, $filename.'.nzb');
276
            }
277
        }
278
    }
279
280
    return $zipped;
281
}
282
283
if (! function_exists('release_flag')) {
284
    // Function inspired by c0r3@newznabforums adds country flags on the browse page.
285
    /**
286
     * @param  string  $text  Text to match against.
287
     * @param  string  $page  Type of page. browse or search.
288
     * @return bool|string
289
     */
290
    function release_flag($text, $page)
291
    {
292
        $code = $language = '';
293
294
        switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/\bHindi\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/French|Vostfr|Multi/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/\bGreek\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Italian|\bita\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/\bCzech\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/German(bed)?|\bger\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Flemish|\b(...|nl)\b|NlSub/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Japanese|\bjp\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Hebrew|Yiddish/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Korean|\bkr\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Tagalog|Filipino/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Hungarian|\bhun\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/\bThai\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Swe(dish|sub)/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/Chinese|Man...in|\bc[hn]\b/i', $text) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
295
            case stripos($text, 'Arabic') !== false:
296
                $code = 'PK';
297
                $language = 'Arabic';
298
                break;
299
            case stripos($text, 'Cantonese') !== false:
300
                $code = 'TW';
301
                $language = 'Cantonese';
302
                break;
303
            case preg_match('/Chinese|Mandarin|\bc[hn]\b/i', $text):
304
                $code = 'CN';
305
                $language = 'Chinese';
306
                break;
307
            case preg_match('/\bCzech\b/i', $text):
308
                $code = 'CZ';
309
                $language = 'Czech';
310
                break;
311
            case stripos($text, 'Danish') !== false:
312
                $code = 'DK';
313
                $language = 'Danish';
314
                break;
315
            case stripos($text, 'Finnish') !== false:
316
                $code = 'FI';
317
                $language = 'Finnish';
318
                break;
319
            case preg_match('/Flemish|\b(Dutch|nl)\b|NlSub/i', $text):
320
                $code = 'NL';
321
                $language = 'Dutch';
322
                break;
323
            case preg_match('/French|Vostfr|Multi/i', $text):
324
                $code = 'FR';
325
                $language = 'French';
326
                break;
327
            case preg_match('/German(bed)?|\bger\b/i', $text):
328
                $code = 'DE';
329
                $language = 'German';
330
                break;
331
            case preg_match('/\bGreek\b/i', $text):
332
                $code = 'GR';
333
                $language = 'Greek';
334
                break;
335
            case preg_match('/Hebrew|Yiddish/i', $text):
336
                $code = 'IL';
337
                $language = 'Hebrew';
338
                break;
339
            case preg_match('/\bHindi\b/i', $text):
340
                $code = 'IN';
341
                $language = 'Hindi';
342
                break;
343
            case preg_match('/Hungarian|\bhun\b/i', $text):
344
                $code = 'HU';
345
                $language = 'Hungarian';
346
                break;
347
            case preg_match('/Italian|\bita\b/i', $text):
348
                $code = 'IT';
349
                $language = 'Italian';
350
                break;
351
            case preg_match('/Japanese|\bjp\b/i', $text):
352
                $code = 'JP';
353
                $language = 'Japanese';
354
                break;
355
            case preg_match('/Korean|\bkr\b/i', $text):
356
                $code = 'KR';
357
                $language = 'Korean';
358
                break;
359
            case stripos($text, 'Norwegian') !== false:
360
                $code = 'NO';
361
                $language = 'Norwegian';
362
                break;
363
            case stripos($text, 'Polish') !== false:
364
                $code = 'PL';
365
                $language = 'Polish';
366
                break;
367
            case stripos($text, 'Portuguese') !== false:
368
                $code = 'PT';
369
                $language = 'Portugese';
370
                break;
371
            case stripos($text, 'Romanian') !== false:
372
                $code = 'RO';
373
                $language = 'Romanian';
374
                break;
375
            case stripos($text, 'Spanish') !== false:
376
                $code = 'ES';
377
                $language = 'Spanish';
378
                break;
379
            case preg_match('/Swe(dish|sub)/i', $text):
380
                $code = 'SE';
381
                $language = 'Swedish';
382
                break;
383
            case preg_match('/Tagalog|Filipino/i', $text):
384
                $code = 'PH';
385
                $language = 'Tagalog|Filipino';
386
                break;
387
            case preg_match('/\bThai\b/i', $text):
388
                $code = 'TH';
389
                $language = 'Thai';
390
                break;
391
            case stripos($text, 'Turkish') !== false:
392
                $code = 'TR';
393
                $language = 'Turkish';
394
                break;
395
            case stripos($text, 'Russian') !== false:
396
                $code = 'RU';
397
                $language = 'Russian';
398
                break;
399
            case stripos($text, 'Vietnamese') !== false:
400
                $code = 'VN';
401
                $language = 'Vietnamese';
402
                break;
403
        }
404
405
        if ($code !== '' && $page === 'browse') {
406
            return '<img title="'.$language.'" alt="'.$language.'" src="'.asset('/assets/images/flags/'.$code.'.png').'"/>';
407
        }
408
409
        if ($page === 'search') {
410
            if ($code === '') {
411
                return false;
412
            }
413
414
            return $code;
415
        }
416
417
        return '';
418
    }
419
    if (! function_exists('sanitize')) {
420
        function sanitize(array|string $phrases, array $doNotSanitize = []): string
421
        {
422
            if (! is_array($phrases)) {
0 ignored issues
show
introduced by
The condition is_array($phrases) is always true.
Loading history...
423
                $wordArray = explode(' ', str_replace('.', ' ', $phrases));
424
            } else {
425
                $wordArray = $phrases;
426
            }
427
428
            $keywords = [];
429
            $tempWords = [];
430
            foreach ($wordArray as $words) {
431
                $words = preg_split('/\s+/', $words);
432
                foreach ($words as $st) {
433
                    if (Str::startsWith($st, ['!', '+', '-', '?', '*']) && Str::length($st) > 1 && ! preg_match('/([!+?\-*]){2,}/', $st)) {
434
                        $str = $st;
435
                    } elseif (Str::endsWith($st, ['+', '-', '?', '*']) && Str::length($st) > 1 && ! preg_match('/([!+?\-*]){2,}/', $st)) {
436
                        $str = $st;
437
                    } else {
438
                        $str = Sanitizer::escape($st, $doNotSanitize);
439
                    }
440
                    $tempWords[] = $str;
441
                }
442
443
                $keywords = $tempWords;
444
            }
445
446
            return implode(' ', $keywords);
447
        }
448
    }
449
}
450