Completed
Push — dev ( 948658...85fd2a )
by Darko
07:23
created

Utility::setCoversConstant()   B

Complexity

Conditions 10
Paths 5

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
cc 10
eloc 11
nc 5
nop 1
dl 0
loc 13
ccs 0
cts 8
cp 0
crap 110
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Blacklight\utility;
4
5
use App\Models\Settings;
6
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\File;
9
use Illuminate\Support\Str;
10
11
/**
12
 * Class Utility.
13
 */
14
class Utility
15
{
16
    /**
17
     *  Regex for detecting multi-platform path. Use it where needed so it can be updated in one location as required characters get added.
18
     */
19
    public const PATH_REGEX = '(?P<drive>[A-Za-z]:|)(?P<path>[/\w.-]+|)';
20
21
    public const VERSION_REGEX = '#(?P<all>v(?P<digits>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<revision>\d+)(?:\.(?P<fix>\d+))?)(?:-(?P<suffix>(?:RC\d+|dev)))?)#';
22
23
    /**
24
     * Checks all levels of the supplied path are readable and executable by current user.
25
     *
26
     * @todo Make this recursive with a switch to only check end point.
27
     * @param $path	*nix path to directory or file
28
     *
29
     * @return bool|string True is successful, otherwise the part of the path that failed testing.
30
     */
31
    public static function canExecuteRead($path)
32
    {
33
        $paths = explode('#/#', $path);
34
        $fullPath = DS;
0 ignored issues
show
Bug introduced by
The constant Blacklight\utility\DS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
35
        foreach ($paths as $singlePath) {
36
            if ($singlePath !== '') {
37
                $fullPath .= $singlePath.DS;
38
                if (! is_readable($fullPath) || ! is_executable($fullPath)) {
39
                    return "The '$fullPath' directory must be readable and executable by all .".PHP_EOL;
40
                }
41
            }
42
        }
43
44
        return true;
45
    }
46
47
    public static function clearScreen(): void
48
    {
49
        if (self::isCLI()) {
50
            passthru('clear');
51
        }
52
    }
53
54
    /**
55
     * Removes the preceeding or proceeding portion of a string
56
     * relative to the last occurrence of the specified character.
57
     * The character selected may be retained or discarded.
58
     *
59
     * @param string $character      the character to search for.
60
     * @param string $string         the string to search through.
61
     * @param string $side           determines whether text to the left or the right of the character is returned.
62
     *                               Options are: left, or right.
63
     * @param bool   $keep_character determines whether or not to keep the character.
64
     *                               Options are: true, or false.
65
     *
66
     * @return string
67
     */
68
    public static function cutStringUsingLast($character, $string, $side, $keep_character = true): string
69
    {
70
        $offset = ($keep_character ? 1 : 0);
71
        $whole_length = \strlen($string);
72
        $right_length = (\strlen(strrchr($string, $character)) - 1);
73
        $left_length = ($whole_length - $right_length - 1);
74
        switch ($side) {
75
            case 'left':
76
                $piece = substr($string, 0, $left_length + $offset);
77
                break;
78
            case 'right':
79
                $start = (0 - ($right_length + $offset));
80
                $piece = substr($string, $start);
81
                break;
82
            default:
83
                $piece = false;
84
                break;
85
        }
86
87
        return $piece;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $piece could return the type false which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
88
    }
89
90
    /**
91
     * @param array|null $options
92
     *
93
     * @return array|null
94
     */
95
    public static function getDirFiles(array $options = null): ?array
96
    {
97
        $defaults = [
98
            'dir'   => false,
99
            'ext'   => '', // no full stop (period) separator should be used.
100
            'file'    => true,
101
            'path'  => '',
102
            'regex' => '',
103
        ];
104
        $options += $defaults;
105
        if (! $options['dir'] && ! $options['file']) {
106
            return null;
107
        }
108
109
        // Replace windows style path separators with unix style.
110
        $iterator = new \FilesystemIterator(
111
            str_replace('\\', '/', $options['path']),
112
            \FilesystemIterator::KEY_AS_PATHNAME |
113
            \FilesystemIterator::SKIP_DOTS |
114
            \FilesystemIterator::UNIX_PATHS
115
        );
116
117
        $files = [];
118
        foreach ($iterator as $fileInfo) {
119
            $file = $iterator->key();
120
            switch (true) {
121
                case ! $options['dir'] && $fileInfo->isDir():
122
                    break;
123
                case ! empty($options['ext']) && $fileInfo->getExtension() !== $options['ext']:
124
                    break;
125
                case empty($options['regex']) || ! preg_match($options['regex'], $file):
126
                    break;
127
                case ! $options['file'] && $fileInfo->isFile():
128
                    break;
129
                default:
130
                    $files[] = $file;
131
            }
132
        }
133
134
        return $files;
135
    }
136
137
    /**
138
     * @return array
139
     */
140
    public static function getThemesList(): array
141
    {
142
        $ignoredThemes = ['admin', 'shared'];
143
        $themes = scandir(base_path().'/resources/views/themes', SCANDIR_SORT_ASCENDING);
0 ignored issues
show
Bug introduced by
Are you sure the usage of base_path() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
144
        $themeList[] = 'None';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$themeList was never initialized. Although not strictly required by PHP, it is generally a good practice to add $themeList = array(); before regardless.
Loading history...
145
        foreach ($themes as $theme) {
146
            if (strpos($theme, '.') === false && ! \in_array($theme, $ignoredThemes, false) && File::isDirectory(base_path().'/resources/views/themes/'.$theme)) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of base_path() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
147
                $themeList[] = $theme;
148
            }
149
        }
150
151
        sort($themeList);
152
153
        return $themeList;
154
    }
155
156
    /**
157
     * Detect if the command is accessible on the system.
158
     *
159
     *
160
     * @param $cmd
161
     *
162
     * @return bool
163
     */
164
    public static function hasCommand($cmd): bool
165
    {
166
        $returnVal = shell_exec("which $cmd");
167
168
        return $returnVal !== null;
169
    }
170
171
    /**
172
     * Check if user is running from CLI.
173
     *
174
     * @return bool
175
     */
176
    public static function isCLI(): bool
177
    {
178
        return strtolower(PHP_SAPI) === 'cli';
179
    }
180
181
    /**
182
     * @param $filename
183
     *
184
     * @return bool|null|string
185
     */
186
    public static function isGZipped($filename)
187
    {
188
        $gzipped = null;
189
        if (($fp = fopen($filename, 'rb')) !== false) {
190
            if (@fread($fp, 2) === "\x1F\x8B") { // this is a gzip'd file
191
                fseek($fp, -4, SEEK_END);
192
                if (\strlen($datum = @fread($fp, 4)) === 4) {
193
                    $gzipped = $datum;
194
                }
195
            }
196
            fclose($fp);
197
        }
198
199
        return $gzipped;
200
    }
201
202
    /**
203
     * Strips non-printing characters from a string.
204
     *
205
     * Operates directly on the text string, but also returns the result for situations requiring a
206
     * return value (use in ternary, etc.)/
207
     *
208
     * @param string $text String variable to strip.
209
     *
210
     * @return string    The stripped variable.
211
     */
212
    public static function stripNonPrintingChars(&$text): string
213
    {
214
        $text = str_replace('/[[:^print:]]/', '', $text);
215
216
        return $text;
217
    }
218
219
    /**
220
     * Unzip a gzip file, return the output. Return false on error / empty.
221
     *
222
     * @param string $filePath
223
     *
224
     * @return bool|string
225
     */
226
    public static function unzipGzipFile($filePath)
227
    {
228
        $string = '';
229
        $gzFile = @gzopen($filePath, 'rb', 0);
230
        if ($gzFile) {
0 ignored issues
show
introduced by
$gzFile is of type resource, thus it always evaluated to false.
Loading history...
231
            while (! gzeof($gzFile)) {
232
                $temp = gzread($gzFile, 1024);
233
                // Check for empty string.
234
                // Without this the loop would be endless and consume 100% CPU.
235
                // Do not set $string empty here, as the data might still be good.
236
                if (! $temp) {
237
                    break;
238
                }
239
                $string .= $temp;
240
            }
241
            gzclose($gzFile);
242
        }
243
244
        return $string === '' ? false : $string;
0 ignored issues
show
introduced by
The condition $string === '' is always true.
Loading history...
245
    }
246
247
    /**
248
     * Creates an array to be used with stream_context_create() to verify openssl certificates
249
     * when connecting to a tls or ssl connection when using stream functions (fopen/file_get_contents/etc).
250
     *
251
     * @param bool $forceIgnore Force ignoring of verification.
252
     *
253
     * @return array
254
     * @static
255
     */
256
    public static function streamSslContextOptions($forceIgnore = false): array
257
    {
258
        if (config('nntmux_ssl.ssl_cafile') === '' && config('nntmux_ssl.ssl_capath') === '') {
259
            $options = [
260
                'verify_peer'       => false,
261
                'verify_peer_name'  => false,
262
                'allow_self_signed' => true,
263
            ];
264
        } else {
265
            $options = [
266
                'verify_peer'       => $forceIgnore ? false : config('nntmux_ssl.ssl_verify_peer'),
267
                'verify_peer_name'  => $forceIgnore ? false : config('nntmux_ssl.ssl_verify_host'),
268
                'allow_self_signed' => $forceIgnore ? true : config('nntmux_ssl.ssl_allow_self_signed'),
269
            ];
270
            if (config('nntmux_ssl.ssl_cafile') !== '') {
271
                $options['cafile'] = config('nntmux_ssl.ssl_cafile');
272
            }
273
            if (config('nntmux_ssl.ssl_capath') !== '') {
274
                $options['capath'] = config('nntmux_ssl.ssl_capath');
275
            }
276
        }
277
        // If we set the transport to tls and the server falls back to ssl,
278
        // the context options would be for tls and would not apply to ssl,
279
        // so set both tls and ssl context in case the server does not support tls.
280
        return ['tls' => $options, 'ssl' => $options];
281
    }
282
283
    /**
284
     * Set curl context options for verifying SSL certificates.
285
     *
286
     * @param bool $verify false = Ignore config.php and do not verify the openssl cert.
287
     *                     true  = Check config.php and verify based on those settings.
288
     *                     If you know the certificate will be self-signed, pass false.
289
     *
290
     * @return array
291
     * @static
292
     */
293
    public static function curlSslContextOptions($verify = true): array
294
    {
295
        $options = [];
296
        if ($verify && config('nntmux_ssl.ssl_verify_host') && (! empty(config('nntmux_ssl.ssl_cafile')) || ! empty(config('nntmux_ssl.ssl_capath')))) {
297
            $options += [
298
                CURLOPT_SSL_VERIFYPEER => (bool) config('nntmux_ssl.ssl_verify_peer'),
299
                CURLOPT_SSL_VERIFYHOST => config('nntmux_ssl.ssl_verify_host') ? 2 : 0,
300
            ];
301
            if (! empty(config('nntmux_ssl.ssl_cafile'))) {
302
                $options += [CURLOPT_CAINFO => config('nntmux_ssl.ssl_cafile')];
303
            }
304
            if (! empty(config('nntmux_ssl.ssl_capath'))) {
305
                $options += [CURLOPT_CAPATH => config('nntmux_ssl.ssl_capath')];
306
            }
307
        } else {
308
            $options += [
309
                CURLOPT_SSL_VERIFYPEER => false,
310
                CURLOPT_SSL_VERIFYHOST => 0,
311
            ];
312
        }
313
314
        return $options;
315
    }
316
317
    /**
318
     * @param array $options
319
     *
320
     * @return string
321
     */
322
    public static function getCoverURL(array $options = []): string
323
    {
324
        $defaults = [
325
            'id'     => null,
326
            'suffix' => '-cover.jpg',
327
            'type'   => '',
328
        ];
329
        $options += $defaults;
330
        $fileSpecTemplate = '%s/%s%s';
331
        $fileSpec = '';
332
333
        if (! empty($options['id']) && \in_array(
334
            $options['type'],
335
            ['anime', 'audio', 'audiosample', 'book', 'console', 'games', 'movies', 'music', 'preview', 'sample', 'tvrage', 'video', 'xxx'],
336
            false
337
            )
338
        ) {
339
            $fileSpec = sprintf($fileSpecTemplate, $options['type'], $options['id'], $options['suffix']);
340
            $fileSpec = file_exists(resource_path().'/covers/'.$fileSpec) ? $fileSpec :
341
                sprintf($fileSpecTemplate, $options['type'], 'no', $options['suffix']);
342
        }
343
344
        return $fileSpec;
345
    }
346
347
    /**
348
     * Converts XML to an associative array with namespace preservation -- use if intending to JSON encode.
349
     * @author Tamlyn from Outlandish.com
350
     *
351
     * @param \SimpleXMLElement $xml The SimpleXML parsed XML string data
352
     * @param array             $options
353
     *
354
     * @return array            The associate array of the XML namespaced file
355
     */
356
    public static function xmlToArray(\SimpleXMLElement $xml, array $options = []): array
357
    {
358
        $defaults = [
359
            'namespaceSeparator' => ':', //you may want this to be something other than a colon
360
            'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
361
            'alwaysArray' => [],   //array of xml tag names which should always become arrays
362
            'autoArray' => true,        //only create arrays for tags which appear more than once
363
            'textContent' => '$',       //key used for the text content of elements
364
            'autoText' => true,         //skip textContent key if node has no attributes or child nodes
365
            'keySearch' => false,       //optional search and replace on tag and attribute names
366
            'keyReplace' => false,       //replace values for above search values (as passed to str_replace())
367
        ];
368
        $options = array_merge($defaults, $options);
369
        $namespaces = $xml->getDocNamespaces();
370
        $namespaces[''] = null; //add base (empty) namespace
371
372
        $attributesArray = $tagsArray = [];
373
        foreach ($namespaces as $prefix => $namespace) {
374
            //get attributes from all namespaces
375
            foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
376
                //replace characters in attribute name
377
                if ($options['keySearch']) {
378
                    $attributeName =
379
                    str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
380
                }
381
                $attributeKey = $options['attributePrefix']
382
                    .($prefix ? $prefix.$options['namespaceSeparator'] : '')
383
                    .$attributeName;
384
                $attributesArray[$attributeKey] = (string) $attribute;
385
            }
386
            //get child nodes from all namespaces
387
            foreach ($xml->children($namespace) as $childXml) {
388
                //recurse into child nodes
389
                $childArray = self::xmlToArray($childXml, $options);
390
                $childTagName = key($childArray);
391
                $childProperties = current($childArray);
392
393
                //replace characters in tag name
394
                if ($options['keySearch']) {
395
                    $childTagName =
396
                    str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
397
                }
398
                //add namespace prefix, if any
399
                if ($prefix) {
400
                    $childTagName = $prefix.$options['namespaceSeparator'].$childTagName;
401
                }
402
403
                if (! isset($tagsArray[$childTagName])) {
404
                    //only entry with this key
405
                    //test if tags of this type should always be arrays, no matter the element count
406
                    $tagsArray[$childTagName] =
407
                        \in_array($childTagName, $options['alwaysArray'], false) || ! $options['autoArray']
408
                            ? [$childProperties] : $childProperties;
409
                } elseif (
410
                    \is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
411
                    === range(0, \count($tagsArray[$childTagName]) - 1)
412
                ) {
413
                    //key already exists and is integer indexed array
414
                    $tagsArray[$childTagName][] = $childProperties;
415
                } else {
416
                    //key exists so convert to integer indexed array with previous value in position 0
417
                    $tagsArray[$childTagName] = [$tagsArray[$childTagName], $childProperties];
418
                }
419
            }
420
        }
421
422
        //get text content of node
423
        $textContentArray = [];
424
        $plainText = trim((string) $xml);
425
        if ($plainText !== '') {
426
            $textContentArray[$options['textContent']] = $plainText;
427
        }
428
429
        //stick it all together
430
        $propertiesArray = ! $options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
431
            ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
432
433
        //return node as array
434
        return [
435
            $xml->getName() => $propertiesArray,
436
        ];
437
    }
438
439
    /**
440
     * Return file type/info using magic numbers.
441
     * Try using `file` program where available, fallback to using PHP's finfo class.
442
     *
443
     * @param string $path Path to the file / folder to check.
444
     *
445
     * @return string File info. Empty string on failure.
446
     * @throws \Exception
447
     */
448
    public static function fileInfo($path): string
449
    {
450
        $magicPath = Settings::settingValue('apps.indexer.magic_file_path');
451
        if ($magicPath !== null && self::hasCommand('file')) {
452
            $magicSwitch = " -m $magicPath";
453
            $output = runCmd('file'.$magicSwitch.' -b "'.$path.'"');
454
        } else {
455
            $fileInfo = $magicPath === null ? finfo_open(FILEINFO_RAW) : finfo_open(FILEINFO_RAW, $magicPath);
456
457
            $output = finfo_file($fileInfo, $path);
458
            if (empty($output)) {
459
                $output = '';
460
            }
461
            finfo_close($fileInfo);
462
        }
463
464
        return $output;
465
    }
466
467
    /**
468
     * @param $code
469
     *
470
     * @return bool
471
     */
472
    public function checkStatus($code): bool
473
    {
474
        return $code === 0;
475
    }
476
477
    /**
478
     * Convert Code page 437 chars to UTF.
479
     *
480
     * @param string $string
481
     *
482
     * @return string
483
     */
484
    public static function cp437toUTF($string): string
485
    {
486
        return iconv('CP437', 'UTF-8//IGNORE//TRANSLIT', $string);
487
    }
488
489
    /**
490
     * Fetches an embeddable video to a IMDB trailer from http://www.traileraddict.com.
491
     *
492
     * @param $imdbID
493
     *
494
     * @return string
495
     */
496
    public static function imdb_trailers($imdbID): string
497
    {
498
        $xml = getRawHtml('https://api.traileraddict.com/?imdb='.$imdbID);
499
        if ($xml !== false && preg_match('#(v\.traileraddict\.com/\d+)#i', $xml, $html)) {
0 ignored issues
show
Bug introduced by
It seems like $xml can also be of type true; however, parameter $subject of preg_match() 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

499
        if ($xml !== false && preg_match('#(v\.traileraddict\.com/\d+)#i', /** @scrutinizer ignore-type */ $xml, $html)) {
Loading history...
500
            return 'https://'.$html[1];
501
        }
502
503
        return '';
504
    }
505
506
    /**
507
     * Convert obj to array.
508
     *
509
     * @param       $arrObjData
510
     * @param array $arrSkipIndices
511
     *
512
     * @return array
513
     */
514
    public static function objectsIntoArray($arrObjData, array $arrSkipIndices = []): array
515
    {
516
        $arrData = [];
517
518
        // If input is object, convert into array.
519
        if (\is_object($arrObjData)) {
520
            $arrObjData = get_object_vars($arrObjData);
521
        }
522
523
        if (\is_array($arrObjData)) {
524
            foreach ($arrObjData as $index => $value) {
525
                // Recursive call.
526
                if (\is_object($value) || \is_array($value)) {
527
                    $value = self::objectsIntoArray($value, $arrSkipIndices);
528
                }
529
                if (\in_array($index, $arrSkipIndices, false)) {
530
                    continue;
531
                }
532
                $arrData[$index] = $value;
533
            }
534
        }
535
536
        return $arrData;
537
    }
538
539
    /**
540
     * Remove unsafe chars from a filename.
541
     *
542
     * @param string $filename
543
     *
544
     * @return string
545
     */
546
    public static function safeFilename($filename): string
547
    {
548
        return trim(preg_replace('/[^\w\s.-]*/i', '', $filename));
549
    }
550
551
    /**
552
     * @param $input
553
     *
554
     * @return \SimpleXMLElement
555
     */
556
    public static function responseXmlToObject($input): \SimpleXMLElement
557
    {
558
        $input = str_replace('<newznab:', '<', $input);
559
560
        return @simplexml_load_string($input);
0 ignored issues
show
Bug Best Practice introduced by
The expression return @simplexml_load_string($input) could return the type false which is incompatible with the type-hinted return SimpleXMLElement. Consider adding an additional type-check to rule them out.
Loading history...
561
    }
562
563
    /**
564
     * Display error/error code.
565
     * @param int    $errorCode
566
     * @param string $errorText
567
     */
568
    public static function showApiError($errorCode = 900, $errorText = ''): void
569
    {
570
        $errorHeader = 'HTTP 1.1 400 Bad Request';
571
        if ($errorText === '') {
572
            switch ($errorCode) {
573
                case 100:
574
                    $errorText = 'Incorrect user credentials';
575
                    $errorHeader = 'HTTP 1.1 401 Unauthorized';
576
                    break;
577
                case 101:
578
                    $errorText = 'Account suspended';
579
                    $errorHeader = 'HTTP 1.1 403 Forbidden';
580
                    break;
581
                case 102:
582
                    $errorText = 'Insufficient privileges/not authorized';
583
                    $errorHeader = 'HTTP 1.1 401 Unauthorized';
584
                    break;
585
                case 103:
586
                    $errorText = 'Registration denied';
587
                    $errorHeader = 'HTTP 1.1 403 Forbidden';
588
                    break;
589
                case 104:
590
                    $errorText = 'Registrations are closed';
591
                    $errorHeader = 'HTTP 1.1 403 Forbidden';
592
                    break;
593
                case 105:
594
                    $errorText = 'Invalid registration (Email Address Taken)';
595
                    $errorHeader = 'HTTP 1.1 403 Forbidden';
596
                    break;
597
                case 106:
598
                    $errorText = 'Invalid registration (Email Address Bad Format)';
599
                    $errorHeader = 'HTTP 1.1 403 Forbidden';
600
                    break;
601
                case 107:
602
                    $errorText = 'Registration Failed (Data error)';
603
                    $errorHeader = 'HTTP 1.1 400 Bad Request';
604
                    break;
605
                case 200:
606
                    $errorText = 'Missing parameter';
607
                    $errorHeader = 'HTTP 1.1 400 Bad Request';
608
                    break;
609
                case 201:
610
                    $errorText = 'Incorrect parameter';
611
                    $errorHeader = 'HTTP 1.1 400 Bad Request';
612
                    break;
613
                case 202:
614
                    $errorText = 'No such function';
615
                    $errorHeader = 'HTTP 1.1 404 Not Found';
616
                    break;
617
                case 203:
618
                    $errorText = 'Function not available';
619
                    $errorHeader = 'HTTP 1.1 400 Bad Request';
620
                    break;
621
                case 300:
622
                    $errorText = 'No such item';
623
                    $errorHeader = 'HTTP 1.1 404 Not Found';
624
                    break;
625
                case 500:
626
                    $errorText = 'Request limit reached';
627
                    $errorHeader = 'HTTP 1.1 429 Too Many Requests';
628
                    break;
629
                case 501:
630
                    $errorText = 'Download limit reached';
631
                    $errorHeader = 'HTTP 1.1 429 Too Many Requests';
632
                    break;
633
                case 910:
634
                    $errorText = 'API disabled';
635
                    $errorHeader = 'HTTP 1.1 401 Unauthorized';
636
                    break;
637
                default:
638
                    $errorText = 'Unknown error';
639
                    $errorHeader = 'HTTP 1.1 400 Bad Request';
640
                    break;
641
            }
642
        }
643
644
        $response =
645
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".
646
            '<error code="'.$errorCode.'" description="'.$errorText."\"/>\n";
647
        header('Content-type: text/xml');
648
        header('Content-Length: '.\strlen($response));
649
        header('X-NNTmux: API ERROR ['.$errorCode.'] '.$errorText);
650
        header($errorHeader);
651
652
        exit($response);
653
    }
654
655
    /**
656
     * Simple function to reduce duplication in html string formatting.
657
     *
658
     * @param $string
659
     *
660
     * @return string
661
     */
662
    public static function htmlfmt($string): string
663
    {
664
        return htmlspecialchars($string, ENT_QUOTES, 'utf-8');
665
    }
666
667
    /**
668
     * @param $tableName
669
     *
670
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
671
     */
672
    public static function getRange($tableName): LengthAwarePaginator
673
    {
674
        $range = DB::table($tableName);
675
        if ($tableName === 'xxxinfo') {
676
            $range->selectRaw('UNCOMPRESS(plot) AS plot');
677
        }
678
679
        return $range->orderByDesc('created_at')->paginate(config('nntmux.items_per_page'));
680
    }
681
682
    /**
683
     * @param $tableName
684
     *
685
     * @return int
686
     */
687
    public static function getCount($tableName): int
688
    {
689
        $res = DB::table($tableName)->count('id');
690
691
        return $res === false ? 0 : $res;
0 ignored issues
show
introduced by
The condition $res === false is always false.
Loading history...
692
    }
693
}
694