Failed Conditions
Pull Request — experimental/sf (#31)
by Kentaro
06:59
created

FileController::upload()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 41

Duplication

Lines 7
Ratio 17.07 %

Code Coverage

Tests 16
CRAP Score 5.7044

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 1
dl 7
loc 41
rs 8.9528
c 0
b 0
f 0
ccs 16
cts 23
cp 0.6957
crap 5.7044
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Content;
15
16
use Eccube\Controller\AbstractController;
17
use Eccube\Util\FilesystemUtil;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
21
use Symfony\Component\Filesystem\Exception\IOException;
22
use Symfony\Component\Filesystem\Filesystem;
23
use Symfony\Component\Finder\Finder;
24
use Symfony\Component\Form\Extension\Core\Type\FileType;
25
use Symfony\Component\Form\Extension\Core\Type\FormType;
26
use Symfony\Component\Form\Extension\Core\Type\TextType;
27
use Symfony\Component\HttpFoundation\BinaryFileResponse;
28
use Symfony\Component\HttpFoundation\File\Exception\FileException;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
31
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
32
use Symfony\Component\Validator\Constraints as Assert;
33
34
class FileController extends AbstractController
35
{
36
    const SJIS = 'sjis-win';
37
    const UTF = 'UTF-8';
38
    private $errors = [];
39
    private $encode = '';
40
41
    /**
42
     * FileController constructor.
43
     */
44 6
    public function __construct()
45
    {
46 6
        $this->encode = self::UTF;
47 6
        if ('\\' === DIRECTORY_SEPARATOR) {
48
            $this->encode = self::SJIS;
49
        }
50
    }
51
52
    /**
53
     * @Route("/%eccube_admin_route%/content/file_manager", name="admin_content_file")
54
     * @Template("@admin/Content/file.twig")
55
     */
56 3
    public function index(Request $request)
57
    {
58 3
        $form = $this->formFactory->createBuilder(FormType::class)
59 3
            ->add('file', FileType::class)
60 3
            ->add('create_file', TextType::class)
61 3
            ->getForm();
62
63
        // user_data_dir
64 3
        $userDataDir = $this->getUserDataDir();
65 3
        $topDir = $this->normalizePath($userDataDir);
66
//        $topDir = '/';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
67
        // user_data_dirの親ディレクトリ
68 3
        $htmlDir = $this->normalizePath($this->getUserDataDir().'/../');
69
70
        // カレントディレクトリ
71 3
        $nowDir = $this->checkDir($this->getUserDataDir($request->get('tree_select_file')), $this->getUserDataDir())
72 3
            ? $this->normalizePath($this->getUserDataDir($request->get('tree_select_file')))
73 3
            : $topDir;
74
75
        // パンくず表示用データ
76 3
        $nowDirList = json_encode(explode('/', trim(str_replace($htmlDir, '', $nowDir), '/')));
77 3
        $jailNowDir = $this->getJailDir($nowDir);
78 3
        $isTopDir = ($topDir === $jailNowDir);
79 3
        $parentDir = substr($nowDir, 0, strrpos($nowDir, '/'));
80
81 3
        if ('POST' === $request->getMethod()) {
82 2
            switch ($request->get('mode')) {
83
                case 'create':
84 1
                    $this->create($request);
85 1
                    break;
86
                case 'upload':
87 1
                    $this->upload($request);
88 1
                    break;
89
                default:
90
                    break;
91
            }
92
        }
93 3
        $tree = $this->getTree($this->getUserDataDir(), $request);
94 3
        $arrFileList = $this->getFileList($nowDir);
95 3
        $paths = $this->getPathsToArray($tree);
96 3
        $tree = $this->getTreeToArray($tree);
97
98
        return [
99 3
            'form' => $form->createView(),
100 3
            'tpl_javascript' => json_encode($tree),
101 3
            'top_dir' => $this->getJailDir($topDir),
102 3
            'tpl_is_top_dir' => $isTopDir,
103 3
            'tpl_now_dir' => $jailNowDir,
104 3
            'html_dir' => $this->getJailDir($htmlDir),
105 3
            'now_dir_list' => $nowDirList,
106 3
            'tpl_parent_dir' => $this->getJailDir($parentDir),
107 3
            'arrFileList' => $arrFileList,
108 3
            'errors' => $this->errors,
109 3
            'paths' => json_encode($paths),
110
        ];
111
    }
112
113
    /**
114
     * @Route("/%eccube_admin_route%/content/file_view", name="admin_content_file_view")
115
     */
116 1
    public function view(Request $request)
117
    {
118 1
        $file = $this->convertStrToServer($this->getUserDataDir($request->get('file')));
119 1
        if ($this->checkDir($file, $this->getUserDataDir())) {
120 1
            setlocale(LC_ALL, 'ja_JP.UTF-8');
121
122 1
            return new BinaryFileResponse($file);
123
        }
124
125
        throw new NotFoundHttpException();
126
    }
127
128
    /**
129
     * Create directory
130
     *
131
     * @param Request $request
132
     */
133 1
    public function create(Request $request)
134
    {
135 1
        $form = $this->formFactory->createBuilder(FormType::class)
136 1
            ->add('file', FileType::class)
137 1
            ->add('create_file', TextType::class, [
138
                'constraints' => [
139 1
                    new Assert\NotBlank([
140 1
                        'message' => 'file.text.error.folder_name',
141
                    ]),
142 1
                    new Assert\Regex([
143 1
                        'pattern' => '/[^[:alnum:]_.\\-]/',
144
                        'match' => false,
145
                        'message' => 'file.text.error.folder_symbol',
146
                    ]),
147 1
                    new Assert\Regex([
148 1
                        'pattern' => "/^\.(.*)$/",
149
                        'match' => false,
150
                        'message' => 'file.text.error.folder_period',
151
                    ]),
152
                ],
153
            ])
154 1
            ->getForm();
155
156 1
        $form->handleRequest($request);
157 1 View Code Duplication
        if (!$form->isValid()) {
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...
158
            foreach ($form->getErrors(true) as $error) {
159
                $this->errors[] = ['message' => $error->getMessage()];
0 ignored issues
show
Bug introduced by
The method getMessage does only exist in Symfony\Component\Form\FormError, but not in Symfony\Component\Form\FormErrorIterator.

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...
160
            }
161
162
            return;
163
        }
164
165 1
        $fs = new Filesystem();
166 1
        $filename = $form->get('create_file')->getData();
167
168
        try {
169 1
            $topDir = $this->getUserDataDir();
170 1
            $nowDir = $this->getUserDataDir($request->get('now_dir'));
171 1
            $nowDir = $this->checkDir($nowDir, $topDir)
172
                ? $this->normalizePath($nowDir)
173 1
                : $topDir;
174 1
            $fs->mkdir($nowDir.'/'.$filename);
175
176 1
            $this->addSuccess('admin.content.file.create_dir_success', 'admin');
177
        } catch (IOException $e) {
178
            $this->errors[] = ['message' => $e->getMessage()];
179
        }
180
    }
181
182
    /**
183
     * @Method("DELETE")
184
     * @Route("/%eccube_admin_route%/content/file_delete", name="admin_content_file_delete")
185
     */
186 1
    public function delete(Request $request)
187
    {
188 1
        $this->isTokenValid();
189
190 1
        $topDir = $this->getUserDataDir();
191 1
        $file = $this->convertStrToServer($this->getUserDataDir($request->get('select_file')));
192 1
        if ($this->checkDir($file, $topDir)) {
193 1
            $fs = new Filesystem();
194 1
            if ($fs->exists($file)) {
195 1
                $fs->remove($file);
196 1
                $this->addSuccess('admin.delete.complete', 'admin');
197
            }
198
        }
199
200 1
        return $this->redirectToRoute('admin_content_file');
201
    }
202
203
    /**
204
     * @Route("/%eccube_admin_route%/content/file_download", name="admin_content_file_download")
205
     */
206 1
    public function download(Request $request)
207
    {
208 1
        $topDir = $this->getUserDataDir();
209 1
        $file = $this->convertStrToServer($this->getUserDataDir($request->get('select_file')));
210 1
        if ($this->checkDir($file, $topDir)) {
211 1
            if (!is_dir($file)) {
212 1
                setlocale(LC_ALL, 'ja_JP.UTF-8');
213 1
                $pathParts = pathinfo($file);
214
215
                $patterns = [
216 1
                    '/[a-zA-Z0-9!"#$%&()=~^|@`:*;+{}]/',
217
                    '/[- ,.<>?_[\]\/\\\\]/',
218
                    "/['\r\n\t\v\f]/",
219
                ];
220
221 1
                $str = preg_replace($patterns, '', $pathParts['basename']);
222 1
                if (strlen($str) === 0) {
223 1
                    return (new BinaryFileResponse($file))->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
224
                } else {
225
                    return new BinaryFileResponse($file, 200, [
226
                        'Content-Type' => 'aplication/octet-stream;',
227
                        'Content-Disposition' => "attachment; filename*=UTF-8\'\'".rawurlencode($this->convertStrFromServer($pathParts['basename'])),
228
                    ]);
229
                }
230
            }
231
        }
232
        throw new NotFoundHttpException();
233
    }
234
235 1
    public function upload(Request $request)
236
    {
237 1
        $form = $this->formFactory->createBuilder(FormType::class)
238 1
            ->add('file', FileType::class, [
239
                'constraints' => [
240 1
                    new Assert\NotBlank([
241 1
                        'message' => 'file.text.error.file_not_selected',
242
                    ]),
243
                ],
244
            ])
245 1
            ->add('create_file', TextType::class)
246 1
            ->getForm();
247
248 1
        $form->handleRequest($request);
249
250 1 View Code Duplication
        if (!$form->isValid()) {
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...
251
            foreach ($form->getErrors(true) as $error) {
252
                $this->errors[] = ['message' => $error->getMessage()];
0 ignored issues
show
Bug introduced by
The method getMessage does only exist in Symfony\Component\Form\FormError, but not in Symfony\Component\Form\FormErrorIterator.

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...
253
            }
254
255
            return;
256
        }
257
258 1
        $data = $form->getData();
259 1
        $topDir = $this->getUserDataDir();
260 1
        $nowDir = $this->getUserDataDir($request->get('now_dir'));
261
262 1
        if (!$this->checkDir($nowDir, $topDir)) {
263
            $this->errors[] = ['message' => 'file.text.error.invalid_upload_folder'];
264
265
            return;
266
        }
267
268 1
        $filename = $this->convertStrToServer($data['file']->getClientOriginalName());
269
        try {
270 1
            $data['file']->move($nowDir, $filename);
271 1
            $this->addSuccess('admin.content.file.upload_success', 'admin');
272
        } catch (FileException $e) {
273
            $this->errors[] = ['message' => $e->getMessage()];
274
        }
275
    }
276
277 3
    private function getTreeToArray($tree)
278
    {
279 3
        $arrTree = [];
280 3
        foreach ($tree as $key => $val) {
281 3
            $path = $this->getJailDir($val['path']);
282 3
            $arrTree[$key] = [
283 3
                $key,
284 3
                $val['type'],
285 3
                $path,
286 3
                $val['depth'],
287 3
                $val['open'] ? 'true' : 'false',
288
            ];
289
        }
290
291 3
        return $arrTree;
292
    }
293
294 3
    private function getPathsToArray($tree)
295
    {
296 3
        $paths = [];
297 3
        foreach ($tree as $val) {
298 3
            $paths[] = $this->getJailDir($val['path']);
299
        }
300
301 3
        return $paths;
302
    }
303
304 3
    /**
305
     * @param string $topDir
306 3
     * @param Request $request
307 3
     */
308 3
    private function getTree($topDir, $request)
309
    {
310 3
        $finder = Finder::create()->in($topDir)
311 3
            ->directories()
312 3
            ->sortByName();
313 3
314 3
        $tree = [];
315
        $tree[] = [
316
            'path' => $topDir,
317
            'type' => '_parent',
318 3
            'depth' => 0,
319
            'open' => true,
320 3
        ];
321 3
322
        $defaultDepth = count(explode('/', $topDir));
323
324
        $openDirs = [];
325 3
        if ($request->get('tree_status')) {
326 1
            $openDirs = explode('|', $request->get('tree_status'));
327 1
        }
328 1
329 1
        foreach ($finder as $dirs) {
330 1
            $path = $this->normalizePath($dirs->getRealPath());
331 1
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
332 1
            $depth = count(explode('/', $path)) - $defaultDepth;
333 1
            $tree[] = [
334
                'path' => $path,
335
                'type' => $type,
336
                'depth' => $depth,
337 3
                'open' => (in_array($path, $openDirs)) ? true : false,
338
            ];
339
        }
340 3
341
        return $tree;
342 3
    }
343 3
344 3
    /**
345 3
     * @param string $nowDir
346
     */
347 3
    private function getFileList($nowDir)
348 3
    {
349
        $topDir = $this->getuserDataDir();
350 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
351 3
            $acceptPath = realpath($topDir);
352 3
            $targetPath = $file->getRealPath();
353 3
354 3
            return strpos($targetPath, $acceptPath) === 0;
355 3
        };
356
357 3
        $finder = Finder::create()
358
            ->filter($filter)
359
            ->in($nowDir)
360
            ->ignoreDotFiles(false)
361
            ->sortByName()
362 3
            ->depth(0);
363
        $dirFinder = $finder->directories();
364 3
        try {
365
            $dirs = $dirFinder->getIterator();
366
        } catch (\Exception $e) {
367
            $dirs = [];
368
        }
369 3
370 3
        $fileFinder = $finder->files();
371 1
        try {
372 1
            $files = $fileFinder->getIterator();
373 1
        } catch (\Exception $e) {
374 1
            $files = [];
375 1
        }
376 1
377 1
        $arrFileList = [];
378 1
        foreach ($dirs as $dir) {
379 1
            $dirPath = $this->normalizePath($dir->getRealPath());
380 1
            $childDir = Finder::create()
381 1
                ->in($dirPath)
382 1
                ->ignoreDotFiles(false)
383 1
                ->directories()
384 1
                ->depth(0);
385 1
            $childFile = Finder::create()
386
                ->in($dirPath)
387 1
                ->ignoreDotFiles(false)
388
                ->files()
389
                ->depth(0);
390 3
            $countNumber = $childDir->count() + $childFile->count();
391 3
            $arrFileList[] = [
392 3
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
393 3
                'file_path' => $this->convertStrFromServer($this->getJailDir($dirPath)),
394 3
                'file_size' => FilesystemUtil::sizeToHumanReadable($dir->getSize()),
395 3
                'file_time' => $dir->getmTime(),
396
                'is_dir' => true,
397
                'is_empty' => $countNumber == 0 ? true : false,
398 3
            ];
399
        }
400
        foreach ($files as $file) {
401
            $arrFileList[] = [
402 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
403
                'file_path' => $this->convertStrFromServer($this->getJailDir($this->normalizePath($file->getRealPath()))),
404
                'file_size' => FilesystemUtil::sizeToHumanReadable($file->getSize()),
405 3
                'file_time' => $file->getmTime(),
406
                'is_dir' => false,
407 3
                'is_empty' => false,
408
                'extension' => $file->getExtension(),
409
            ];
410 6
        }
411
412 6
        return $arrFileList;
413 6
    }
414
415 6
    protected function normalizePath($path)
416
    {
417
        return str_replace('\\', '/', realpath($path));
418 3
    }
419
420 3
    /**
421
     * @param string $topDir
422
     */
423
    protected function checkDir($targetDir, $topDir)
424 3
    {
425
        $targetDir = realpath($targetDir);
426
        $topDir = realpath($topDir);
427 4
428
        return strpos($targetDir, $topDir) === 0;
429 4
    }
430
431
    /**
432
     * @return string
433 4
     */
434 View Code Duplication
    private function convertStrFromServer($target)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
435
    {
436 6
        if ($this->encode == self::SJIS) {
437
            return mb_convert_encoding($target, self::UTF, self::SJIS);
438 6
        }
439
440
        return $target;
441 3
    }
442
443 3 View Code Duplication
    private function convertStrToServer($target)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
444 3
    {
445
        if ($this->encode == self::SJIS) {
446 3
            return mb_convert_encoding($target, self::SJIS, self::UTF);
447
        }
448
449
        return $target;
450
    }
451
452
    private function getUserDataDir($nowDir = null)
453
    {
454
        return rtrim($this->getParameter('kernel.project_dir').'/html/user_data'.$nowDir, '/');
455
    }
456
457
    private function getJailDir($path)
458
    {
459
        $realpath = realpath($path);
460
        $jailPath = str_replace(realpath($this->getUserDataDir()), '', $realpath);
461
462
        return $jailPath ? $jailPath : '/';
463
    }
464
}
465