Completed
Push — dev ( a9cf94...2698ac )
by Darko
07:42
created

getRawHtmlThroughCF()   A

Complexity

Conditions 6
Paths 14

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 14
nop 1
dl 0
loc 24
ccs 0
cts 10
cp 0
crap 42
rs 9.1111
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A makeFieldLinks() 0 21 6
1
<?php
2
3
use Colors\Color;
4
use Blacklight\NZB;
5
use Blacklight\XXX;
6
use GuzzleHttp\Client;
7
use App\Models\Release;
8
use DariusIII\Zipper\Zipper;
9
use Blacklight\utility\Utility;
10
use GuzzleHttp\Cookie\CookieJar;
11
use GuzzleHttp\Cookie\SetCookie;
12
use Illuminate\Support\Facades\DB;
13
use Illuminate\Support\Facades\Log;
14
use Symfony\Component\Process\Process;
15
use GuzzleHttp\Exception\RequestException;
16
17
if (! function_exists('getRawHtml')) {
18
19
    /**
20
     * @param      $url
21
     * @param bool $cookie
22
     *
23
     * @return bool|mixed|string
24
     */
25
    function getRawHtml($url, $cookie = false)
26
    {
27
        $cookieJar = new CookieJar();
28
        $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']]);
29
        if ($cookie !== false) {
30
            $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

30
            $cookie = $cookieJar->setCookie(SetCookie::fromString(/** @scrutinizer ignore-type */ $cookie));
Loading history...
31
            $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']]);
32
        }
33
        try {
34
            $response = $client->get($url)->getBody()->getContents();
35
            $jsonResponse = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
36
            if (json_last_error() === JSON_ERROR_NONE) {
37
                $response = $jsonResponse;
38
            }
39
        } catch (RequestException $e) {
40
            if (config('app.debug') === true) {
41
                Log::error($e->getMessage());
42
            }
43
            $response = false;
44
        } catch (\RuntimeException $e) {
45
            if (config('app.debug') === true) {
46
                Log::error($e->getMessage());
47
            }
48
            $response = false;
49
        }
50
51
        return $response;
52
    }
53
}
54
55
if (! function_exists('makeFieldLinks')) {
56
57
    /**
58
     * @param $data
59
     * @param $field
60
     * @param $type
61
     *
62
     * @return string
63
     * @throws \Exception
64
     */
65
    function makeFieldLinks($data, $field, $type)
66
    {
67
        $tmpArr = explode(', ', $data[$field]);
68
        $newArr = [];
69
        $i = 0;
70
        foreach ($tmpArr as $ta) {
71
            if (trim($ta) === '') {
72
                continue;
73
            }
74
            if ($type === 'xxx' && $field === 'genre') {
75
                $ta = (new XXX())->getGenres(true, $ta);
76
                $ta = $ta['title'];
77
            }
78
            if ($i > 7) {
79
                break;
80
            }
81
            $newArr[] = '<a href="'.WWW_TOP.'/'.ucfirst($type).'?'.$field.'='.urlencode($ta).'" title="'.$ta.'">'.$ta.'</a>';
0 ignored issues
show
Bug introduced by
The constant WWW_TOP was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
82
            $i++;
83
        }
84
85
        return implode(', ', $newArr);
86
    }
87
}
88
89
if (! function_exists('getUserBrowseOrder')) {
90
    /**
91
     * @param string $orderBy
92
     *
93
     * @return array
94
     */
95
    function getUserBrowseOrder($orderBy): array
96
    {
97
        $order = ($orderBy === '' ? 'username_desc' : $orderBy);
98
        $orderArr = explode('_', $order);
99
        switch ($orderArr[0]) {
100
            case 'email':
101
                $orderField = 'email';
102
                break;
103
            case 'host':
104
                $orderField = 'host';
105
                break;
106
            case 'createdat':
107
                $orderField = 'created_at';
108
                break;
109
            case 'lastlogin':
110
                $orderField = 'lastlogin';
111
                break;
112
            case 'apiaccess':
113
                $orderField = 'apiaccess';
114
                break;
115
            case 'apirequests':
116
                $orderField = 'apirequests';
117
                break;
118
            case 'grabs':
119
                $orderField = 'grabs';
120
                break;
121
            case 'roles_id':
122
                $orderField = 'users_role_id';
123
                break;
124
            case 'rolechangedate':
125
                $orderField = 'rolechangedate';
126
                break;
127
            default:
128
                $orderField = 'username';
129
                break;
130
        }
131
        $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
132
133
        return [$orderField, $orderSort];
134
    }
135
}
136
137
if (! function_exists('getUserBrowseOrdering')) {
138
139
    /**
140
     * @return array
141
     */
142
    function getUserBrowseOrdering(): array
143
    {
144
        return [
145
            'username_asc',
146
            'username_desc',
147
            'email_asc',
148
            'email_desc',
149
            'host_asc',
150
            'host_desc',
151
            'createdat_asc',
152
            'createdat_desc',
153
            'lastlogin_asc',
154
            'lastlogin_desc',
155
            'apiaccess_asc',
156
            'apiaccess_desc',
157
            'apirequests_asc',
158
            'apirequests_desc',
159
            'grabs_asc',
160
            'grabs_desc',
161
            'role_asc',
162
            'role_desc',
163
            'rolechangedate_asc',
164
            'rolechangedate_desc',
165
            'verification_asc',
166
            'verification_desc',
167
        ];
168
    }
169
}
170
171
if (! function_exists('createGUID')) {
172
    /**
173
     * @return string
174
     * @throws \Exception
175
     */
176
    function createGUID(): string
177
    {
178
        $data = random_bytes(16);
179
        $data[6] = \chr(\ord($data[6]) & 0x0f | 0x40);    // set version to 0100
180
        $data[8] = \chr(\ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
181
182
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(sodium_bin2hex($data), 4));
183
    }
184
}
185
186
if (! function_exists('getSimilarName')) {
187
    /**
188
     * @param string $name
189
     *
190
     * @return string
191
     */
192
    function getSimilarName($name): string
193
    {
194
        return implode(' ', \array_slice(str_word_count(str_replace(['.', '_'], ' ', $name), 2), 0, 2));
195
    }
196
}
197
198
if (! function_exists('color')) {
199
    /**
200
     * @param string $string
201
     *
202
     * @return \Colors\Color
203
     */
204
    function color($string = ''): Color
205
    {
206
        return new Color($string);
207
    }
208
}
209
210
if (! function_exists('human_filesize')) {
211
212
    /**
213
     * @param     $bytes
214
     * @param int $decimals
215
     *
216
     * @return string
217
     */
218
    function human_filesize($bytes, $decimals = 0): string
219
    {
220
        $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
221
        $factor = floor((\strlen($bytes) - 1) / 3);
222
223
        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 expected by parameter $val 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

223
        return round(/** @scrutinizer ignore-type */ sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
Loading history...
224
    }
225
}
226
227
if (! function_exists('bcdechex')) {
228
229
    /**
230
     * @param $dec
231
     *
232
     * @return string
233
     */
234
    function bcdechex($dec)
235
    {
236
        $hex = '';
237
        do {
238
            $last = bcmod($dec, 16);
239
            $hex = dechex($last).$hex;
0 ignored issues
show
Bug introduced by
It seems like $last can also be of type string; however, parameter $number of dechex() does only seem to accept integer, 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

239
            $hex = dechex(/** @scrutinizer ignore-type */ $last).$hex;
Loading history...
240
            $dec = bcdiv(bcsub($dec, $last), 16);
241
        } while ($dec > 0);
242
243
        return $hex;
244
    }
245
}
246
247
if (! function_exists('runCmd')) {
248
    /**
249
     * Run CLI command.
250
     *
251
     *
252
     * @param string $command
253
     * @param bool $debug
254
     *
255
     * @return string
256
     */
257
    function runCmd($command, $debug = false)
258
    {
259
        if ($debug) {
260
            echo '-Running Command: '.PHP_EOL.'   '.$command.PHP_EOL;
261
        }
262
263
        $process = new Process($command);
0 ignored issues
show
Bug introduced by
$command of type string is incompatible with the type array expected by parameter $command of Symfony\Component\Process\Process::__construct(). ( Ignorable by Annotation )

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

263
        $process = new Process(/** @scrutinizer ignore-type */ $command);
Loading history...
264
        $process->run();
265
        $output = $process->getOutput();
266
267
        if ($debug) {
268
            echo '-Command Output: '.PHP_EOL.'   '.$output.PHP_EOL;
269
        }
270
271
        return $output;
272
    }
273
}
274
275
if (! function_exists('escapeString')) {
276
277
    /**
278
     * @param $string
279
     *
280
     * @return string
281
     */
282
    function escapeString($string)
283
    {
284
        return DB::connection()->getPdo()->quote($string);
285
    }
286
}
287
288
if (! function_exists('realDuration')) {
289
290
    /**
291
     * @param $milliseconds
292
     *
293
     * @return string
294
     */
295
    function realDuration($milliseconds)
296
    {
297
        $time = round($milliseconds / 1000);
298
299
        return sprintf('%02dh:%02dm:%02ds', $time / 3600, $time / 60 % 60, $time % 60);
300
    }
301
}
302
303
if (! function_exists('is_it_json')) {
304
305
    /**
306
     * @param array|string $isIt
307
     * @return bool
308
     */
309
    function is_it_json($isIt)
310
    {
311
        if (is_array($isIt)) {
312
            return false;
313
        }
314
        json_decode($isIt, true, 512, JSON_THROW_ON_ERROR);
315
316
        return json_last_error() === JSON_ERROR_NONE;
317
    }
318
}
319
320
if (! function_exists('getZipped')) {
321
322
    /**
323
     * @param array $guids
324
     *
325
     * @return string
326
     * @throws \Exception
327
     */
328
    function getZipped(array $guids = []): string
329
    {
330
        $nzb = new NZB();
331
        $zipped = new Zipper();
332
        $zippedFileName = now()->format('Ymdhis').'.nzb.zip';
333
        $zippedFilePath = resource_path().'/tmp/'.$zippedFileName;
334
335
        foreach ($guids as $guid) {
336
            $nzbPath = $nzb->NZBPath($guid);
337
338
            if ($nzbPath) {
339
                $nzbContents = Utility::unzipGzipFile($nzbPath);
340
341
                if ($nzbContents) {
342
                    $filename = $guid;
343
                    $r = Release::getByGuid($guid);
344
                    if ($r) {
345
                        $filename = $r['searchname'];
346
                    }
347
                    $zipped->make($zippedFilePath)->addString($filename.'.nzb', $nzbContents);
348
                }
349
            }
350
        }
351
352
        $zipped->close();
353
354
        return File::isFile($zippedFilePath) ? $zippedFilePath : '';
355
    }
356
}
357