Passed
Push — master ( a1524f...4d2cc5 )
by Darko
07:18
created

AdminNzbController::getUploadErrorMessage()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 20
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 18
c 1
b 1
f 0
dl 0
loc 20
rs 8.4444
cc 8
nc 8
nop 3
1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use App\Http\Controllers\BasePageController;
6
use Blacklight\NZBExport;
7
use Blacklight\NZBImport;
8
use Blacklight\Releases;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Str;
11
12
class AdminNzbController extends BasePageController
13
{
14
    /**
15
     * @throws \Exception
16
     */
17
    public function import(Request $request): void
18
    {
19
        $this->setAdminPrefs();
20
21
        $filesToProcess = [];
22
        $uploadMessages = [];
23
24
        if ($this->isPostBack($request)) {
25
            $useNzbName = false;
26
            $deleteNZB = true;
27
28
            // Get the list of NZB files from php /tmp folder if nzb files were uploaded.
29
            if (isset($_FILES['uploadedfiles']) && ! empty($_FILES['uploadedfiles']['name'][0])) {
30
                $maxFileSize = min(
31
                    $this->convertToBytes(ini_get('upload_max_filesize')),
32
                    $this->convertToBytes(ini_get('post_max_size'))
33
                );
34
35
                foreach ($_FILES['uploadedfiles']['error'] as $key => $error) {
36
                    $fileName = $_FILES['uploadedfiles']['name'][$key];
37
38
                    if ($error === UPLOAD_ERR_OK) {
39
                        $tmp_name = $_FILES['uploadedfiles']['tmp_name'][$key];
40
                        $filesToProcess[] = $tmp_name;
41
                        $uploadMessages[] = "File '{$fileName}' uploaded successfully.";
42
                    } else {
43
                        // Handle specific upload errors
44
                        $errorMessage = $this->getUploadErrorMessage($error, $fileName, $maxFileSize);
45
                        $uploadMessages[] = $errorMessage;
46
                    }
47
                }
48
            } else {
49
                // Check if the user wants to use the file name as the release name.
50
                $useNzbName = ($request->has('usefilename') && $request->input('usefilename') === 'on');
51
52
                // Check if the user wants to delete the NZB file when done importing.
53
                $deleteNZB = ($request->has('deleteNZB') && $request->input('deleteNZB') === 'on');
54
55
                // Get the path the user set in the browser if he put one.
56
                $path = ($request->has('folder') ? $request->input('folder') : '');
57
                if (! Str::endsWith($path, '/')) {
58
                    $path .= '/';
59
                }
60
61
                // Get the files from the user specified path.
62
                $nzbFiles = glob($path.'*.nzb', GLOB_NOSORT);
63
                if (empty($nzbFiles)) {
64
                    $uploadMessages[] = "No NZB files found in the specified path: {$path}";
65
                } else {
66
                    $filesToProcess = $nzbFiles;
67
                    $uploadMessages[] = 'Found '.count($nzbFiles).' NZB file(s) in the specified path.';
68
                }
69
            }
70
71
            $importResults = [];
72
            if (\count($filesToProcess) > 0) {
73
                // Create a new instance of NZBImport and send it the file locations.
74
                $NZBImport = new NZBImport(['Browser' => true, 'Settings' => null]);
75
                $importResults = $NZBImport->beginImport($filesToProcess, $useNzbName, $deleteNZB);
76
            }
77
78
            $output = implode('<br>', array_merge($uploadMessages, is_array($importResults) ? $importResults : [$importResults]));
79
            $this->smarty->assign('output', $output);
80
        }
81
82
        $meta_title = $title = 'Import Nzbs';
83
        $content = $this->smarty->fetch('nzb-import.tpl');
84
        $this->smarty->assign(compact('title', 'meta_title', 'content'));
85
        $this->adminrender();
86
    }
87
88
    /**
89
     * Helper method to convert PHP size strings (like "2M") to bytes
90
     */
91
    private function convertToBytes($sizeStr)
92
    {
93
        $sizeStr = trim($sizeStr);
94
        $unit = strtolower(substr($sizeStr, -1));
95
        $size = (int) $sizeStr;
96
97
        switch ($unit) {
98
            case 'g':
99
                $size *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
100
            case 'm':
101
                $size *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
102
            case 'k':
103
                $size *= 1024;
104
        }
105
106
        return $size;
107
    }
108
109
    /**
110
     * Get human-readable error message for upload errors
111
     */
112
    private function getUploadErrorMessage($errorCode, $fileName, $maxFileSize)
0 ignored issues
show
Unused Code introduced by
The parameter $maxFileSize is not used and could be removed. ( Ignorable by Annotation )

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

112
    private function getUploadErrorMessage($errorCode, $fileName, /** @scrutinizer ignore-unused */ $maxFileSize)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
113
    {
114
        switch ($errorCode) {
115
            case UPLOAD_ERR_INI_SIZE:
116
                return "The file '{$fileName}' exceeds the upload_max_filesize directive (".
117
                       ini_get('upload_max_filesize').').';
118
            case UPLOAD_ERR_FORM_SIZE:
119
                return "The file '{$fileName}' exceeds the MAX_FILE_SIZE directive specified in the HTML form.";
120
            case UPLOAD_ERR_PARTIAL:
121
                return "The file '{$fileName}' was only partially uploaded.";
122
            case UPLOAD_ERR_NO_FILE:
123
                return "No file was uploaded for '{$fileName}'.";
124
            case UPLOAD_ERR_NO_TMP_DIR:
125
                return "Missing temporary folder for file '{$fileName}'.";
126
            case UPLOAD_ERR_CANT_WRITE:
127
                return "Failed to write file '{$fileName}' to disk.";
128
            case UPLOAD_ERR_EXTENSION:
129
                return "File upload stopped by extension for '{$fileName}'.";
130
            default:
131
                return "Unknown upload error for '{$fileName}'.";
132
        }
133
    }
134
135
    /**
136
     * @throws \Exception
137
     */
138
    public function export(Request $request): void
139
    {
140
        $this->setAdminPrefs();
141
        $rel = new Releases;
142
143
        if ($this->isPostBack($request)) {
144
            $path = $request->input('folder');
145
            $postFrom = ($request->input('postfrom') ?? '');
146
            $postTo = ($request->input('postto') ?? '');
147
            $group = ($request->input('group') === '-1' ? 0 : (int) $request->input('group'));
148
            $gzip = ($request->input('gzip') === '1');
149
150
            if ($path !== '') {
151
                $NE = new NZBExport([
0 ignored issues
show
Unused Code introduced by
The call to Blacklight\NZBExport::__construct() has too many arguments starting with array('Browser' => true,...ll, 'Releases' => $rel). ( Ignorable by Annotation )

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

151
                $NE = /** @scrutinizer ignore-call */ new NZBExport([

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
152
                    'Browser' => true, 'Settings' => null,
153
                    'Releases' => $rel,
154
                ]);
155
                $retVal = $NE->beginExport(
156
                    [
157
                        $path,
158
                        $postFrom,
159
                        $postTo,
160
                        $group,
161
                        $gzip,
162
                    ]
163
                );
164
            } else {
165
                $retVal = 'Error, a path is required!';
166
            }
167
168
            $this->smarty->assign(
169
                [
170
                    'folder' => $path,
171
                    'output' => $retVal,
172
                    'fromdate' => $postFrom,
173
                    'todate' => $postTo,
174
                    'group' => $request->input('group'),
175
                    'gzip' => $request->input('gzip'),
176
                ]
177
            );
178
        } else {
179
            $this->smarty->assign(
180
                [
181
                    'fromdate' => $rel->getEarliestUsenetPostDate(),
182
                    'todate' => $rel->getLatestUsenetPostDate(),
183
                ]
184
            );
185
        }
186
187
        $meta_title = $title = 'Export Nzbs';
188
        $this->smarty->assign(
189
            [
190
                'gziplist' => [1 => 'True', 0 => 'False'],
191
                'grouplist' => $rel->getReleasedGroupsForSelect(true),
192
            ]
193
        );
194
        $content = $this->smarty->fetch('nzb-export.tpl');
195
        $this->smarty->assign(compact('title', 'meta_title', 'content'));
196
        $this->adminrender();
197
    }
198
}
199