Completed
Push — dev ( 0da3af...2e8e1c )
by Darko
07:30
created

is_it_json()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
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 $cookie
20
     *
21
     * @return bool|mixed|string
22
     */
23
    function getRawHtml($url, $cookie = false)
24
    {
25
        $cookiejar = new CookieJar();
26
        $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']]);
27
        if ($cookie !== false) {
28
            $cookieJar = $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

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

257
            return round(/** @scrutinizer ignore-type */ sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
Loading history...
258
        }
259
    }
260
261
    if (! function_exists('bcdechex')) {
262
263
        /**
264
         * @param $dec
265
         *
266
         * @return string
267
         */
268
        function bcdechex($dec)
269
        {
270
            $hex = '';
271
            do {
272
                $last = bcmod($dec, 16);
273
                $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

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

297
            $process = new Process(/** @scrutinizer ignore-type */ $command);
Loading history...
298
            $process->run();
299
            $output = $process->getOutput();
300
301
            if ($debug) {
302
                echo '-Command Output: '.PHP_EOL.'   '.$output.PHP_EOL;
303
            }
304
305
            return $output;
306
        }
307
    }
308
309
    if (! function_exists('escapeString')) {
310
311
        /**
312
         * @param $string
313
         *
314
         * @return string
315
         */
316
        function escapeString($string)
317
        {
318
            return DB::connection()->getPdo()->quote($string);
319
        }
320
    }
321
322
    if (! function_exists('realDuration')) {
323
324
        /**
325
         * @param $milliseconds
326
         *
327
         * @return string
328
         */
329
        function realDuration($milliseconds)
330
        {
331
            $time = round($milliseconds / 1000);
332
333
            return sprintf('%02dh:%02dm:%02ds', $time / 3600, $time / 60 % 60, $time % 60);
334
        }
335
    }
336
337
    if (! function_exists('is_it_json')) {
338
339
        /**
340
         * @param array|string $isIt
341
         * @return bool
342
         */
343
        function is_it_json($isIt)
344
        {
345
            if (is_array($isIt)) {
346
                return false;
347
            }
348
            json_decode($isIt);
349
350
            return (json_last_error() === JSON_ERROR_NONE);
351
        }
352
    }
353
}
354