Failed Conditions
Push — master ( fc54b8...947180 )
by Yangsin
124:44 queued 119:37
created

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

Severity

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
 * 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
36
{
37
    const SJIS = 'sjis-win';
38
    const UTF = 'UTF-8';
39
    private $error = null;
40
    private $encode = '';
41
42 6
    public function __construct(){
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)
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
        switch ($request->get('mode')) {
71 3
            case 'create':
72 1
                $this->create($app, $request);
73 1
                break;
74 2
            case 'upload':
75 1
                $this->upload($app, $request);
76 1
                break;
77
            default:
78 3
                break;
79
        }
80
81 3
        $tree = $this->getTree($topDir, $request);
82 3
        $arrFileList = $this->getFileList($app, $nowDir);
83
84 3
        $javascript = $this->getJsArrayList($tree);
85 3
        $onload = "eccube.fileManager.viewFileTree('tree', arrTree, '" . $nowDir . "', 'tree_select_file', 'tree_status', 'move');";
86
87 3
        return $app->render('Content/file.twig', array(
88 3
            'form' => $form->createView(),
89 3
            'tpl_onload' => $onload,
90 3
            'tpl_javascript' => $javascript,
91 3
            'top_dir' => $topDir,
92 3
            'tpl_is_top_dir' => $isTopDir,
93 3
            'tpl_now_dir' => $nowDir,
94 3
            'html_dir' => $htmlDir,
95 3
            'now_dir_list' => $nowDirList,
96 3
            'tpl_parent_dir' => $parentDir,
97 3
            'arrFileList' => $arrFileList,
98 3
            'error' => $this->error,
99
        ));
100
    }
101
102 1
    public function view(Application $app, Request $request)
103
    {
104 1
        $topDir = $app['config']['user_data_realdir'];
105 1
        if ($this->checkDir($this->convertStrToServer($request->get('file')), $topDir)) {
106 1
            $file = $this->convertStrToServer($request->get('file'));
107 1
            setlocale(LC_ALL, "ja_JP.UTF-8");
108 1
            return $app->sendFile($file);
109
        }
110
111
        throw new NotFoundHttpException();
112
    }
113
114 1
    public function create(Application $app, Request $request)
115
    {
116
117 1
        $form = $app['form.factory']->createBuilder('form')
118 1
            ->add('file', 'file')
119 1
            ->add('create_file', 'text')
120 1
            ->getForm();
121
122 1
        $form->handleRequest($request);
123
124 1
        if ($form->isValid()) {
125
126 1
            $fs = new Filesystem();
127 1
            $filename = $form->get('create_file')->getData();
128
129 1
            $pattern = "/[^[:alnum:]_.\\-]/";
130 1
            $pattern2 = "/^\.(.*)$/";
131 1
            if (empty($filename)) {
132
                $this->error = array('message' => 'フォルダ作成名が入力されていません。');
133 1
            } elseif (strlen($filename) > 0 && preg_match($pattern, $filename)) {
134
                $this->error = array('message' => 'フォルダ名には、英数字、記号(_ - .)のみを入力して下さい。');
135 1
            } elseif (strlen($filename) > 0 && preg_match($pattern2, $filename)) {
136
                $this->error = array('message' => '.から始まるフォルダ名は作成できません。');
137
            } else {
138 1
                $topDir = $app['config']['user_data_realdir'];
139 1
                $nowDir = $this->checkDir($request->get('now_dir'), $topDir)
140
                    ? $this->normalizePath($request->get('now_dir'))
141 1
                    : $topDir;
142 1
                $fs->mkdir($nowDir . '/' . $filename);
143
            }
144
        }
145
146 1
        return $app->redirect($app->url('admin_content_file'));
147
    }
148
149 1
    public function delete(Application $app, Request $request)
150
    {
151
152 1
        $this->isTokenValid($app);
153
154 1
        $topDir = $app['config']['user_data_realdir'];
155 1
        if ($this->checkDir($this->convertStrToServer($request->get('select_file')), $topDir)) {
156 1
            $fs = new Filesystem();
157 1
            if ($fs->exists($this->convertStrToServer($request->get('select_file')))) {
158 1
                $fs->remove($this->convertStrToServer($request->get('select_file')));
159
            }
160
        }
161
162 1
        return $app->redirect($app->url('admin_content_file'));
163
    }
164
165 1
    public function download(Application $app, Request $request)
166
    {
167 1
        $topDir = $app['config']['user_data_realdir'];
168 1
        $file = $this->convertStrToServer($request->get('select_file'));
169 1
        if ($this->checkDir($file, $topDir)) {
170 1
            if (!is_dir($file)) {
171 1
                $filename = $this->convertStrFromServer($file);
0 ignored issues
show
$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 1
                setlocale(LC_ALL, 'ja_JP.UTF-8');
173 1
                $pathParts = pathinfo($file);
174
175
                $patterns = array(
176 1
                    '/[a-zA-Z0-9!"#$%&()=~^|@`:*;+{}]/',
177
                    '/[- ,.<>?_[\]\/\\\\]/',
178
                    "/['\r\n\t\v\f]/",
179
                );
180
181 1
                $str = preg_replace($patterns, '', $pathParts['basename']);
182 1
                if (strlen($str) === 0) {
183 1
                    return $app->sendFile($file)->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
184
                } else {
185
                    return $app->sendFile($file, 200, array(
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 1
    public function upload(Application $app, Request $request)
196
    {
197 1
        $form = $app['form.factory']->createBuilder('form')
198 1
            ->add('file', 'file')
199 1
            ->add('create_file', 'text')
200 1
            ->getForm();
201
202 1
        $form->handleRequest($request);
203
204 1
        if ($form->isValid()) {
205 1
            $data = $form->getData();
206 1
            if (empty($data['file'])) {
207
                $this->error = array('message' => 'ファイルが選択されていません。');
208
            } else {
209 1
                $topDir = $app['config']['user_data_realdir'];
210 1
                if ($this->checkDir($request->get('now_dir'), $topDir)) {
211 1
                    $filename = $this->convertStrToServer($data['file']->getClientOriginalName());
212 1
                    $data['file']->move($request->get('now_dir'), $filename);
213
                }
214
            }
215
        }
216
    }
217
218 3
    private function getJsArrayList($tree)
219
    {
220 3
        $str = "arrTree = new Array();\n";
221 3
        foreach ($tree as $key => $val) {
222 3
            $str .= 'arrTree[' . $key . "] = new Array(" . $key . ", '" . $val['type'] . "', '" . $val['path'] . "', " . $val['rank'] . ',';
223 3
            if ($val['open']) {
224 3
                $str .= "true);\n";
225
            } else {
226 3
                $str .= "false);\n";
227
            }
228
        }
229
230 3
        return $str;
231
    }
232
233 3
    private function getTree($topDir, $request)
234
    {
235 3
        $finder = Finder::create()->in($topDir)
236 3
            ->directories()
237 3
            ->sortByName();
238
239 3
        $tree = array();
240 3
        $tree[] = array(
241 3
            'path' => $topDir,
242 3
            'type' => '_parent',
243 3
            'rank' => 0,
244
            'open' => true,
245
        );
246
247 3
        $defaultRank = count(explode('/', $topDir));
248
249 3
        $openDirs = array();
250 3
        if ($request->get('tree_status')) {
251
            $openDirs = explode('|', $request->get('tree_status'));
252
        }
253
254 3
        foreach ($finder as $dirs) {
255 1
            $path = $this->normalizePath($dirs->getRealPath());
256 1
            $type = (iterator_count(Finder::create()->in($path)->directories())) ? '_parent' : '_child';
257 1
            $rank = count(explode('/', $path)) - $defaultRank;
258
259 1
            $tree[] = array(
260 3
                'path' => $path,
261 1
                'type' => $type,
262 1
                'rank' => $rank,
263 1
                'open' => (in_array($path, $openDirs)) ? true : false,
264
            );
265
        }
266
267 3
        return $tree;
268
    }
269
270 3
    private function getFileList($app, $nowDir)
271
    {
272 3
        $topDir = $app['config']['user_data_realdir'];
273 3
        $filter = function (\SplFileInfo $file) use ($topDir) {
274 2
            $acceptPath = realpath($topDir);
275 2
            $targetPath = $file->getRealPath();
276 2
            return (strpos($targetPath, $acceptPath) === 0);
277 3
        };
278
279 3
        $dirFinder = Finder::create()
280 3
            ->filter($filter)
281 3
            ->in($nowDir)
282 3
            ->directories()
283 3
            ->sortByName()
284 3
            ->depth(0);
285 3
        $fileFinder = Finder::create()
286 3
            ->filter($filter)
287 3
            ->in($nowDir)
288 3
            ->files()
289 3
            ->sortByName()
290 3
            ->depth(0);
291 3
        $dirs = iterator_to_array($dirFinder);
292 3
        $files = iterator_to_array($fileFinder);
293
294 3
        $arrFileList = array();
295 3 View Code Duplication
        foreach ($dirs as $dir) {
296 1
            $arrFileList[] = array(
297 3
                'file_name' => $this->convertStrFromServer($dir->getFilename()),
298 1
                'file_path' => $this->convertStrFromServer($this->normalizePath($dir->getRealPath())),
299 1
                'file_size' => $dir->getSize(),
300 1
                'file_time' => date("Y/m/d", $dir->getmTime()),
301
                'is_dir' => true,
302
            );
303
        }
304 3 View Code Duplication
        foreach ($files as $file) {
305 1
            $arrFileList[] = array(
306 3
                'file_name' => $this->convertStrFromServer($file->getFilename()),
307 1
                'file_path' => $this->convertStrFromServer($this->normalizePath($file->getRealPath())),
308 1
                'file_size' => $file->getSize(),
309 1
                'file_time' => date("Y/m/d", $file->getmTime()),
310
                'is_dir' => false,
311
            );
312
        }
313
314 3
        return $arrFileList;
315
    }
316
317 3
    protected function normalizePath($path)
318
    {
319 3
        return str_replace('\\', '/', realpath($path));
320
    }
321
322 6
    protected function checkDir($targetDir, $topDir)
323
    {
324 6
        $targetDir = realpath($targetDir);
325 6
        $topDir = realpath($topDir);
326 6
        return (strpos($targetDir, $topDir) === 0);
327
    }
328
329 3 View Code Duplication
    private function convertStrFromServer($target)
330
    {
331 3
        if ($this->encode == self::SJIS) {
332
            return mb_convert_encoding($target, self::UTF, self::SJIS);
333
        }
334 3
        return $target;
335
    }
336
337 4 View Code Duplication
    private function convertStrToServer($target)
338
    {
339 4
        if ($this->encode == self::SJIS) {
340
            return mb_convert_encoding($target, self::SJIS, self::UTF);
341
        }
342 4
        return $target;
343
    }
344
}
345