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