Failed Conditions
Pull Request — experimental/sf (#3236)
by Kentaro
144:19 queued 116:23
created

Eccube/Controller/Admin/Content/FileController.php (1 issue)

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\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 = '/';
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()) {
158
            foreach ($form->getErrors(true) as $error) {
159
                $this->errors[] = ['message' => $error->getMessage()];
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()) {
251
            foreach ($form->getErrors(true) as $error) {
252
                $this->errors[] = ['message' => $error->getMessage()];
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
    /**
305
     * @param string $topDir
306
     * @param Request $request
307
     */
308 3
    private function getTree($topDir, $request)
309
    {
310 3
        $finder = Finder::create()->in($topDir)
311 3
            ->directories()
312 3
            ->sortByName();
313
314 3
        $tree = [];
315 3
        $tree[] = [
316 3
            'path' => $topDir,
317 3
            'type' => '_parent',
318 3
            'depth' => 0,
319
            'open' => true,
320
        ];
321
322 3
        $defaultDepth = count(explode('/', $topDir));
323
324 3
        $openDirs = [];
325 3
        if ($request->get('tree_status')) {
326
            $openDirs = explode('|', $request->get('tree_status'));
327
        }
328
329 3
        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 1
                'path' => $path,
335 1
                'type' => $type,
336 1
                'depth' => $depth,
337 1
                'open' => (in_array($path, $openDirs)) ? true : false,
338
            ];
339
        }
340
341 3
        return $tree;
342
    }
343
344
    /**
345
     * @param string $nowDir
346
     */
347 3
    private function getFileList($nowDir)
348
    {
349 3
        $topDir = $this->getuserDataDir();
350 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
351 3
            $acceptPath = realpath($topDir);
352 3
            $targetPath = $file->getRealPath();
353
354 3
            return strpos($targetPath, $acceptPath) === 0;
355 3
        };
356
357 3
        $finder = Finder::create()
358 3
            ->filter($filter)
359 3
            ->in($nowDir)
360 3
            ->sortByName()
361 3
            ->depth(0);
362 3
        $dirFinder = $finder->directories();
363
        try {
364 3
            $dirs = $dirFinder->getIterator();
365
        } catch (\Exception $e) {
366
            $dirs = [];
367
        }
368
369 3
        $fileFinder = $finder->files();
370
        try {
371 3
            $files = $fileFinder->getIterator();
372
        } catch (\Exception $e) {
373
            $files = [];
374
        }
375
376 3
        $arrFileList = [];
377 3
        foreach ($dirs as $dir) {
378 1
            $dirPath = $this->normalizePath($dir->getRealPath());
379 1
            $childDir = Finder::create()
380 1
                ->in($dirPath)
381 1
                ->directories()
382 1
                ->depth(0);
383 1
            $childFile = Finder::create()
384 1
                ->in($dirPath)
385 1
                ->files()
386 1
                ->depth(0);
387 1
            $countNumber = $childDir->count() + $childFile->count();
388 1
            $arrFileList[] = [
389 1
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
390 1
                'file_path' => $this->convertStrFromServer($this->getJailDir($dirPath)),
391 1
                'file_size' => FilesystemUtil::sizeToHumanReadable($dir->getSize()),
392 1
                'file_time' => $dir->getmTime(),
393
                'is_dir' => true,
394 1
                'is_empty' => $countNumber == 0 ? true : false,
395
            ];
396
        }
397 3
        foreach ($files as $file) {
398 3
            $arrFileList[] = [
399 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
400 3
                'file_path' => $this->convertStrFromServer($this->getJailDir($this->normalizePath($file->getRealPath()))),
401 3
                'file_size' => FilesystemUtil::sizeToHumanReadable($file->getSize()),
402 3
                'file_time' => $file->getmTime(),
403
                'is_dir' => false,
404
                'is_empty' => false,
405 3
                'extension' => $file->getExtension(),
406
            ];
407
        }
408
409 3
        return $arrFileList;
410
    }
411
412 3
    protected function normalizePath($path)
413
    {
414 3
        return str_replace('\\', '/', realpath($path));
415
    }
416
417
    /**
418
     * @param string $topDir
419
     */
420 6
    protected function checkDir($targetDir, $topDir)
421
    {
422 6
        $targetDir = realpath($targetDir);
423 6
        $topDir = realpath($topDir);
424
425 6
        return strpos($targetDir, $topDir) === 0;
426
    }
427
428
    /**
429
     * @return string
430
     */
431 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...
432
    {
433 3
        if ($this->encode == self::SJIS) {
434
            return mb_convert_encoding($target, self::UTF, self::SJIS);
435
        }
436
437 3
        return $target;
438
    }
439
440 4 View Code Duplication
    private function convertStrToServer($target)
441
    {
442 4
        if ($this->encode == self::SJIS) {
443
            return mb_convert_encoding($target, self::SJIS, self::UTF);
444
        }
445
446 4
        return $target;
447
    }
448
449 6
    private function getUserDataDir($nowDir = null)
450
    {
451 6
        return rtrim($this->getParameter('kernel.project_dir').'/html/user_data'.$nowDir, '/');
452
    }
453
454 3
    private function getJailDir($path)
455
    {
456 3
        $realpath = realpath($path);
457 3
        $jailPath = str_replace(realpath($this->getUserDataDir()), '', $realpath);
458
459 3
        return $jailPath ? $jailPath : '/';
460
    }
461
}
462