Completed
Push — 4.0 ( b48f64...137622 )
by chihiro
20:21 queued 10s
created

Eccube/Controller/Admin/Content/FileController.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\Template;
19
use Symfony\Component\Filesystem\Exception\IOException;
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\File\Exception\FileException;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
29
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
30
use Symfony\Component\Routing\Annotation\Route;
31
use Symfony\Component\Validator\Constraints as Assert;
32
33
class FileController extends AbstractController
34
{
35
    const SJIS = 'sjis-win';
36
    const UTF = 'UTF-8';
37
    private $errors = [];
38
    private $encode = '';
39
40
    /**
41
     * FileController constructor.
42
     */
43
    public function __construct()
44 6
    {
45
        $this->encode = self::UTF;
46 6
        if ('\\' === DIRECTORY_SEPARATOR) {
47 6
            $this->encode = self::SJIS;
48
        }
49
    }
50
51
    /**
52
     * @Route("/%eccube_admin_route%/content/file_manager", name="admin_content_file")
53
     * @Template("@admin/Content/file.twig")
54
     */
55
    public function index(Request $request)
56 3
    {
57
        $form = $this->formFactory->createBuilder(FormType::class)
58 3
            ->add('file', FileType::class)
59 3
            ->add('create_file', TextType::class)
60 3
            ->getForm();
61 3
62
        // user_data_dir
63
        $userDataDir = $this->getUserDataDir();
64 3
        $topDir = $this->normalizePath($userDataDir);
65 3
        //        $topDir = '/';
66
        // user_data_dirの親ディレクトリ
67
        $htmlDir = $this->normalizePath($this->getUserDataDir().'/../');
68 3
69
        // カレントディレクトリ
70
        $nowDir = $this->checkDir($this->getUserDataDir($request->get('tree_select_file')), $this->getUserDataDir())
71 3
            ? $this->normalizePath($this->getUserDataDir($request->get('tree_select_file')))
72 3
            : $topDir;
73 3
74
        // パンくず表示用データ
75
        $nowDirList = json_encode(explode('/', trim(str_replace($htmlDir, '', $nowDir), '/')));
76 3
        $jailNowDir = $this->getJailDir($nowDir);
77 3
        $isTopDir = ($topDir === $jailNowDir);
78 3
        $parentDir = substr($nowDir, 0, strrpos($nowDir, '/'));
79 3
80
        if ('POST' === $request->getMethod()) {
81 3
            switch ($request->get('mode')) {
82 2
                case 'create':
83
                    $this->create($request);
84 1
                    break;
85 1
                case 'upload':
86
                    $this->upload($request);
87 1
                    break;
88 1
                default:
89
                    break;
90
            }
91
        }
92
        $tree = $this->getTree($this->getUserDataDir(), $request);
93 3
        $arrFileList = $this->getFileList($nowDir);
94 3
        $paths = $this->getPathsToArray($tree);
95 3
        $tree = $this->getTreeToArray($tree);
96 3
97
        return [
98
            'form' => $form->createView(),
99 3
            'tpl_javascript' => json_encode($tree),
100 3
            'top_dir' => $this->getJailDir($topDir),
101 3
            'tpl_is_top_dir' => $isTopDir,
102 3
            'tpl_now_dir' => $jailNowDir,
103 3
            'html_dir' => $this->getJailDir($htmlDir),
104 3
            'now_dir_list' => $nowDirList,
105 3
            'tpl_parent_dir' => $this->getJailDir($parentDir),
106 3
            'arrFileList' => $arrFileList,
107 3
            'errors' => $this->errors,
108 3
            'paths' => json_encode($paths),
109 3
        ];
110
    }
111
112
    /**
113
     * @Route("/%eccube_admin_route%/content/file_view", name="admin_content_file_view")
114
     */
115
    public function view(Request $request)
116 1
    {
117
        $file = $this->convertStrToServer($this->getUserDataDir($request->get('file')));
118 1
        if ($this->checkDir($file, $this->getUserDataDir())) {
119 1
            setlocale(LC_ALL, 'ja_JP.UTF-8');
120 1
121
            return new BinaryFileResponse($file);
122 1
        }
123
124
        throw new NotFoundHttpException();
125
    }
126
127
    /**
128
     * Create directory
129
     *
130
     * @param Request $request
131
     */
132
    public function create(Request $request)
133 1
    {
134
        $form = $this->formFactory->createBuilder(FormType::class)
135 1
            ->add('file', FileType::class)
136 1
            ->add('create_file', TextType::class, [
137 1
                'constraints' => [
138
                    new Assert\NotBlank(),
139 1
                    new Assert\Regex([
140 1
                        'pattern' => '/[^[:alnum:]_.\\-]/',
141
                        'match' => false,
142 1
                        'message' => 'file.text.error.folder_symbol',
143 1
                    ]),
144
                    new Assert\Regex([
145
                        'pattern' => "/^\.(.*)$/",
146
                        'match' => false,
147 1
                        'message' => 'file.text.error.folder_period',
148 1
                    ]),
149
                ],
150
            ])
151
            ->getForm();
152
153
        $form->handleRequest($request);
154 1 View Code Duplication
        if (!$form->isValid()) {
155
            foreach ($form->getErrors(true) as $error) {
156 1
                $this->errors[] = ['message' => $error->getMessage()];
0 ignored issues
show
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...
157 1
            }
158
159
            return;
160
        }
161
162
        $fs = new Filesystem();
163
        $filename = $form->get('create_file')->getData();
164
165 1
        try {
166 1
            $topDir = $this->getUserDataDir();
167
            $nowDir = $this->getUserDataDir($request->get('now_dir'));
168
            $nowDir = $this->checkDir($nowDir, $topDir)
169 1
                ? $this->normalizePath($nowDir)
170 1
                : $topDir;
171 1
            $fs->mkdir($nowDir.'/'.$filename);
172
173 1
            $this->addSuccess('admin.common.create_complete', 'admin');
174 1
        } catch (IOException $e) {
175
            $this->errors[] = ['message' => $e->getMessage()];
176 1
        }
177
    }
178
179
    /**
180
     * @Route("/%eccube_admin_route%/content/file_delete", name="admin_content_file_delete", methods={"DELETE"})
181
     */
182
    public function delete(Request $request)
183
    {
184
        $this->isTokenValid();
185
186 1
        $selectFile = $request->get('select_file');
187
        if (is_null($selectFile) || $selectFile == '/') {
188 1
            return $this->redirectToRoute('admin_content_file');
189
        }
190 1
191 1
        $topDir = $this->getUserDataDir();
192 1
        $file = $this->convertStrToServer($this->getUserDataDir($selectFile));
193 1
        if ($this->checkDir($file, $topDir)) {
194 1
            $fs = new Filesystem();
195 1
            if ($fs->exists($file)) {
196 1
                $fs->remove($file);
197
                $this->addSuccess('admin.common.delete_complete', 'admin');
198
            }
199
        }
200 1
201
        return $this->redirectToRoute('admin_content_file');
202
    }
203
204
    /**
205
     * @Route("/%eccube_admin_route%/content/file_download", name="admin_content_file_download")
206 1
     */
207
    public function download(Request $request)
208 1
    {
209 1
        $topDir = $this->getUserDataDir();
210 1
        $file = $this->convertStrToServer($this->getUserDataDir($request->get('select_file')));
211 1
        if ($this->checkDir($file, $topDir)) {
212 1
            if (!is_dir($file)) {
213 1
                setlocale(LC_ALL, 'ja_JP.UTF-8');
214
                $pathParts = pathinfo($file);
215
216 1
                $patterns = [
217
                    '/[a-zA-Z0-9!"#$%&()=~^|@`:*;+{}]/',
218
                    '/[- ,.<>?_[\]\/\\\\]/',
219
                    "/['\r\n\t\v\f]/",
220
                ];
221 1
222 1
                $str = preg_replace($patterns, '', $pathParts['basename']);
223 1
                if (strlen($str) === 0) {
224
                    return (new BinaryFileResponse($file))->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
225
                } else {
226
                    return new BinaryFileResponse($file, 200, [
227
                        'Content-Type' => 'aplication/octet-stream;',
228
                        'Content-Disposition' => "attachment; filename*=UTF-8\'\'".rawurlencode($this->convertStrFromServer($pathParts['basename'])),
229
                    ]);
230
                }
231
            }
232
        }
233
        throw new NotFoundHttpException();
234
    }
235 1
236
    public function upload(Request $request)
237 1
    {
238 1
        $form = $this->formFactory->createBuilder(FormType::class)
239
            ->add('file', FileType::class, [
240 1
                'constraints' => [
241 1
                    new Assert\NotBlank([
242
                        'message' => 'admin.common.file_select_empty',
243
                    ]),
244
                ],
245 1
            ])
246 1
            ->add('create_file', TextType::class)
247
            ->getForm();
248 1
249
        $form->handleRequest($request);
250 1
251 View Code Duplication
        if (!$form->isValid()) {
252
            foreach ($form->getErrors(true) as $error) {
253
                $this->errors[] = ['message' => $error->getMessage()];
0 ignored issues
show
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...
254
            }
255
256
            return;
257
        }
258 1
259 1
        $data = $form->getData();
260 1
        $topDir = $this->getUserDataDir();
261
        $nowDir = $this->getUserDataDir($request->get('now_dir'));
262 1
263
        if (!$this->checkDir($nowDir, $topDir)) {
264
            $this->errors[] = ['message' => 'file.text.error.invalid_upload_folder'];
265
266
            return;
267
        }
268 1
269
        $filename = $this->convertStrToServer($data['file']->getClientOriginalName());
270 1
        try {
271 1
            $data['file']->move($nowDir, $filename);
272
            $this->addSuccess('admin.common.upload_complete', 'admin');
273
        } catch (FileException $e) {
274
            $this->errors[] = ['message' => $e->getMessage()];
275
        }
276
    }
277 3
278
    private function getTreeToArray($tree)
279 3
    {
280 3
        $arrTree = [];
281 3
        foreach ($tree as $key => $val) {
282 3
            $path = $this->getJailDir($val['path']);
283 3
            $arrTree[$key] = [
284 3
                $key,
285 3
                $val['type'],
286 3
                $path,
287 3
                $val['depth'],
288
                $val['open'] ? 'true' : 'false',
289
            ];
290
        }
291 3
292
        return $arrTree;
293
    }
294 3
295
    private function getPathsToArray($tree)
296 3
    {
297 3
        $paths = [];
298 3
        foreach ($tree as $val) {
299
            $paths[] = $this->getJailDir($val['path']);
300
        }
301 3
302
        return $paths;
303
    }
304
305
    /**
306
     * @param string $topDir
307
     * @param Request $request
308 3
     */
309
    private function getTree($topDir, $request)
310 3
    {
311 3
        $finder = Finder::create()->in($topDir)
312 3
            ->directories()
313
            ->sortByName();
314 3
315 3
        $tree = [];
316 3
        $tree[] = [
317 3
            'path' => $topDir,
318 3
            'type' => '_parent',
319
            'depth' => 0,
320
            'open' => true,
321
        ];
322 3
323
        $defaultDepth = count(explode('/', $topDir));
324 3
325 3
        $openDirs = [];
326
        if ($request->get('tree_status')) {
327
            $openDirs = explode('|', $request->get('tree_status'));
328
        }
329 3
330 1
        foreach ($finder as $dirs) {
331 1
            $path = $this->normalizePath($dirs->getRealPath());
332 1
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
333 1
            $depth = count(explode('/', $path)) - $defaultDepth;
334 1
            $tree[] = [
335 1
                'path' => $path,
336 1
                'type' => $type,
337 1
                'depth' => $depth,
338
                'open' => (in_array($path, $openDirs)) ? true : false,
339
            ];
340
        }
341 3
342
        return $tree;
343
    }
344
345
    /**
346
     * @param string $nowDir
347 3
     */
348
    private function getFileList($nowDir)
349 3
    {
350 3
        $topDir = $this->getuserDataDir();
351 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
352 3
            $acceptPath = realpath($topDir);
353
            $targetPath = $file->getRealPath();
354 3
355 3
            return strpos($targetPath, $acceptPath) === 0;
356
        };
357 3
358 3
        $finder = Finder::create()
359 3
            ->filter($filter)
360 3
            ->in($nowDir)
361 3
            ->ignoreDotFiles(false)
362 3
            ->sortByName()
363 3
            ->depth(0);
364
        $dirFinder = $finder->directories();
365 3
        try {
366
            $dirs = $dirFinder->getIterator();
367
        } catch (\Exception $e) {
368
            $dirs = [];
369
        }
370 3
371
        $fileFinder = $finder->files();
372 3
        try {
373
            $files = $fileFinder->getIterator();
374
        } catch (\Exception $e) {
375
            $files = [];
376
        }
377 3
378 3
        $arrFileList = [];
379 1
        foreach ($dirs as $dir) {
380 1
            $dirPath = $this->normalizePath($dir->getRealPath());
381 1
            $childDir = Finder::create()
382 1
                ->in($dirPath)
383 1
                ->ignoreDotFiles(false)
384 1
                ->directories()
385 1
                ->depth(0);
386 1
            $childFile = Finder::create()
387 1
                ->in($dirPath)
388 1
                ->ignoreDotFiles(false)
389 1
                ->files()
390 1
                ->depth(0);
391 1
            $countNumber = $childDir->count() + $childFile->count();
392 1
            $arrFileList[] = [
393 1
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
394 1
                'file_path' => $this->convertStrFromServer($this->getJailDir($dirPath)),
395 1
                'file_size' => FilesystemUtil::sizeToHumanReadable($dir->getSize()),
396
                'file_time' => $dir->getmTime(),
397 1
                'is_dir' => true,
398
                'is_empty' => $countNumber == 0 ? true : false,
399
            ];
400 3
        }
401 3
        foreach ($files as $file) {
402 3
            $arrFileList[] = [
403 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
404 3
                'file_path' => $this->convertStrFromServer($this->getJailDir($this->normalizePath($file->getRealPath()))),
405 3
                'file_size' => FilesystemUtil::sizeToHumanReadable($file->getSize()),
406
                'file_time' => $file->getmTime(),
407
                'is_dir' => false,
408 3
                'is_empty' => false,
409
                'extension' => $file->getExtension(),
410
            ];
411
        }
412 3
413
        return $arrFileList;
414
    }
415 3
416
    protected function normalizePath($path)
417 3
    {
418
        return str_replace('\\', '/', realpath($path));
419
    }
420
421
    /**
422
     * @param string $topDir
423 6
     */
424
    protected function checkDir($targetDir, $topDir)
425 6
    {
426 6
        $targetDir = realpath($targetDir);
427
        $topDir = realpath($topDir);
428 6
429
        return strpos($targetDir, $topDir) === 0;
430
    }
431
432
    /**
433
     * @return string
434 3
     */
435 View Code Duplication
    private function convertStrFromServer($target)
436 3
    {
437
        if ($this->encode == self::SJIS) {
438
            return mb_convert_encoding($target, self::UTF, self::SJIS);
439
        }
440 3
441
        return $target;
442
    }
443 4
444 View Code Duplication
    private function convertStrToServer($target)
445 4
    {
446
        if ($this->encode == self::SJIS) {
447
            return mb_convert_encoding($target, self::SJIS, self::UTF);
448
        }
449 4
450
        return $target;
451
    }
452 6
453
    private function getUserDataDir($nowDir = null)
454 6
    {
455
        return rtrim($this->getParameter('kernel.project_dir').'/html/user_data'.$nowDir, '/');
456
    }
457 3
458
    private function getJailDir($path)
459 3
    {
460 3
        $realpath = realpath($path);
461
        $jailPath = str_replace(realpath($this->getUserDataDir()), '', $realpath);
462 3
463
        return $jailPath ? $jailPath : '/';
464
    }
465
}
466