Completed
Push — dev ( 28182b...2f6da2 )
by Darko
14:04 queued 05:10
created

getRawHtml()   B

Complexity

Conditions 7
Paths 28

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 28
ccs 0
cts 13
cp 0
rs 8.8333
c 2
b 0
f 0
cc 7
nc 28
nop 2
crap 56
1
<?php
2
3
use Colors\Color;
4
use Blacklight\XXX;
5
use GuzzleHttp\Client;
6
use Tuna\CloudflareMiddleware;
7
use GuzzleHttp\Cookie\CookieJar;
8
use GuzzleHttp\Cookie\SetCookie;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Facades\Log;
11
use GuzzleHttp\Cookie\FileCookieJar;
12
use Symfony\Component\Process\Process;
13
use GuzzleHttp\Exception\RequestException;
14
15
if (! function_exists('getRawHtml')) {
16
17
    /**
18
     * @param             $url
19
     * @param bool|string $cookie
20
     *
21
     * @return bool|string
22
     * @throws \InvalidArgumentException
23
     * @throws \RuntimeException
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
            $cookieJar = $cookiejar->setCookie(SetCookie::fromString($cookie));
0 ignored issues
show
Bug introduced by
It seems like $cookie can also be of type true; however, parameter $cookie of GuzzleHttp\Cookie\SetCookie::fromString() does only seem to accept string, 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

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

260
            return round(/** @scrutinizer ignore-type */ sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
Loading history...
261
        }
262
    }
263
264
    if (! function_exists('bcdechex')) {
265
266
        /**
267
         * @param $dec
268
         *
269
         * @return string
270
         */
271
        function bcdechex($dec)
272
        {
273
            $hex = '';
274
            do {
275
                $last = bcmod($dec, 16);
276
                $hex = dechex($last).$hex;
0 ignored issues
show
Bug introduced by
$last of type string is incompatible with the type integer expected by parameter $number 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

276
                $hex = dechex(/** @scrutinizer ignore-type */ $last).$hex;
Loading history...
277
                $dec = bcdiv(bcsub($dec, $last), 16);
278
            } while ($dec > 0);
279
280
            return $hex;
281
        }
282
    }
283
284
    if (! function_exists('runCmd')) {
285
        /**
286
         * Run CLI command.
287
         *
288
         *
289
         * @param string $command
290
         * @param bool $debug
291
         *
292
         * @return string
293
         */
294
        function runCmd($command, $debug = false)
295
        {
296
            if ($debug) {
297
                echo '-Running Command: '.PHP_EOL.'   '.$command.PHP_EOL;
298
            }
299
300
            $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

300
            $process = new Process(/** @scrutinizer ignore-type */ $command);
Loading history...
301
            $process->run();
302
            $output = $process->getOutput();
303
304
            if ($debug) {
305
                echo '-Command Output: '.PHP_EOL.'   '.$output.PHP_EOL;
306
            }
307
308
            return $output;
309
        }
310
    }
311
312
    if (! function_exists('escapeString')) {
313
314
        /**
315
         * @param $string
316
         *
317
         * @return string
318
         */
319
        function escapeString($string)
320
        {
321
            return DB::connection()->getPdo()->quote($string);
322
        }
323
    }
324
325
    if (! function_exists('realDuration')) {
326
327
        /**
328
         * @param $milliseconds
329
         *
330
         * @return string
331
         */
332
        function realDuration($milliseconds)
333
        {
334
            $time = round($milliseconds / 1000);
335
336
            return sprintf('%02dh:%02dm:%02ds', $time / 3600, $time / 60 % 60, $time % 60);
337
        }
338
    }
339
}
340