Completed
Pull Request — master (#2025)
by
unknown
69:10 queued 34:42
created

FileController::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2.0625
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 6
    public function __construct(){
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
43 6
        $this->encode = self::UTF;
44 6
        if ('\\' === DIRECTORY_SEPARATOR) {
45
            $this->encode = self::SJIS;
46
        }
47
    }
48
49 3
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
50
    {
51 3
        $form = $app['form.factory']->createBuilder('form')
52 3
            ->add('file', 'file')
53 3
            ->add('create_file', 'text')
54 3
            ->getForm();
55
56
        // user_data_dir
57 3
        $topDir = $this->normalizePath($app['config']['user_data_realdir']);
58
        // user_data_dirの親ディレクトリ
59 3
        $htmlDir = $this->normalizePath($topDir.'/../');
60
        // カレントディレクトリ
61 3
        $nowDir = $this->checkDir($request->get('tree_select_file'), $topDir)
62
            ? $this->normalizePath($request->get('tree_select_file'))
63 3
            : $topDir;
64
        // パンくず表示用データ
65 3
        $nowDirList = json_encode(explode('/', trim(str_replace($htmlDir, '', $nowDir), '/')));
66
67 3
        $isTopDir = ($topDir === $nowDir);
68 3
        $parentDir = substr($nowDir, 0, strrpos($nowDir, '/'));
69
70 3
        if ('POST' === $request->getMethod()) {
71 2
            switch ($request->get('mode')) {
72 2
                case 'create':
73 1
                    $this->create($app, $request);
74 1
                    break;
75 1
                case 'upload':
76 1
                    $this->upload($app, $request);
77 1
                    break;
78
                default:
79 2
                    break;
80
            }
81
        }
82
83 3
        $tree = $this->getTree($topDir, $request);
84 3
        $arrFileList = $this->getFileList($app, $nowDir);
85
86 3
        $javascript = $this->getJsArrayList($tree);
87 3
        $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...
88
89 3
        return $app->render('Content/file.twig', array(
90 3
            'form' => $form->createView(),
91 3
            'tpl_onload' => $onload,
92 3
            'tpl_javascript' => $javascript,
93 3
            'top_dir' => $topDir,
94 3
            'tpl_is_top_dir' => $isTopDir,
95 3
            'tpl_now_dir' => $nowDir,
96 3
            'html_dir' => $htmlDir,
97 3
            'now_dir_list' => $nowDirList,
98 3
            'tpl_parent_dir' => $parentDir,
99 3
            'arrFileList' => $arrFileList,
100 3
            'error' => $this->error,
101
        ));
102
    }
103
104 1
    public function view(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
105
    {
106 1
        $topDir = $app['config']['user_data_realdir'];
107 1
        if ($this->checkDir($this->convertStrToServer($request->get('file')), $topDir)) {
108 1
            $file = $this->convertStrToServer($request->get('file'));
109 1
            setlocale(LC_ALL, "ja_JP.UTF-8");
110 1
            return $app->sendFile($file);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
111
        }
112
113
        throw new NotFoundHttpException();
114
    }
115
116 1
    public function create(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
117
    {
118
119 1
        $form = $app['form.factory']->createBuilder('form')
120 1
            ->add('file', 'file')
121 1
            ->add('create_file', 'text')
122 1
            ->getForm();
123
124 1
        $form->handleRequest($request);
125
126 1
        if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
127
128 1
            $fs = new Filesystem();
129 1
            $filename = $form->get('create_file')->getData();
130
131 1
            $pattern = "/[^[:alnum:]_.\\-]/";
132 1
            $pattern2 = "/^\.(.*)$/";
133 1
            if (empty($filename)) {
134
                $this->error = array('message' => 'フォルダ作成名が入力されていません。');
135 1
            } elseif (strlen($filename) > 0 && preg_match($pattern, $filename)) {
136
                $this->error = array('message' => 'フォルダ名には、英数字、記号(_ - .)のみを入力して下さい。');
137 1
            } elseif (strlen($filename) > 0 && preg_match($pattern2, $filename)) {
138
                $this->error = array('message' => '.から始まるフォルダ名は作成できません。');
139
            } else {
140 1
                $topDir = $app['config']['user_data_realdir'];
141 1
                $nowDir = $this->checkDir($request->get('now_dir'), $topDir)
142
                    ? $this->normalizePath($request->get('now_dir'))
143 1
                    : $topDir;
144 1
                $fs->mkdir($nowDir . '/' . $filename);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
145
            }
146
        }
147
148 1
        return $app->redirect($app->url('admin_content_file'));
149
    }
150
151 1
    public function delete(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
152
    {
153
154 1
        $this->isTokenValid($app);
155
156 1
        $topDir = $app['config']['user_data_realdir'];
157 1
        if ($this->checkDir($this->convertStrToServer($request->get('select_file')), $topDir)) {
158 1
            $fs = new Filesystem();
159 1
            if ($fs->exists($this->convertStrToServer($request->get('select_file')))) {
160 1
                $fs->remove($this->convertStrToServer($request->get('select_file')));
161
            }
162
        }
163
164 1
        return $app->redirect($app->url('admin_content_file'));
165
    }
166
167 1
    public function download(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
168
    {
169 1
        $topDir = $app['config']['user_data_realdir'];
170 1
        $file = $this->convertStrToServer($request->get('select_file'));
171 1
        if ($this->checkDir($file, $topDir)) {
172 1
            if (!is_dir($file)) {
173 1
                $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...
174 1
                setlocale(LC_ALL, 'ja_JP.UTF-8');
175 1
                $pathParts = pathinfo($file);
176
177
                $patterns = array(
178 1
                    '/[a-zA-Z0-9!"#$%&()=~^|@`:*;+{}]/',
179
                    '/[- ,.<>?_[\]\/\\\\]/',
180
                    "/['\r\n\t\v\f]/",
181
                );
182
183 1
                $str = preg_replace($patterns, '', $pathParts['basename']);
184 1
                if (strlen($str) === 0) {
185 1
                    return $app->sendFile($file)->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
186
                } else {
187
                    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...
188
                        "Content-Type" => "aplication/octet-stream;",
189
                        "Content-Disposition" => "attachment; filename*=UTF-8\'\'".rawurlencode($this->convertStrFromServer($pathParts['basename']))
190
                    ));
191
                }
192
            }
193
        }
194
        throw new NotFoundHttpException();
195
    }
196
197 1
    public function upload(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
198
    {
199 1
        $form = $app['form.factory']->createBuilder('form')
200 1
            ->add('file', 'file')
201 1
            ->add('create_file', 'text')
202 1
            ->getForm();
203
204 1
        $form->handleRequest($request);
205
206 1
        if ($form->isValid()) {
207 1
            $data = $form->getData();
208 1
            if (empty($data['file'])) {
209
                $this->error = array('message' => 'ファイルが選択されていません。');
210
            } else {
211 1
                $topDir = $app['config']['user_data_realdir'];
212 1
                if ($this->checkDir($request->get('now_dir'), $topDir)) {
213 1
                    $filename = $this->convertStrToServer($data['file']->getClientOriginalName());
214 1
                    $data['file']->move($request->get('now_dir'), $filename);
215
                }
216
            }
217
        }
218
    }
219
220 3
    private function getJsArrayList($tree)
221
    {
222 3
        $str = "arrTree = new Array();\n";
223 3
        foreach ($tree as $key => $val) {
224 3
            $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...
225 3
            if ($val['open']) {
226 3
                $str .= "true);\n";
227
            } else {
228 3
                $str .= "false);\n";
229
            }
230
        }
231
232 3
        return $str;
233
    }
234
235 3
    private function getTree($topDir, $request)
236
    {
237 3
        $finder = Finder::create()->in($topDir)
238 3
            ->directories()
239 3
            ->sortByName();
240
241 3
        $tree = array();
242 3
        $tree[] = array(
243 3
            'path' => $topDir,
244 3
            'type' => '_parent',
245 3
            'rank' => 0,
246
            'open' => true,
247
        );
248
249 3
        $defaultRank = count(explode('/', $topDir));
250
251 3
        $openDirs = array();
252 3
        if ($request->get('tree_status')) {
253
            $openDirs = explode('|', $request->get('tree_status'));
254
        }
255
256 3
        foreach ($finder as $dirs) {
257 1
            $path = $this->normalizePath($dirs->getRealPath());
258 1
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
259 1
            $rank = count(explode('/', $path)) - $defaultRank;
260
261 1
            $tree[] = array(
262 3
                'path' => $path,
263 1
                'type' => $type,
264 1
                'rank' => $rank,
265 1
                'open' => (in_array($path, $openDirs)) ? true : false,
266
            );
267
        }
268
269 3
        return $tree;
270
    }
271
272 3
    private function getFileList($app, $nowDir)
273
    {
274 3
        $topDir = $app['config']['user_data_realdir'];
275 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
276 2
            $acceptPath = realpath($topDir);
277 2
            $targetPath = $file->getRealPath();
278 2
            return (strpos($targetPath, $acceptPath) === 0);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
279 3
        };
280
281 3
        $dirFinder = Finder::create()
282 3
            ->filter($filter)
283 3
            ->in($nowDir)
284 3
            ->directories()
285 3
            ->sortByName()
286 3
            ->depth(0);
287 3
        $fileFinder = Finder::create()
288 3
            ->filter($filter)
289 3
            ->in($nowDir)
290 3
            ->files()
291 3
            ->sortByName()
292 3
            ->depth(0);
293 3
        $dirs = iterator_to_array($dirFinder);
294 3
        $files = iterator_to_array($fileFinder);
295
296 3
        $arrFileList = array();
297 3 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...
298 1
            $arrFileList[] = array(
299 3
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
300 1
                'file_path' => $this->convertStrFromServer($this->normalizePath($dir->getRealPath())),
301 1
                'file_size' => $dir->getSize(),
302 1
                'file_time' => date("Y/m/d", $dir->getmTime()),
303
                'is_dir' => true,
304
            );
305
        }
306 3 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...
307 1
            $arrFileList[] = array(
308 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
309 1
                'file_path' => $this->convertStrFromServer($this->normalizePath($file->getRealPath())),
310 1
                'file_size' => $file->getSize(),
311 1
                'file_time' => date("Y/m/d", $file->getmTime()),
312
                'is_dir' => false,
313
            );
314
        }
315
316 3
        return $arrFileList;
317
    }
318
319 3
    protected function normalizePath($path)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
320
    {
321 3
        return str_replace('\\', '/', realpath($path));
322
    }
323
324 6
    protected function checkDir($targetDir, $topDir)
325
    {
326 6
        $targetDir = realpath($targetDir);
327 6
        $topDir = realpath($topDir);
328 6
        return (strpos($targetDir, $topDir) === 0);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
329
    }
330
331 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...
332
    {
333 3
        if ($this->encode == self::SJIS) {
334
            return mb_convert_encoding($target, self::UTF, self::SJIS);
335
        }
336 3
        return $target;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
337
    }
338
339 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...
340
    {
341 4
        if ($this->encode == self::SJIS) {
342
            return mb_convert_encoding($target, self::SJIS, self::UTF);
343
        }
344 4
        return $target;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
345
    }
346
}
347