Completed
Push — dev ( 203fdf...1e2a34 )
by Darko
08:38
created

getRawHtmlThroughCF()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 16
ccs 0
cts 7
cp 0
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
use Colors\Color;
4
use Blacklight\XXX;
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Cookie\CookieJar;
7
use GuzzleHttp\Cookie\FileCookieJar;
8
use GuzzleHttp\Cookie\SetCookie;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Facades\Log;
11
use Symfony\Component\Process\Process;
12
use GuzzleHttp\Exception\RequestException;
13
use Tuna\CloudflareMiddleware;
14
15
if (! function_exists('getRawHtml')) {
16
17
    /**
18
     * @param      $url
19
     * @param bool|string $cookie
20
     *
21
     * @return bool|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
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

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

241
            return round(/** @scrutinizer ignore-type */ sprintf("%.{$decimals}f", $bytes / (1024 ** $factor)), $decimals).@$size[$factor];
Loading history...
242
        }
243
    }
244
245
    if (! function_exists('bcdechex')) {
246
247
        /**
248
         * @param $dec
249
         *
250
         * @return string
251
         */
252
        function bcdechex($dec)
253
        {
254
            $hex = '';
255
            do {
256
                $last = bcmod($dec, 16);
257
                $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

257
                $hex = dechex(/** @scrutinizer ignore-type */ $last).$hex;
Loading history...
258
                $dec = bcdiv(bcsub($dec, $last), 16);
259
            } while ($dec > 0);
260
261
            return $hex;
262
        }
263
    }
264
265
    if (! function_exists('runCmd')) {
266
        /**
267
         * Run CLI command.
268
         *
269
         *
270
         * @param string $command
271
         * @param bool $debug
272
         *
273
         * @return string
274
         */
275
        function runCmd($command, $debug = false)
276
        {
277
            if ($debug) {
278
                echo '-Running Command: '.PHP_EOL.'   '.$command.PHP_EOL;
279
            }
280
281
            $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

281
            $process = new Process(/** @scrutinizer ignore-type */ $command);
Loading history...
282
            $process->run();
283
            $output = $process->getOutput();
284
285
            if ($debug) {
286
                echo '-Command Output: '.PHP_EOL.'   '.$output.PHP_EOL;
287
            }
288
289
            return $output;
290
        }
291
    }
292
293
    if (! function_exists('escapeString')) {
294
295
        /**
296
         * @param $string
297
         *
298
         * @return string
299
         */
300
        function escapeString($string)
301
        {
302
            return DB::connection()->getPdo()->quote($string);
303
        }
304
    }
305
306
    if (! function_exists('realDuration')) {
307
308
        /**
309
         * @param $milliseconds
310
         *
311
         * @return string
312
         */
313
        function realDuration($milliseconds)
314
        {
315
            $time = round($milliseconds / 1000);
316
317
            return sprintf('%02dh:%02dm:%02ds', $time / 3600, $time / 60 % 60, $time % 60);
318
        }
319
    }
320
}
321