FileController::convertStrFromServer()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %
Metric Value
dl 7
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Admin\Content;
26
27
use Eccube\Application;
28
use Eccube\Controller\AbstractController;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\Filesystem\Filesystem;
31
use Symfony\Component\Finder\Finder;
32
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
33
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
34
35
class FileController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
36
{
37
    const SJIS = 'sjis-win';
38
    const UTF = 'UTF-8';
39
    private $error = null;
40
    private $encode = '';
41
42
    public function __construct(){
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
43
        $this->encode = self::UTF;
44
        if ('\\' === DIRECTORY_SEPARATOR) {
45
            $this->encode = self::SJIS;
46
        }
47
    }
48
49
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
50
    {
51
        $form = $app['form.factory']->createBuilder('form')
52
            ->add('file', 'file')
53
            ->add('create_file', 'text')
54
            ->getForm();
55
56
        // user_data_dir
57
        $topDir = $this->normalizePath($app['config']['user_data_realdir']);
58
        // user_data_dirの親ディレクトリ
59
        $htmlDir = $this->normalizePath($topDir.'/../');
60
        // カレントディレクトリ
61
        $nowDir = $this->checkDir($request->get('tree_select_file'), $topDir)
62
            ? $this->normalizePath($request->get('tree_select_file'))
63
            : $topDir;
64
        // パンくず表示用データ
65
        $nowDirList = json_encode(explode('/', trim(str_replace($htmlDir, '', $nowDir), '/')));
66
67
        $isTopDir = ($topDir === $nowDir);
68
        $parentDir = substr($nowDir, 0, strrpos($nowDir, '/'));
69
70
        switch ($request->get('mode')) {
71
            case 'create':
72
                $this->create($app, $request);
73
                break;
74
            case 'upload':
75
                $this->upload($app, $request);
76
                break;
77
            default:
78
                break;
79
        }
80
81
        $tree = $this->getTree($topDir, $request);
82
        $arrFileList = $this->getFileList($app, $nowDir);
83
84
        $javascript = $this->getJsArrayList($tree);
85
        $onload = "eccube.fileManager.viewFileTree('tree', arrTree, '" . $nowDir . "', 'tree_select_file', 'tree_status', 'move');";
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
86
87
        return $app->render('Content/file.twig', array(
88
            'form' => $form->createView(),
89
            'tpl_onload' => $onload,
90
            'tpl_javascript' => $javascript,
91
            'top_dir' => $topDir,
92
            'tpl_is_top_dir' => $isTopDir,
93
            'tpl_now_dir' => $nowDir,
94
            'html_dir' => $htmlDir,
95
            'now_dir_list' => $nowDirList,
96
            'tpl_parent_dir' => $parentDir,
97
            'arrFileList' => $arrFileList,
98
            'error' => $this->error,
99
        ));
100
    }
101
102
    public function view(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
103
    {
104
        $topDir = $app['config']['user_data_realdir'];
105
        if ($this->checkDir($this->convertStrToServer($request->get('file')), $topDir)) {
106
            $file = $this->convertStrToServer($request->get('file'));
107
            setlocale(LC_ALL, "ja_JP.UTF-8");
108
            return $app->sendFile($file);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
109
        }
110
111
        throw new NotFoundHttpException();
112
    }
113
114
    public function create(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
115
    {
116
117
        $form = $app['form.factory']->createBuilder('form')
118
            ->add('file', 'file')
119
            ->add('create_file', 'text')
120
            ->getForm();
121
122
        $form->handleRequest($request);
123
124
        if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
125
126
            $fs = new Filesystem();
127
            $filename = $form->get('create_file')->getData();
128
129
            $pattern = "/[^[:alnum:]_.\\-]/";
130
            $pattern2 = "/^\.(.*)$/";
131
            if (empty($filename)) {
132
                $this->error = array('message' => 'フォルダ作成名が入力されていません。');
133
            } elseif (strlen($filename) > 0 && preg_match($pattern, $filename)) {
134
                $this->error = array('message' => 'フォルダ名には、英数字、記号(_ - .)のみを入力して下さい。');
135
            } elseif (strlen($filename) > 0 && preg_match($pattern2, $filename)) {
136
                $this->error = array('message' => '.から始まるフォルダ名は作成できません。');
137
            } else {
138
                $topDir = $app['config']['user_data_realdir'];
139
                $nowDir = $this->checkDir($request->get('now_dir'), $topDir)
140
                    ? $this->normalizePath($request->get('now_dir'))
141
                    : $topDir;
142
                $fs->mkdir($nowDir . '/' . $filename);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
143
            }
144
        }
145
146
        return $app->redirect($app->url('admin_content_file'));
147
    }
148
149
    public function delete(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
150
    {
151
152
        $this->isTokenValid($app);
153
154
        $topDir = $app['config']['user_data_realdir'];
155
        if ($this->checkDir($this->convertStrToServer($request->get('select_file')), $topDir)) {
156
            $fs = new Filesystem();
157
            if ($fs->exists($this->convertStrToServer($request->get('select_file')))) {
158
                $fs->remove($this->convertStrToServer($request->get('select_file')));
159
            }
160
        }
161
162
        return $app->redirect($app->url('admin_content_file'));
163
    }
164
165
    public function download(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
166
    {
167
        $topDir = $app['config']['user_data_realdir'];
168
        $file = $this->convertStrToServer($request->get('select_file'));
169
        if ($this->checkDir($file, $topDir)) {
170
            if (!is_dir($file)) {
171
                $filename = $this->convertStrFromServer($file);
0 ignored issues
show
Unused Code introduced by
$filename is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
172
                setlocale(LC_ALL, 'ja_JP.UTF-8');
173
                $pathParts = pathinfo($file);
174
175
                $patterns = array(
176
                    '/[a-zA-Z0-9!"#$%&()=~^|@`:*;+{}]/',
177
                    '/[- ,.<>?_[\]\/\\\\]/',
178
                    "/['\r\n\t\v\f]/",
179
                );
180
181
                $str = preg_replace($patterns, '', $pathParts['basename']);
182
                if (strlen($str) === 0) {
183
                    return $app->sendFile($file)->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
184
                } else {
185
                    return $app->sendFile($file, 200, array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
186
                        "Content-Type" => "aplication/octet-stream;",
187
                        "Content-Disposition" => "attachment; filename*=UTF-8\'\'".rawurlencode($this->convertStrFromServer($pathParts['basename']))
188
                    ));
189
                }
190
            }
191
        }
192
        throw new NotFoundHttpException();
193
    }
194
195
    public function upload(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
196
    {
197
        $form = $app['form.factory']->createBuilder('form')
198
            ->add('file', 'file')
199
            ->add('create_file', 'text')
200
            ->getForm();
201
202
        $form->handleRequest($request);
203
204
        if ($form->isValid()) {
205
            $data = $form->getData();
206
            if (empty($data['file'])) {
207
                $this->error = array('message' => 'ファイルが選択されていません。');
208
            } else {
209
                $topDir = $app['config']['user_data_realdir'];
210
                if ($this->checkDir($request->get('now_dir'), $topDir)) {
211
                    $filename = $this->convertStrToServer($data['file']->getClientOriginalName());
212
                    $data['file']->move($request->get('now_dir'), $filename);
213
                }
214
            }
215
        }
216
    }
217
218
    private function getJsArrayList($tree)
219
    {
220
        $str = "arrTree = new Array();\n";
221
        foreach ($tree as $key => $val) {
222
            $str .= 'arrTree[' . $key . "] = new Array(" . $key . ", '" . $val['type'] . "', '" . $val['path'] . "', " . $val['rank'] . ',';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
223
            if ($val['open']) {
224
                $str .= "true);\n";
225
            } else {
226
                $str .= "false);\n";
227
            }
228
        }
229
230
        return $str;
231
    }
232
233
    private function getTree($topDir, $request)
234
    {
235
        $finder = Finder::create()->in($topDir)
236
            ->directories()
237
            ->sortByName();
238
239
        $tree = array();
240
        $tree[] = array(
241
            'path' => $topDir,
242
            'type' => '_parent',
243
            'rank' => 0,
244
            'open' => true,
245
        );
246
247
        $defaultRank = count(explode('/', $topDir));
248
249
        $openDirs = array();
250
        if ($request->get('tree_status')) {
251
            $openDirs = explode('|', $request->get('tree_status'));
252
        }
253
254
        foreach ($finder as $dirs) {
255
            $path = $this->normalizePath($dirs->getRealPath());
256
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
257
            $rank = count(explode('/', $path)) - $defaultRank;
258
259
            $tree[] = array(
260
                'path' => $path,
261
                'type' => $type,
262
                'rank' => $rank,
263
                'open' => (in_array($path, $openDirs)) ? true : false,
264
            );
265
        }
266
267
        return $tree;
268
    }
269
270
    private function getFileList($app, $nowDir)
271
    {
272
        $topDir = $app['config']['user_data_realdir'];
273
        $filter = function (\SplFileInfo $file) use ($topDir) {
274
            $acceptPath = realpath($topDir);
275
            $targetPath = $file->getRealPath();
276
            return (strpos($targetPath, $acceptPath) === 0);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
277
        };
278
279
        $dirFinder = Finder::create()
280
            ->filter($filter)
281
            ->in($nowDir)
282
            ->directories()
283
            ->sortByName()
284
            ->depth(0);
285
        $fileFinder = Finder::create()
286
            ->filter($filter)
287
            ->in($nowDir)
288
            ->files()
289
            ->sortByName()
290
            ->depth(0);
291
        $dirs = iterator_to_array($dirFinder);
292
        $files = iterator_to_array($fileFinder);
293
294
        $arrFileList = array();
295 View Code Duplication
        foreach ($dirs as $dir) {
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...
296
            $arrFileList[] = array(
297
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
298
                'file_path' => $this->convertStrFromServer($this->normalizePath($dir->getRealPath())),
299
                'file_size' => $dir->getSize(),
300
                'file_time' => date("Y/m/d", $dir->getmTime()),
301
                'is_dir' => true,
302
            );
303
        }
304 View Code Duplication
        foreach ($files as $file) {
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...
305
            $arrFileList[] = array(
306
                'file_name' => $this->convertStrFromServer($file->getFilename()),
307
                'file_path' => $this->convertStrFromServer($this->normalizePath($file->getRealPath())),
308
                'file_size' => $file->getSize(),
309
                'file_time' => date("Y/m/d", $file->getmTime()),
310
                'is_dir' => false,
311
            );
312
        }
313
314
        return $arrFileList;
315
    }
316
317
    protected function normalizePath($path)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
318
    {
319
        return str_replace('\\', '/', realpath($path));
320
    }
321
322
    protected function checkDir($targetDir, $topDir)
323
    {
324
        $targetDir = realpath($targetDir);
325
        $topDir = realpath($topDir);
326
        return (strpos($targetDir, $topDir) === 0);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
327
    }
328
329 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...
330
    {
331
        if ($this->encode == self::SJIS) {
332
            return mb_convert_encoding($target, self::UTF, self::SJIS);
333
        }
334
        return $target;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
335
    }
336
337 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...
338
    {
339
        if ($this->encode == self::SJIS) {
340
            return mb_convert_encoding($target, self::SJIS, self::UTF);
341
        }
342
        return $target;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
343
    }
344
}
345