Failed Conditions
Branch experimental/sf (68db07)
by Kentaro
42:17 queued 33:39
created

FileController::getJailDir()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 2
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
20
use Symfony\Component\Filesystem\Filesystem;
21
use Symfony\Component\Finder\Finder;
22
use Symfony\Component\Form\Extension\Core\Type\FileType;
23
use Symfony\Component\Form\Extension\Core\Type\FormType;
24
use Symfony\Component\Form\Extension\Core\Type\TextType;
25
use Symfony\Component\HttpFoundation\BinaryFileResponse;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
28
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29
use Symfony\Component\HttpFoundation\File\Exception\FileException;
30
use Symfony\Component\Validator\Constraints as Assert;
31
use Eccube\Util\FilesystemUtil;
32
use Symfony\Component\Filesystem\Exception\IOException;
33
34
class FileController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
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
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
53
     * @Route("/%eccube_admin_route%/content/file_manager", name="admin_content_file")
54
     * @Template("@admin/Content/file.twig")
55
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
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 = '/';
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
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
114
     * @Route("/%eccube_admin_route%/content/file_view", name="admin_content_file_view")
115
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
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()) {
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
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
183
     * @Method("DELETE")
184
     * @Route("/%eccube_admin_route%/content/file_delete", name="admin_content_file_delete")
185
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
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
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
204
     * @Route("/%eccube_admin_route%/content/file_download", name="admin_content_file_download")
205
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
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()) {
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
    private function getTree($topDir, $request)
305
    {
306 3
        $finder = Finder::create()->in($topDir)
307 3
            ->directories()
308 3
            ->sortByName();
309
310 3
        $tree = [];
311 3
        $tree[] = [
312 3
            'path' => $topDir,
313 3
            'type' => '_parent',
314 3
            'depth' => 0,
315
            'open' => true,
316
        ];
317
318 3
        $defaultDepth = count(explode('/', $topDir));
319
320 3
        $openDirs = [];
321 3
        if ($request->get('tree_status')) {
322
            $openDirs = explode('|', $request->get('tree_status'));
323
        }
324
325 3
        foreach ($finder as $dirs) {
326 1
            $path = $this->normalizePath($dirs->getRealPath());
327 1
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
328 1
            $depth = count(explode('/', $path)) - $defaultDepth;
329 1
            $tree[] = [
330 1
                'path' => $path,
331 1
                'type' => $type,
332 1
                'depth' => $depth,
333 1
                'open' => (in_array($path, $openDirs)) ? true : false,
334
            ];
335
        }
336
337 3
        return $tree;
338
    }
339
340 3
    private function getFileList($nowDir)
341
    {
342 3
        $topDir = $this->getuserDataDir();
343 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
344 3
            $acceptPath = realpath($topDir);
345 3
            $targetPath = $file->getRealPath();
346
347 3
            return strpos($targetPath, $acceptPath) === 0;
348 3
        };
349
350 3
        $finder = Finder::create()
351 3
            ->filter($filter)
352 3
            ->in($nowDir)
353 3
            ->sortByName()
354 3
            ->depth(0);
355 3
        $dirFinder = $finder->directories();
356
        try {
357 3
            $dirs = $dirFinder->getIterator();
358
        } catch (\Exception $e) {
359
            $dirs = [];
360
        }
361
362 3
        $fileFinder = $finder->files();
363
        try {
364 3
            $files = $fileFinder->getIterator();
365
        } catch (\Exception $e) {
366
            $files = [];
367
        }
368
369 3
        $arrFileList = [];
370 3
        foreach ($dirs as $dir) {
371 1
            $dirPath = $this->normalizePath($dir->getRealPath());
372 1
            $childDir = Finder::create()
373 1
                ->in($dirPath)
374 1
                ->directories()
375 1
                ->depth(0);
376 1
            $childFile = Finder::create()
377 1
                ->in($dirPath)
378 1
                ->files()
379 1
                ->depth(0);
380 1
            $countNumber = $childDir->count() + $childFile->count();
381 1
            $arrFileList[] = [
382 1
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
383 1
                'file_path' => $this->convertStrFromServer($this->getJailDir($dirPath)),
384 1
                'file_size' => FilesystemUtil::sizeToHumanReadable($dir->getSize()),
385 1
                'file_time' => $dir->getmTime(),
386
                'is_dir' => true,
387 1
                'is_empty' => $countNumber == 0 ? true : false,
388
            ];
389
        }
390 3
        foreach ($files as $file) {
391 3
            $arrFileList[] = [
392 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
393 3
                'file_path' => $this->convertStrFromServer($this->getJailDir($this->normalizePath($file->getRealPath()))),
394 3
                'file_size' => FilesystemUtil::sizeToHumanReadable($file->getSize()),
395 3
                'file_time' => $file->getmTime(),
396
                'is_dir' => false,
397
                'is_empty' => false,
398 3
                'extension' => $file->getExtension(),
399
            ];
400
        }
401
402 3
        return $arrFileList;
403
    }
404
405 3
    protected function normalizePath($path)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
406
    {
407 3
        return str_replace('\\', '/', realpath($path));
408
    }
409
410 6
    protected function checkDir($targetDir, $topDir)
411
    {
412 6
        $targetDir = realpath($targetDir);
413 6
        $topDir = realpath($topDir);
414
415 6
        return strpos($targetDir, $topDir) === 0;
416
    }
417
418 3 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...
419
    {
420 3
        if ($this->encode == self::SJIS) {
421
            return mb_convert_encoding($target, self::UTF, self::SJIS);
422
        }
423
424 3
        return $target;
425
    }
426
427 4 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...
428
    {
429 4
        if ($this->encode == self::SJIS) {
430
            return mb_convert_encoding($target, self::SJIS, self::UTF);
431
        }
432
433 4
        return $target;
434
    }
435
436 6
    private function getUserDataDir($nowDir = null)
437
    {
438 6
        return rtrim($this->getParameter('kernel.project_dir').'/html/user_data'.$nowDir, '/');
439
    }
440
441 3
    private function getJailDir($path)
442
    {
443 3
        $realpath = realpath($path);
444 3
        $jailPath = str_replace(realpath($this->getUserDataDir()), '', $realpath);
445
446 3
        return $jailPath ? $jailPath : '/';
447
    }
448
}
449