FileController   A
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 221
Duplicated Lines 23.98 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 39
lcom 0
cbo 5
dl 53
loc 221
rs 9.28
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
C upload() 45 76 14
A downloadThumbnail() 0 12 2
A download() 0 17 4
A getAvatar() 0 14 4
B delete() 4 33 11
A uploadTmpFile() 4 23 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace Fabrica\Http\Api;
3
4
use Illuminate\Http\Request;
5
use Illuminate\Support\Facades\Event;
6
7
use Fabrica\Http\Api\Controller;
8
use Fabrica\Project\Eloquent\File;
9
use Fabrica\Events\FileUploadEvent;
10
use Fabrica\Events\FileDelEvent;
11
use Fabrica\Utils\File as FileUtil;
12
use DB;
13
14
class FileController extends Controller
15
{
16
    /**
17
     * Upload file.
18
     *
19
     * @param  \Illuminate\Http\Request $request
20
     * @param  String                   $project_key
21
     * @return \Illuminate\Http\Response
22
     */
23
    public function upload(Request $request, $project_key)
24
    {
25
        set_time_limit(0);
26
27
        if (!is_writable(config('filesystems.disks.local.root', '/tmp'))) {
28
            throw new \UnexpectedValueException('the user has not the writable permission to the directory.', -15103);
29
        }
30
31
        $thumbnail_size = 190;
32
33
        $fields = array_keys($_FILES); 
34
        $field = array_pop($fields);
35 View Code Duplication
        if (empty($_FILES) || $_FILES[$field]['error'] > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
36
            throw new \UnexpectedValueException('upload file errors.', -15101);
37
        }
38
39
        $basename = md5(microtime() . $_FILES[$field]['name']);
40
        $sub_save_path = config('filesystems.disks.local.root', '/tmp') . '/' . substr($basename, 0, 2) . '/';
41
        if (!is_dir($sub_save_path)) {
42
            @mkdir($sub_save_path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
43
        }
44
        $filename = '/tmp/' . $basename;
45
        move_uploaded_file($_FILES[$field]['tmp_name'], $filename);
46
        $data = [];
47
        $data['name']    = $_FILES[$field]['name'];
48
        $data['size']    = $_FILES[$field]['size'];
49
        $data['type']    = $_FILES[$field]['type'];
50
        $data['index']   = $basename; 
51 View Code Duplication
        if (in_array($_FILES[$field]['type'], [ 'image/jpeg', 'image/jpg', 'image/png', 'image/gif' ])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
            $size = getimagesize($filename);
53
            $width = $size[0]; $height = $size[1];
54
            $scale = $width < $height ? $height : $width;
55
            $thumbnails_width = floor($thumbnail_size * $width / $scale);
56
            $thumbnails_height = floor($thumbnail_size * $height / $scale);
57
            $thumbnails_filename = $filename . '_thumbnails';
58
            if ($scale <= $thumbnail_size) {
59
                @copy($filename, $thumbnails_filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
60
            }
61
            else if ($_FILES[$field]['type'] == 'image/jpeg' || $_FILES[$field]['type'] == 'image/jpg') {
62
                $src_image = imagecreatefromjpeg($filename);
63
                $dst_image = imagecreatetruecolor($thumbnails_width, $thumbnails_height);
64
                imagecopyresized($dst_image, $src_image, 0, 0, 0, 0, $thumbnails_width, $thumbnails_height, $width, $height);
65
                imagejpeg($dst_image, $thumbnails_filename);
66
            }
67
            else if ($_FILES[$field]['type'] == 'image/png') {
68
                $src_image = imagecreatefrompng($filename);
69
                $dst_image = imagecreatetruecolor($thumbnails_width, $thumbnails_height);
70
                imagecopyresized($dst_image, $src_image, 0, 0, 0, 0, $thumbnails_width, $thumbnails_height, $width, $height);
71
                imagepng($dst_image, $thumbnails_filename);
72
            }
73
            else if ($_FILES[$field]['type'] == 'image/gif') {
74
                $src_image = imagecreatefromgif($filename);
75
                $dst_image = imagecreatetruecolor($thumbnails_width, $thumbnails_height);
76
                imagecopyresized($dst_image, $src_image, 0, 0, 0, 0, $thumbnails_width, $thumbnails_height, $width, $height);
77
                imagegif($dst_image, $thumbnails_filename);
78
            }
79
            else 
80
            {
81
                @copy($filename, $thumbnails_filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
82
            }
83
            $data['thumbnails_index'] = $basename . '_thumbnails';
84
            // move the thumbnails
85
            @rename($thumbnails_filename, $sub_save_path . $data['thumbnails_index']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
86
        }
87
        // move original file
88
        @rename($filename, $sub_save_path . $basename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
89
        $data['uploader'] = [ 'id' => $this->user->id, 'name' => $this->user->first_name, 'email' => $this->user->email ];
90
        $file = File::create($data);
91
92
        $issue_id = $request->input('issue_id');
93
        if (isset($issue_id) && $issue_id) {
94
            Event::fire(new FileUploadEvent($project_key, $issue_id, $field, $file->id, $data['uploader']));
95
        }
96
97
        return response()->json([ 'ecode' => 0, 'data' => [ 'field' => $field, 'file' => File::find($file->id), 'filename' => '/actionview/api/project/' . $project_key . '/file/' . $file->id ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
98
    }
99
100
    /**
101
     * Download small image file.
102
     *
103
     * @param \Illuminate\Http\Request $request
104
     * @param String                   $id
105
     */
106
    public function downloadThumbnail(Request $request, $project_key, $id)
107
    {
108
        $file = File::find($id);
109
        $filepath = config('filesystems.disks.local.root', '/tmp') . '/' . substr($file->index, 0, 2);
110
        $filename = $filepath . '/' . $file->thumbnails_index;
111
112
        if (!file_exists($filename)) {
113
            throw new \UnexpectedValueException('file does not exist.', -15100);
114
        }
115
116
        FileUtil::download($filename, $file->name);
117
    }
118
119
    /**
120
     * Download file.
121
     *
122
     * @param \Illuminate\Http\Request $request
123
     * @param String                   $id
124
     */
125
    public function download(Request $request, $project_key, $id)
126
    {
127
        set_time_limit(0);
128
129
        $file = File::find($id); 
130
        if (!$file || $file->del_flg == 1) {
131
            throw new \UnexpectedValueException('file does not exist.', -15100);
132
        }
133
134
        $filepath = config('filesystems.disks.local.root', '/tmp') . '/' . substr($file->index, 0, 2);
135
        $filename = $filepath . '/' . $file->index;
136
        if (!file_exists($filename)) {
137
            throw new \UnexpectedValueException('file does not exist.', -15100);
138
        }
139
140
        FileUtil::download($filename, $file->name);
141
    }
142
143
    /**
144
     * get avatar file.
145
     *
146
     * @param \Illuminate\Http\Request $request
147
     */
148
    public function getAvatar(Request $request)
149
    {
150
        $fid = $request->input('fid');
151
        if (!isset($fid) || !$fid) {
152
            throw new \UnexpectedValueException('the avatar file id cannot empty.', -15100);
153
        }
154
155
        $filename = config('filesystems.disks.local.root', '/tmp') . '/avatar/' . $fid;
156
        if (!file_exists($filename)) {
157
            throw new \UnexpectedValueException('the avatar file does not exist.', -15100);
158
        }
159
160
        FileUtil::download($filename, $filename);
161
    }
162
163
    /**
164
     * Delete file.
165
     *
166
     * @param  \Illuminate\Http\Request $request
167
     * @param  String                   $project_key
168
     * @param  String                   $id
169
     * @return \Illuminate\Http\Response
170
     */
171
    public function delete(Request $request, $project_key, $id)
172
    {
173
        $file = File::find($id);
174
        //if (!file || $file->del_flg == 1)
175
        //{
176
        //    throw new \UnexpectedValueException('file does not exist.', -15100);
177
        //}
178
179 View Code Duplication
        if ($file && !$this->isPermissionAllowed($project_key, 'remove_file') && !($this->isPermissionAllowed($project_key, 'remove_self_file') && $file->uploader['id'] == $this->user->id)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
            return response()->json(['ecode' => -10002, 'emsg' => 'permission denied.']);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
181
        }
182
183
        $issue_id = $request->input('issue_id');
184
        $field_key = $request->input('field_key');
185
        if (isset($issue_id) && $issue_id && isset($field_key) && $field_key) {
186
            $user = [ 'id' => $this->user->id, 'name' => $this->user->first_name, 'email' => $this->user->email ];
187
            Event::fire(new FileDelEvent($project_key, $issue_id, $field_key, $id, $user));
188
        }
189
190
        // logically deleted
191
        if ($file) {
192
            $file->fill([ 'del_flg' => 1 ])->save();
193
        }
194
195
        $issue = DB::collection('issue_' . $project_key)->where('_id', $issue_id)->first();
196
        if (array_search($id, $issue[$field_key]) === false) {
197
            return response()->json(['ecode' => 0, 'data' => ['id' => $id]]);
198
        }
199
        else
200
        {
201
            throw new \UnexpectedValueException('file deletion failed.', -15102);
202
        }
203
    }
204
205
    /**
206
     * Upload temporary file.
207
     *
208
     * @param  \Illuminate\Http\Request $request
209
     * @return \Illuminate\Http\Response
210
     */
211
    public function uploadTmpFile(Request $request)
212
    {
213
        set_time_limit(0);
214
215 View Code Duplication
        if (empty($_FILES) || $_FILES['file']['error'] > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
            throw new \UnexpectedValueException('upload file errors.', -15101);
217
        }
218
219
        $basename = md5(microtime() . $_FILES['file']['name']);
220
        $sub_save_path = config('filesystems.disks.local.root', '/tmp') . '/' . substr($basename, 0, 2) . '/';
221
        if (!is_dir($sub_save_path)) {
222
            @mkdir($sub_save_path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
223
        }
224
        $filename = '/tmp/' . $basename;
225
        move_uploaded_file($_FILES['file']['tmp_name'], $filename);
226
227
        // move original file
228
        @rename($filename, $sub_save_path . $basename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
229
        $data['uploader'] = [ 'id' => $this->user->id, 'name' => $this->user->first_name, 'email' => $this->user->email ];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
230
        $file = File::create($data);
0 ignored issues
show
Unused Code introduced by
$file is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
231
232
        return response()->json([ 'ecode' => 0, 'data' => [ 'fid' => $basename, 'fname' => $_FILES['file']['name'] ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
233
    }
234
}
235