Passed
Push — master ( d63a45...8016ac )
by Iman
09:10
created

FileController::getPreview()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 16
nop 5
dl 0
loc 35
rs 8.7377
c 0
b 0
f 0
1
<?php
2
3
namespace Crocodicstudio\Crudbooster\Controllers;
4
5
use Crocodicstudio\Crudbooster\CBCoreModule\FileUploader;
6
use Crocodicstudio\Crudbooster\Controllers\Helpers\IndexImport;
7
use Crocodicstudio\Crudbooster\Modules\ModuleGenerator\ControllerGenerator\FieldDetector;
8
use Storage;
9
use Response;
10
use Image;
11
use File;
12
use Illuminate\Support\Facades\Request;
13
14
class FileController extends Controller
15
{
16
    public function uploadSummernote()
17
    {
18
        echo asset(app( FileUploader::class)->uploadFile('userfile'));
19
    }
20
21
    public function uploadFile()
22
    {
23
        echo app(FileUploader::class)->uploadFile('userfile');
24
    }
25
26
    public function doUploadImportData()
27
    {
28
        $import = app(IndexImport::class);
29
        //$this->cbLoader();
30
        if (! Request::hasFile('userfile')) {
31
            return redirect()->back();
32
        }
33
        $file = Request::file('userfile');
34
        $validator = $import->validateForImport($file);
35
        if ($validator->fails()) {
36
            backWithMsg(implode('<br/>', $validator->errors()->all()), 'warning');
37
        }
38
        $url = $import->uploadImportData($file);
39
40
        return redirect($url);
41
    }
42
43
    public function getPreview($one, $two = null, $three = null, $four = null, $five = null)
44
    {
45
        // array_filter() filters out the falsy values from array.
46
        $params = array_filter([$one, $two, $three, $four, $five]);        
47
        $filename = array_pop($params);
48
        $fullFilePath = implode(DIRECTORY_SEPARATOR, array_filter(['uploads', $one, $two, $three, $four, $five]));
49
50
        $fullStoragePath = storage_path('app/'.$fullFilePath);
51
52
53
        if (! Storage::exists($fullFilePath)) {
54
            abort(404);
55
        }
56
        $hasImageExtension = $this->isImage($fullStoragePath);
57
        $imageFileSize = 0;
58
        $imgRaw = '';
59
        if ($hasImageExtension) {
60
            list($imgRaw, $imageFileSize) = $this->resizeImage($fullStoragePath);
61
        }
62
63
        list($headers, $isCachedByBrowser) = $this->prepareHeaders($imageFileSize, $fullFilePath, $filename);
64
65
        if ($hasImageExtension) {
66
            if ($isCachedByBrowser) {
67
                return Response::make('', 304, $headers); // File (image) is cached by the browser, so we don't have to send it again
68
            }
69
70
            return Response::make($imgRaw, 200, $headers);
71
        }
72
73
        if (request('download')) {
74
            return Response::download($fullStoragePath, $filename, $headers);
0 ignored issues
show
Bug introduced by
The call to Illuminate\Support\Facades\Response::download() has too few arguments starting with |. ( Ignorable by Annotation )

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

74
            return Response::/** @scrutinizer ignore-call */ download($fullStoragePath, $filename, $headers);

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
Bug introduced by
$fullStoragePath of type string is incompatible with the type SplFileInfo expected by parameter $| of Illuminate\Support\Facades\Response::download(). ( Ignorable by Annotation )

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

74
            return Response::download(/** @scrutinizer ignore-type */ $fullStoragePath, $filename, $headers);
Loading history...
75
        }
76
77
        return Response::file($fullStoragePath, $headers);
78
    }
79
80
    /**
81
     * @param $fullStoragePath
82
     * @return array
83
     */
84
    private function resizeImage($fullStoragePath)
85
    {
86
        $w = request('w', cbConfig('DEFAULT_THUMBNAIL_WIDTH', 300));
87
        $h = request('h', $w);
88
        $imgRaw = Image::cache(function ($image) use ($fullStoragePath, $w, $h) {
89
            $im = $image->make($fullStoragePath);
90
            if (! $w) {
91
                return $im;
92
            }
93
            if (! $h) {
94
                $im->fit($w);
95
            } else {
96
                $im->fit($w, $h);
97
            }
98
        });
99
100
        $imageFileSize = mb_strlen($imgRaw, '8bit') ?: 0;
101
102
        return [$imgRaw, $imageFileSize];
103
    }
104
105
    /**
106
     * @param $fullStoragePath
107
     * @return bool
108
     */
109
    private function isImage($fullStoragePath)
110
    {
111
        $extension = strtolower(File::extension($fullStoragePath));
112
113
        return FieldDetector::isWithin($extension, 'IMAGE_EXTENSIONS');;
114
    }
115
116
    /**
117
     * @param $imageFileSize
118
     * @param $fullFilePath
119
     * @param $filename
120
     * @return array
121
     */
122
    private function prepareHeaders($imageFileSize, $fullFilePath, $filename)
123
    {
124
        $lifetime = 31556926; // One year in seconds
125
        $fullStoragePath = storage_path('app/'.$fullFilePath);
126
        /**
127
         * Prepare some header variables
128
         */
129
        $handler = new \Symfony\Component\HttpFoundation\File\File($fullStoragePath);
130
        $file_time = $handler->getMTime(); // Get the last modified time for the file (Unix timestamp)
131
132
        $header_content_type = $handler->getMimeType();
133
        $header_content_length = ($imageFileSize) ?: $handler->getSize();
134
        $header_etag = md5($file_time.$fullFilePath);
135
        $header_last_modified = gmdate('r', $file_time);
136
        $header_expires = gmdate('r', $file_time + $lifetime);
137
138
        $headers = [
139
            'Content-Disposition' => 'inline; filename="'.$filename.'"',
140
            'Last-Modified' => $header_last_modified,
141
            'Cache-Control' => 'must-revalidate',
142
            'Expires' => $header_expires,
143
            'Pragma' => 'public',
144
            'Etag' => $header_etag,
145
        ];
146
147
        // return Response::download($fullStoragePath, $filename, $headers);
148
149
        $headers = array_merge($headers, [
150
            'Content-Type' => $header_content_type,
151
            'Content-Length' => $header_content_length,
152
        ]);
153
154
        /**
155
         * Is the resource cached?
156
         */
157
        $h1 = Request::server('HTTP_IF_MODIFIED_SINCE') && Request::server('HTTP_IF_MODIFIED_SINCE') == $header_last_modified;
158
        $h2 = Request::server('HTTP_IF_NONE_MATCH') && str_replace('"', '', stripslashes(Request::server('HTTP_IF_NONE_MATCH'))) == $header_etag;
159
        $isCachedByBrowser = ($h1 || $h2);
160
161
        return [$headers, $isCachedByBrowser];
162
    }
163
164
    /**
165
     * @return mixed
166
     */
167
    public function doneImport()
168
    {
169
        return app(IndexImport::class)->doneImport();
170
    }
171
}
172