Passed
Branch master (f2d2e3)
by Michael
18:45
created

browser::getLangs()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 17
c 1
b 1
f 0
nc 3
nop 0
dl 0
loc 23
rs 9.0777
1
<?php
2
3
/** This file is part of KCFinder project
4
  *
5
  *      @desc Browser actions class
6
  *   @package KCFinder
7
  *   @version 3.12
8
  *    @author Pavel Tzonkov <[email protected]>
9
  * @copyright 2010-2014 KCFinder Project
10
  *   @license http://opensource.org/licenses/GPL-3.0 GPLv3
11
  *   @license http://opensource.org/licenses/LGPL-3.0 LGPLv3
12
  *      @link http://kcfinder.sunhater.com
13
  */
14
15
namespace kcfinder;
16
17
class browser extends uploader {
18
    protected $action;
19
    protected $thumbsDir;
20
    protected $thumbsTypeDir;
21
22
    public function __construct() {
23
        parent::__construct();
24
25
        // SECURITY CHECK INPUT DIRECTORY
26
        if (isset($_POST['dir'])) {
27
            $dir = $this->checkInputDir($_POST['dir'], true, false);
28
            if ($dir === false) unset($_POST['dir']);
29
            $_POST['dir'] = $dir;
30
        }
31
32
        if (isset($_GET['dir'])) {
33
            $dir = $this->checkInputDir($_GET['dir'], true, false);
34
            if ($dir === false) unset($_GET['dir']);
35
            $_GET['dir'] = $dir;
36
        }
37
38
        $thumbsDir = $this->config['uploadDir'] . "/" . $this->config['thumbsDir'];
39
        if (!$this->config['disabled'] &&
40
            (
41
                (
42
                    !is_dir($thumbsDir) &&
43
                    !@mkdir($thumbsDir, $this->config['dirPerms'])
44
                ) ||
45
46
                !is_readable($thumbsDir) ||
47
                !dir::isWritable($thumbsDir) ||
48
                (
49
                    !is_dir("$thumbsDir/{$this->type}") &&
50
                    !@mkdir("$thumbsDir/{$this->type}", $this->config['dirPerms'])
51
                )
52
            )
53
        )
54
            $this->errorMsg("Cannot access or create thumbnails folder.");
55
56
        $this->thumbsDir = $thumbsDir;
57
        $this->thumbsTypeDir = "$thumbsDir/{$this->type}";
58
59
        // Remove temporary zip downloads if exists
60
        if (!$this->config['disabled']) {
61
            $files = dir::content($this->config['uploadDir'], array(
62
                'types' => "file",
63
                'pattern' => '/^.*\.zip$/i'
64
            ));
65
66
            if (is_array($files) && count($files)) {
0 ignored issues
show
introduced by
The condition is_array($files) is always false.
Loading history...
67
                $time = time();
68
                foreach ($files as $file)
69
                    if (is_file($file) && ($time - filemtime($file) > 3600))
70
                        unlink($file);
71
            }
72
        }
73
74
        if (isset($_GET['theme']) &&
75
            $this->checkFilename($_GET['theme']) &&
76
            is_dir("themes/{$_GET['theme']}")
77
        )
78
            $this->config['theme'] = $_GET['theme'];
79
    }
80
81
    public function action() {
82
        $act = isset($_GET['act']) ? $_GET['act'] : "browser";
83
        if (!method_exists($this, "act_$act"))
84
            $act = "browser";
85
        $this->action = $act;
86
        $method = "act_$act";
87
88
        if ($this->config['disabled']) {
89
            $message = $this->label("You don't have permissions to browse server.");
90
            if (in_array($act, array("browser", "upload")) ||
91
                (substr($act, 0, 8) == "download")
92
            )
93
                $this->backMsg($message);
94
            else {
95
                header("Content-Type: text/plain; charset={$this->charset}");
96
                die(json_encode(array('error' => $message)));
97
            }
98
        }
99
100
        if (!isset($this->session['dir']))
101
            $this->session['dir'] = $this->type;
102
        else {
103
            $type = $this->getTypeFromPath($this->session['dir']);
104
            $dir = $this->config['uploadDir'] . "/" . $this->session['dir'];
105
            if (($type != $this->type) || !is_dir($dir) || !is_readable($dir))
106
                $this->session['dir'] = $this->type;
107
        }
108
        $this->session['dir'] = path::normalize($this->session['dir']);
109
110
        // Render the browser
111
        if ($act == "browser") {
112
            header("X-UA-Compatible: chrome=1");
113
            header("Content-Type: text/html; charset={$this->charset}");
114
115
        // Ajax requests
116
        } elseif (
117
            (substr($act, 0, 8) != "download") &&
118
            !in_array($act, array("thumb", "upload"))
119
        )
120
            header("Content-Type: text/plain; charset={$this->charset}");
121
122
        $return = $this->$method();
123
        echo ($return === true)
124
            ? '{}'
125
            : $return;
126
    }
127
128
    protected function act_browser() {
129
        if (isset($_GET['dir'])) {
130
            $dir = "{$this->typeDir}/{$_GET['dir']}";
131
            if ($this->checkFilePath($dir) && is_dir($dir) && is_readable($dir))
132
                $this->session['dir'] = path::normalize("{$this->type}/{$_GET['dir']}");
133
        }
134
        return $this->output();
135
    }
136
137
    protected function act_init() {
138
        $tree = $this->getDirInfo($this->typeDir);
139
        $tree['dirs'] = $this->getTree($this->session['dir']);
140
        if (!is_array($tree['dirs']) || !count($tree['dirs']))
141
            unset($tree['dirs']);
142
        $files = $this->getFiles($this->session['dir']);
143
        $dirWritable = dir::isWritable("{$this->config['uploadDir']}/{$this->session['dir']}");
144
        $data = array(
145
            'tree' => &$tree,
146
            'files' => &$files,
147
            'dirWritable' => $dirWritable
148
        );
149
        return json_encode($data);
150
    }
151
152
    protected function act_thumb() {
153
        if (!isset($_GET['file']) ||
154
            !isset($_GET['dir']) ||
155
            !$this->checkFilename($_GET['file'])
156
        )
157
            $this->sendDefaultThumb();
158
159
        $dir = $this->getDir();
160
        $file = "{$this->thumbsTypeDir}/{$_GET['dir']}/${_GET['file']}";
161
162
        // Create thumbnail
163
        if (!is_file($file) || !is_readable($file)) {
164
            $file = "$dir/{$_GET['file']}";
165
            if (!is_file($file) || !is_readable($file))
166
                $this->sendDefaultThumb($file);
167
            $image = image::factory($this->imageDriver, $file);
168
            if ($image->initError)
169
                $this->sendDefaultThumb($file);
170
171
            $img = new fastImage($file);
172
            $type = $img->getType();
173
            $img->close();
174
175
            if (in_array($type, array("gif", "jpeg", "png")) &&
176
                ($image->width <= $this->config['thumbWidth']) &&
177
                ($image->height <= $this->config['thumbHeight'])
178
            ) {
179
                $mime = "image/$type";
180
                httpCache::file($file, $mime);
181
            } else
182
                $this->sendDefaultThumb($file);
183
184
        // Get type from already-existing thumbnail
185
        } else {
186
            $img = new fastImage($file);
187
            $type = $img->getType();
188
            $img->close();
189
        }
190
        httpCache::file($file, "image/$type");
191
    }
192
193
    protected function act_expand() {
194
        return json_encode(array('dirs' => $this->getDirs($this->postDir())));
195
    }
196
197
    protected function act_chDir() {
198
        $this->postDir(); // Just for existing check
199
        $this->session['dir'] = "{$this->type}/{$_POST['dir']}";
200
        $dirWritable = dir::isWritable("{$this->config['uploadDir']}/{$this->session['dir']}");
201
        return json_encode(array(
202
            'files' => $this->getFiles($this->session['dir']),
203
            'dirWritable' => $dirWritable
204
        ));
205
    }
206
207
    protected function act_newDir() {
208
        if (!$this->config['access']['dirs']['create'] ||
209
            !isset($_POST['dir']) ||
210
            !isset($_POST['newDir']) ||
211
            !$this->checkFilename($_POST['newDir'])
212
        )
213
            $this->errorMsg("Unknown error.");
214
215
        $dir = $this->postDir();
216
        $newDir = $this->normalizeDirname(trim($_POST['newDir']));
217
        if (!strlen($newDir))
218
            $this->errorMsg("Please enter new folder name.");
219
        if (preg_match('/[\/\\\\]/s', $newDir))
220
            $this->errorMsg("Unallowable characters in folder name.");
221
        if (substr($newDir, 0, 1) == ".")
222
            $this->errorMsg("Folder name shouldn't begins with '.'");
223
        if (file_exists("$dir/$newDir"))
224
            $this->errorMsg("A file or folder with that name already exists.");
225
        if (!@mkdir("$dir/$newDir", $this->config['dirPerms']))
226
            $this->errorMsg("Cannot create {dir} folder.", array('dir' => $this->htmlData($newDir)));
227
        return true;
228
    }
229
230
    protected function act_renameDir() {
231
        if (!$this->config['access']['dirs']['rename'] ||
232
            !isset($_POST['dir']) ||
233
            !strlen(rtrim(rtrim(trim($_POST['dir']), "/"), "\\")) ||
234
            !isset($_POST['newName']) ||
235
            !$this->checkFilename($_POST['newName'])
236
        )
237
            $this->errorMsg("Unknown error.");
238
239
        $dir = $this->postDir();
240
        $newName = $this->normalizeDirname(trim($_POST['newName']));
241
        if (!strlen($newName))
242
            $this->errorMsg("Please enter new folder name.");
243
        if (preg_match('/[\/\\\\]/s', $newName))
244
            $this->errorMsg("Unallowable characters in folder name.");
245
        if (substr($newName, 0, 1) == ".")
246
            $this->errorMsg("Folder name shouldn't begins with '.'");
247
        if (!@rename($dir, dirname($dir) . "/$newName"))
248
            $this->errorMsg("Cannot rename the folder.");
249
        $thumbDir = "$this->thumbsTypeDir/{$_POST['dir']}";
250
        if (is_dir($thumbDir))
251
            @rename($thumbDir, dirname($thumbDir) . "/$newName");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

251
            /** @scrutinizer ignore-unhandled */ @rename($thumbDir, dirname($thumbDir) . "/$newName");

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
252
        return json_encode(array('name' => $newName));
253
    }
254
255
    protected function act_deleteDir() {
256
        if (!$this->config['access']['dirs']['delete'] ||
257
            !isset($_POST['dir']) ||
258
            !strlen(rtrim(rtrim(trim($_POST['dir']), "/"), "\\"))
259
        )
260
            $this->errorMsg("Unknown error.");
261
262
        $dir = $this->postDir();
263
264
        if (!dir::isWritable($dir))
265
            $this->errorMsg("Cannot delete the folder.");
266
        $result = !dir::prune($dir, false);
267
        if (is_array($result) && count($result))
0 ignored issues
show
introduced by
The condition is_array($result) is always false.
Loading history...
268
            $this->errorMsg("Failed to delete {count} files/folders.",
269
                array('count' => count($result)));
270
        $thumbDir = "$this->thumbsTypeDir/{$_POST['dir']}";
271
        if (is_dir($thumbDir)) dir::prune($thumbDir);
272
        return true;
273
    }
274
275
    protected function act_upload() {
276
        header("Content-Type: text/plain; charset={$this->charset}");
277
278
        if (!$this->config['access']['files']['upload'] ||
279
            (!isset($_POST['dir']) && !isset($_GET['dir']))
280
        )
281
            $this->errorMsg("Unknown error.");
282
283
        $dir = isset($_GET['dir']) ? $this->getDir() : $this->postDir();
284
285
        if (!dir::isWritable($dir))
286
            $this->errorMsg("Cannot access or write to upload folder.");
287
288
        if (is_array($this->file['name'])) {
289
            $return = array();
290
            foreach ($this->file['name'] as $i => $name) {
291
                $return[] = $this->moveUploadFile(array(
292
                    'name' => $name,
293
                    'tmp_name' => $this->file['tmp_name'][$i],
294
                    'error' => $this->file['error'][$i]
295
                ), $dir);
296
            }
297
            return implode("\n", $return);
298
        } else
299
            return $this->moveUploadFile($this->file, $dir);
300
    }
301
302
    protected function act_dragUrl() {
303
        if (!$this->config['access']['files']['upload'] ||
304
            !isset($_GET['dir']) ||
305
            !isset($_POST['url']) ||
306
            !isset($_POST['type'])
307
        )
308
            $this->errorMsg("Unknown error.");
309
310
        $dir = $this->getDir();
311
312
        if (!dir::isWritable($dir))
313
            $this->errorMsg("Cannot access or write to upload folder.");
314
315
        if (is_array($_POST['url']))
316
            foreach ($_POST['url'] as $url)
317
                $this->downloadURL($url, $dir);
318
        else
319
            $this->downloadURL($_POST['url'], $dir);
320
321
        return true;
322
    }
323
324
    protected function act_download() {
325
        $dir = $this->postDir();
326
        if (!isset($_POST['dir']) ||
327
            !isset($_POST['file']) ||
328
            !$this->checkFilename($_POST['file']) ||
329
            (false === ($file = "$dir/{$_POST['file']}")) ||
330
            !file_exists($file) || !is_readable($file)
331
        )
332
            $this->errorMsg("Unknown error.");
333
334
        header("Pragma: public");
335
        header("Expires: 0");
336
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
337
        header("Cache-Control: private", false);
338
        header("Content-Type: application/octet-stream");
339
        header('Content-Disposition: attachment; filename="' . str_replace('"', "_", $_POST['file']) . '"');
340
        header("Content-Transfer-Encoding: binary");
341
        header("Content-Length: " . filesize($file));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file does not seem to be defined for all execution paths leading up to this point.
Loading history...
342
        readfile($file);
343
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
344
    }
345
346
    protected function act_rename() {
347
        $dir = $this->postDir();
348
        if (!$this->config['access']['files']['rename'] ||
349
            !isset($_POST['dir']) ||
350
            !isset($_POST['file']) ||
351
            !isset($_POST['newName']) ||
352
            !$this->checkFilename($_POST['file']) ||
353
            !$this->checkFilename($_POST['newName']) ||
354
            (false === ($file = "$dir/{$_POST['file']}")) ||
355
            !file_exists($file) || !is_readable($file) || !file::isWritable($file)
356
        )
357
            $this->errorMsg("Unknown error.");
358
359
        if (isset($this->config['denyExtensionRename']) &&
360
            $this->config['denyExtensionRename'] &&
361
            (file::getExtension($_POST['file'], true) !==
362
                file::getExtension($_POST['newName'], true)
363
            )
364
        )
365
            $this->errorMsg("You cannot rename the extension of files!");
366
367
        $newName = $this->normalizeFilename(trim($_POST['newName']));
368
        if (!strlen($newName))
369
            $this->errorMsg("Please enter new file name.");
370
        if (preg_match('/[\/\\\\]/s', $newName))
371
            $this->errorMsg("Unallowable characters in file name.");
372
        if (substr($newName, 0, 1) == ".")
373
            $this->errorMsg("File name shouldn't begins with '.'");
374
        $newName = "$dir/$newName";
375
        if (file_exists($newName))
376
            $this->errorMsg("A file or folder with that name already exists.");
377
        $ext = file::getExtension($newName);
378
        if (!$this->validateExtension($ext, $this->type))
379
            $this->errorMsg("Denied file extension.");
380
        if (!@rename($file, $newName))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file does not seem to be defined for all execution paths leading up to this point.
Loading history...
381
            $this->errorMsg("Unknown error.");
382
383
        $thumbDir = "{$this->thumbsTypeDir}/{$_POST['dir']}";
384
        $thumbFile = "$thumbDir/{$_POST['file']}";
385
386
        if (file_exists($thumbFile))
387
            @rename($thumbFile, "$thumbDir/" . basename($newName));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

387
            /** @scrutinizer ignore-unhandled */ @rename($thumbFile, "$thumbDir/" . basename($newName));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
388
        return true;
389
    }
390
391
    protected function act_delete() {
392
        $dir = $this->postDir();
393
        if (!$this->config['access']['files']['delete'] ||
394
            !isset($_POST['dir']) ||
395
            !isset($_POST['file']) ||
396
            !$this->checkFilename($_POST['file']) ||
397
            (false === ($file = "$dir/{$_POST['file']}")) ||
398
            !file_exists($file) || !is_readable($file) || !file::isWritable($file) ||
399
            !@unlink($file)
400
        )
401
            $this->errorMsg("Unknown error.");
402
403
        $thumb = "{$this->thumbsTypeDir}/{$_POST['dir']}/{$_POST['file']}";
404
        if (file_exists($thumb)) @unlink($thumb);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

404
        if (file_exists($thumb)) /** @scrutinizer ignore-unhandled */ @unlink($thumb);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
405
        return true;
406
    }
407
408
    protected function act_cp_cbd() {
409
        $dir = $this->postDir();
410
        if (!$this->config['access']['files']['copy'] ||
411
            !isset($_POST['dir']) ||
412
            !is_dir($dir) || !is_readable($dir) || !dir::isWritable($dir) ||
413
            !isset($_POST['files']) || !is_array($_POST['files']) ||
414
            !count($_POST['files'])
415
        )
416
            $this->errorMsg("Unknown error.");
417
418
        $error = array();
419
        foreach($_POST['files'] as $file) {
420
            $file = path::normalize($file);
421
            if (substr($file, 0, 1) == ".") continue;
422
            $type = explode("/", $file);
423
            $type = $type[0];
424
            if ($type != $this->type) continue;
425
            $path = "{$this->config['uploadDir']}/$file";
426
            if (!$this->checkFilePath($path)) continue;
427
            $base = basename($file);
428
            $replace = array('file' => $this->htmlData($base));
429
            $ext = file::getExtension($base);
430
            if (!file_exists($path))
431
                $error[] = $this->label("The file '{file}' does not exist.", $replace);
432
            elseif (substr($base, 0, 1) == ".")
433
                $error[] = $this->htmlData($base) . ": " . $this->label("File name shouldn't begins with '.'");
434
            elseif (!$this->validateExtension($ext, $type))
435
                $error[] = $this->htmlData($base) . ": " . $this->label("Denied file extension.");
436
            elseif (file_exists("$dir/$base"))
437
                $error[] = $this->htmlData($base) . ": " . $this->label("A file or folder with that name already exists.");
438
            elseif (!is_readable($path) || !is_file($path))
439
                $error[] = $this->label("Cannot read '{file}'.", $replace);
440
            elseif (!@copy($path, "$dir/$base"))
441
                $error[] = $this->label("Cannot copy '{file}'.", $replace);
442
            else {
443
                if (function_exists("chmod"))
444
                    @chmod("$dir/$base", $this->config['filePerms']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

444
                    /** @scrutinizer ignore-unhandled */ @chmod("$dir/$base", $this->config['filePerms']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
445
                $fromThumb = "{$this->thumbsDir}/$file";
446
                if (is_file($fromThumb) && is_readable($fromThumb)) {
447
                    $toThumb = "{$this->thumbsTypeDir}/{$_POST['dir']}";
448
                    if (!is_dir($toThumb))
449
                        @mkdir($toThumb, $this->config['dirPerms'], true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

449
                        /** @scrutinizer ignore-unhandled */ @mkdir($toThumb, $this->config['dirPerms'], true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
450
                    $toThumb .= "/$base";
451
                    @copy($fromThumb, $toThumb);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

451
                    /** @scrutinizer ignore-unhandled */ @copy($fromThumb, $toThumb);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
452
                }
453
            }
454
        }
455
        if (count($error))
456
            return json_encode(array('error' => $error));
457
        return true;
458
    }
459
460
    protected function act_mv_cbd() {
461
        $dir = $this->postDir();
462
        if (!$this->config['access']['files']['move'] ||
463
            !isset($_POST['dir']) ||
464
            !is_dir($dir) || !is_readable($dir) || !dir::isWritable($dir) ||
465
            !isset($_POST['files']) || !is_array($_POST['files']) ||
466
            !count($_POST['files'])
467
        )
468
            $this->errorMsg("Unknown error.");
469
470
        $error = array();
471
        foreach($_POST['files'] as $file) {
472
            $file = path::normalize($file);
473
            if (substr($file, 0, 1) == ".") continue;
474
            $type = explode("/", $file);
475
            $type = $type[0];
476
            if ($type != $this->type) continue;
477
            $path = "{$this->config['uploadDir']}/$file";
478
            if (!$this->checkFilePath($path)) continue;
479
            $base = basename($file);
480
            $replace = array('file' => $this->htmlData($base));
481
            $ext = file::getExtension($base);
482
            if (!file_exists($path))
483
                $error[] = $this->label("The file '{file}' does not exist.", $replace);
484
            elseif (substr($base, 0, 1) == ".")
485
                $error[] = $this->htmlData($base) . ": " . $this->label("File name shouldn't begins with '.'");
486
            elseif (!$this->validateExtension($ext, $type))
487
                $error[] = $this->htmlData($base) . ": " . $this->label("Denied file extension.");
488
            elseif (file_exists("$dir/$base"))
489
                $error[] = $this->htmlData($base) . ": " . $this->label("A file or folder with that name already exists.");
490
            elseif (!is_readable($path) || !is_file($path))
491
                $error[] = $this->label("Cannot read '{file}'.", $replace);
492
            elseif (!file::isWritable($path) || !@rename($path, "$dir/$base"))
493
                $error[] = $this->label("Cannot move '{file}'.", $replace);
494
            else {
495
                if (function_exists("chmod"))
496
                    @chmod("$dir/$base", $this->config['filePerms']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

496
                    /** @scrutinizer ignore-unhandled */ @chmod("$dir/$base", $this->config['filePerms']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
497
                $fromThumb = "{$this->thumbsDir}/$file";
498
                if (is_file($fromThumb) && is_readable($fromThumb)) {
499
                    $toThumb = "{$this->thumbsTypeDir}/{$_POST['dir']}";
500
                    if (!is_dir($toThumb))
501
                        @mkdir($toThumb, $this->config['dirPerms'], true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

501
                        /** @scrutinizer ignore-unhandled */ @mkdir($toThumb, $this->config['dirPerms'], true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
502
                    $toThumb .= "/$base";
503
                    @rename($fromThumb, $toThumb);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

503
                    /** @scrutinizer ignore-unhandled */ @rename($fromThumb, $toThumb);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
504
                }
505
            }
506
        }
507
        if (count($error))
508
            return json_encode(array('error' => $error));
509
        return true;
510
    }
511
512
    protected function act_rm_cbd() {
513
        if (!$this->config['access']['files']['delete'] ||
514
            !isset($_POST['files']) ||
515
            !is_array($_POST['files']) ||
516
            !count($_POST['files'])
517
        )
518
            $this->errorMsg("Unknown error.");
519
520
        $error = array();
521
        foreach($_POST['files'] as $file) {
522
            $file = path::normalize($file);
523
            if (substr($file, 0, 1) == ".") continue;
524
            $type = explode("/", $file);
525
            $type = $type[0];
526
            if ($type != $this->type) continue;
527
            $path = "{$this->config['uploadDir']}/$file";
528
            if (!$this->checkFilePath($path)) continue;
529
            $base = basename($file);
530
            $replace = array('file' => $this->htmlData($base));
531
            if (!is_file($path))
532
                $error[] = $this->label("The file '{file}' does not exist.", $replace);
533
            elseif (!@unlink($path))
534
                $error[] = $this->label("Cannot delete '{file}'.", $replace);
535
            else {
536
                $thumb = "{$this->thumbsDir}/$file";
537
                if (is_file($thumb)) @unlink($thumb);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

537
                if (is_file($thumb)) /** @scrutinizer ignore-unhandled */ @unlink($thumb);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
538
            }
539
        }
540
        if (count($error))
541
            return json_encode(array('error' => $error));
542
        return true;
543
    }
544
545
    protected function act_downloadDir() {
546
        $dir = $this->postDir();
547
        if (!isset($_POST['dir']) || $this->config['denyZipDownload'])
548
            $this->errorMsg("Unknown error.");
549
        $filename = basename($dir) . ".zip";
550
        do {
551
            $file = md5(time() . session_id());
552
            $file = "{$this->config['uploadDir']}/$file.zip";
553
        } while (file_exists($file));
554
        new zipFolder($file, $dir);
555
        header("Content-Type: application/x-zip");
556
        header('Content-Disposition: attachment; filename="' . str_replace('"', "_", $filename) . '"');
557
        header("Content-Length: " . filesize($file));
558
        readfile($file);
559
        unlink($file);
560
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
561
    }
562
563
    protected function act_downloadSelected() {
564
        $dir = $this->postDir();
565
        if (!isset($_POST['dir']) ||
566
            !isset($_POST['files']) ||
567
            !is_array($_POST['files']) ||
568
            $this->config['denyZipDownload']
569
        )
570
            $this->errorMsg("Unknown error.");
571
572
        $zipFiles = array();
573
        foreach ($_POST['files'] as $file) {
574
            $file = path::normalize($file);
575
            if ((substr($file, 0, 1) == ".") || (strpos($file, '/') !== false))
576
                continue;
577
            $file = "$dir/$file";
578
            if (!is_file($file) || !is_readable($file) || !$this->checkFilePath($file))
579
                continue;
580
            $zipFiles[] = $file;
581
        }
582
583
        do {
584
            $file = md5(time() . session_id());
585
            $file = "{$this->config['uploadDir']}/$file.zip";
586
        } while (file_exists($file));
587
588
        $zip = new \ZipArchive();
589
        $res = $zip->open($file, \ZipArchive::CREATE);
590
        if ($res === TRUE) {
591
            foreach ($zipFiles as $cfile)
592
                $zip->addFile($cfile, basename($cfile));
593
            $zip->close();
594
        }
595
        header("Content-Type: application/x-zip");
596
        header('Content-Disposition: attachment; filename="selected_files_' . basename($file) . '"');
597
        header("Content-Length: " . filesize($file));
598
        readfile($file);
599
        unlink($file);
600
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
601
    }
602
603
    protected function act_downloadClipboard() {
604
        if (!isset($_POST['files']) ||
605
            !is_array($_POST['files']) ||
606
            $this->config['denyZipDownload']
607
        )
608
            $this->errorMsg("Unknown error.");
609
610
        $zipFiles = array();
611
        foreach ($_POST['files'] as $file) {
612
            $file = path::normalize($file);
613
            if ((substr($file, 0, 1) == "."))
614
                continue;
615
            $type = explode("/", $file);
616
            $type = $type[0];
617
            if ($type != $this->type)
618
                continue;
619
            $file = $this->config['uploadDir'] . "/$file";
620
            if (!is_file($file) || !is_readable($file) || !$this->checkFilePath($file))
621
                continue;
622
            $zipFiles[] = $file;
623
        }
624
625
        do {
626
            $file = md5(time() . session_id());
627
            $file = "{$this->config['uploadDir']}/$file.zip";
628
        } while (file_exists($file));
629
630
        $zip = new \ZipArchive();
631
        $res = $zip->open($file, \ZipArchive::CREATE);
632
        if ($res === TRUE) {
633
            foreach ($zipFiles as $cfile)
634
                $zip->addFile($cfile, basename($cfile));
635
            $zip->close();
636
        }
637
        header("Content-Type: application/x-zip");
638
        header('Content-Disposition: attachment; filename="clipboard_' . basename($file) . '"');
639
        header("Content-Length: " . filesize($file));
640
        readfile($file);
641
        unlink($file);
642
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
643
    }
644
645
    protected function act_check4Update() {
646
        if ($this->config['denyUpdateCheck'])
647
            return json_encode(array('version' => false));
648
649
        // Caching HTTP request for 6 hours
650
        if (isset($this->session['checkVersion']) &&
651
            isset($this->session['checkVersionTime']) &&
652
            ((time() - $this->session['checkVersionTime']) < 21600)
653
        )
654
            return json_encode(array('version' => $this->session['checkVersion']));
655
656
        $ver = phpGet::get("http://kcfinder.sunhater.com/checkVersion.php");
657
658
        if (isset($ver) && preg_match('/^\d+\.\d+$/', $ver)) {
659
            $this->session['checkVersion'] = $ver;
660
            $this->session['checkVersionTime'] = time();
661
            return json_encode(array('version' => $ver));
662
        } else
663
            return json_encode(array('version' => false));
664
    }
665
666
    protected function moveUploadFile($file, $dir) {
667
        $message = $this->checkUploadedFile($file);
668
669
        if ($message !== true) {
670
            if (isset($file['tmp_name']))
671
                @unlink($file['tmp_name']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

671
                /** @scrutinizer ignore-unhandled */ @unlink($file['tmp_name']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
672
            return "{$file['name']}: $message";
673
        }
674
675
        $filename = $this->normalizeFilename($file['name']);
676
        $target = "$dir/" . file::getInexistantFilename($filename, $dir);
677
678
        if (!@move_uploaded_file($file['tmp_name'], $target) &&
679
            !@rename($file['tmp_name'], $target) &&
680
            !@copy($file['tmp_name'], $target)
681
        ) {
682
            @unlink($file['tmp_name']);
683
            return $this->htmlData($file['name']) . ": " . $this->label("Cannot move uploaded file to target folder.");
684
        } elseif (function_exists('chmod'))
685
            chmod($target, $this->config['filePerms']);
686
687
        $this->makeThumb($target);
688
        return "/" . basename($target);
689
    }
690
691
    protected function sendDefaultThumb($file=null) {
692
        if ($file !== null) {
693
            $ext = file::getExtension($file);
694
            $thumb = "themes/{$this->config['theme']}/img/files/big/$ext.png";
695
        }
696
        if (!isset($thumb) || !file_exists($thumb))
697
            $thumb = "themes/{$this->config['theme']}/img/files/big/..png";
698
        header("Content-Type: image/png");
699
        readfile($thumb);
700
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
701
    }
702
703
    protected function getFiles($dir) {
704
        $thumbDir = "{$this->config['uploadDir']}/{$this->config['thumbsDir']}/$dir";
705
        $dir = "{$this->config['uploadDir']}/$dir";
706
        $return = array();
707
        $files = dir::content($dir, array('types' => "file"));
708
        if ($files === false)
0 ignored issues
show
introduced by
The condition $files === false is always true.
Loading history...
709
            return $return;
710
711
        foreach ($files as $file) {
712
713
            $img = new fastImage($file);
714
            $type = $img->getType();
715
716
            if ($type !== false) {
717
                $size = $img->getSize($file);
718
                if (is_array($size) && count($size)) {
719
                    $thumb_file = "$thumbDir/" . basename($file);
720
                    if (!is_file($thumb_file))
721
                        $this->makeThumb($file, false);
722
                    $smallThumb =
723
                        ($size[0] <= $this->config['thumbWidth']) &&
724
                        ($size[1] <= $this->config['thumbHeight']) &&
725
                        in_array($type, array("gif", "jpeg", "png"));
726
                } else
727
                    $smallThumb = false;
728
            } else
729
                $smallThumb = false;
730
731
            $img->close();
732
733
            $stat = stat($file);
734
            if ($stat === false) continue;
735
            $name = basename($file);
736
            $ext = file::getExtension($file);
737
            $bigIcon = file_exists("themes/{$this->config['theme']}/img/files/big/$ext.png");
738
            $smallIcon = file_exists("themes/{$this->config['theme']}/img/files/small/$ext.png");
739
            $thumb = file_exists("$thumbDir/$name");
740
            $return[] = array(
741
                'name' => stripcslashes($name),
742
                'size' => $stat['size'],
743
                'mtime' => $stat['mtime'],
744
                'date' => @strftime($this->dateTimeSmall, $stat['mtime']),
745
                'readable' => is_readable($file),
746
                'writable' => file::isWritable($file),
747
                'bigIcon' => $bigIcon,
748
                'smallIcon' => $smallIcon,
749
                'thumb' => $thumb,
750
                'smallThumb' => $smallThumb
751
            );
752
        }
753
        return $return;
754
    }
755
756
    protected function getTree($dir, $index=0) {
757
        $path = explode("/", $dir);
758
759
        $pdir = "";
760
        for ($i = 0; ($i <= $index && $i < count($path)); $i++)
761
            $pdir .= "/{$path[$i]}";
762
        if (strlen($pdir))
763
            $pdir = substr($pdir, 1);
764
765
        $fdir = "{$this->config['uploadDir']}/$pdir";
766
767
        $dirs = $this->getDirs($fdir);
768
769
        if (is_array($dirs) && count($dirs) && ($index <= count($path) - 1)) {
770
771
            foreach ($dirs as $i => $cdir) {
772
                if ($cdir['hasDirs'] &&
773
                    (
774
                        ($index == count($path) - 1) ||
775
                        ($cdir['name'] == $path[$index + 1])
776
                    )
777
                ) {
778
                    $dirs[$i]['dirs'] = $this->getTree($dir, $index + 1);
779
                    if (!is_array($dirs[$i]['dirs']) || !count($dirs[$i]['dirs'])) {
780
                        unset($dirs[$i]['dirs']);
781
                        continue;
782
                    }
783
                }
784
            }
785
        } else
786
            return false;
787
788
        return $dirs;
789
    }
790
791
    protected function postDir($existent=true) {
792
        $dir = $this->typeDir;
793
        if (isset($_POST['dir']))
794
            $dir .= "/" . $_POST['dir'];
795
        if (!$this->checkFilePath($dir))
796
            $this->errorMsg("Unknown error.");
797
        if ($existent && (!is_dir($dir) || !is_readable($dir)))
798
            $this->errorMsg("Inexistant or inaccessible folder.");
799
        return $dir;
800
    }
801
802
    protected function getDir($existent=true) {
803
        $dir = $this->typeDir;
804
        if (isset($_GET['dir']))
805
            $dir .= "/" . $_GET['dir'];
806
        if (!$this->checkFilePath($dir))
807
            $this->errorMsg("Unknown error.");
808
        if ($existent && (!is_dir($dir) || !is_readable($dir)))
809
            $this->errorMsg("Inexistant or inaccessible folder.");
810
        return $dir;
811
    }
812
813
    protected function getDirs($dir) {
814
        $dirs = dir::content($dir, array('types' => "dir"));
815
        $return = array();
816
        if (is_array($dirs)) {
0 ignored issues
show
introduced by
The condition is_array($dirs) is always false.
Loading history...
817
            $writable = dir::isWritable($dir);
818
            foreach ($dirs as $cdir) {
819
                $info = $this->getDirInfo($cdir);
820
                if ($info === false) continue;
821
                $info['removable'] = $writable && $info['writable'];
822
                $return[] = $info;
823
            }
824
        }
825
        return $return;
826
    }
827
828
    protected function getDirInfo($dir, $removable=false) {
829
        if ((substr(basename($dir), 0, 1) == ".") || !is_dir($dir) || !is_readable($dir))
830
            return false;
831
        $dirs = dir::content($dir, array('types' => "dir"));
832
        if (is_array($dirs)) {
0 ignored issues
show
introduced by
The condition is_array($dirs) is always false.
Loading history...
833
            foreach ($dirs as $key => $cdir)
834
                if (substr(basename($cdir), 0, 1) == ".")
835
                    unset($dirs[$key]);
836
            $hasDirs = count($dirs) ? true : false;
837
        } else
838
            $hasDirs = false;
839
840
        $writable = dir::isWritable($dir);
841
        $info = array(
842
            'name' => stripslashes(basename($dir)),
843
            'readable' => is_readable($dir),
844
            'writable' => $writable,
845
            'removable' => $removable && $writable && dir::isWritable(dirname($dir)),
846
            'hasDirs' => $hasDirs
847
        );
848
849
        if ($dir == "{$this->config['uploadDir']}/{$this->session['dir']}")
850
            $info['current'] = true;
851
852
        return $info;
853
    }
854
855
    protected function output($data=null, $template=null) {
856
        if (!is_array($data)) $data = array();
857
        if ($template === null)
858
            $template = $this->action;
859
860
        if (file_exists("tpl/tpl_$template.php")) {
861
            ob_start();
862
            $eval = "unset(\$data);unset(\$template);unset(\$eval);";
863
            $_ = $data;
0 ignored issues
show
Unused Code introduced by
The assignment to $_ is dead and can be removed.
Loading history...
864
            foreach (array_keys($data) as $key)
865
                if (preg_match('/^[a-z\d_]+$/i', $key))
866
                    $eval .= "\$$key=\$_['$key'];";
867
            $eval .= "unset(\$_);require \"tpl/tpl_$template.php\";";
868
            eval($eval);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
869
            return ob_get_clean();
870
        }
871
872
        return "";
873
    }
874
875
    protected function errorMsg($message, array $data=null) {
876
        if (in_array($this->action, array("thumb", "upload", "download", "downloadDir")))
877
            die($this->label($message, $data));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
878
        if (($this->action === null) || ($this->action == "browser"))
879
            $this->backMsg($message, $data);
880
        else {
881
            $message = $this->label($message, $data);
882
            die(json_encode(array('error' => $message)));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
883
        }
884
    }
885
886
    protected function htmlData($str) {
887
        return htmlentities($str, null, strtoupper($this->charset));
888
    }
889
890
    protected function downloadURL($url, $dir) {
891
892
        if (!preg_match(phpGet::$urlExpr, $url, $match))
893
            return;
894
895
        if ((isset($match[7]) && strlen($match[7])))
896
            $furl = explode("&", $match[7]);
897
898
        $filename = isset($furl)
899
            ? basename($furl[0])
900
            : "web_image.jpg";
901
902
        $file = tempnam(sys_get_temp_dir(), $filename);
903
904
        if (phpGet::get($url, $file))
0 ignored issues
show
Bug Best Practice introduced by
The expression kcfinder\phpGet::get($url, $file) of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
905
            $this->moveUploadFile(array(
906
                'name' => $filename,
907
                'tmp_name' => $file,
908
                'error' => UPLOAD_ERR_OK
909
            ), $dir);
910
        else
911
            @unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

911
            /** @scrutinizer ignore-unhandled */ @unlink($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
912
    }
913
914
    protected function getLangs() {
915
        if (isset($this->session['langs']))
916
            return $this->session['langs'];
917
918
        $files = dir::content("lang", array(
919
            'pattern' => '/^[a-z]{2,3}(\-[a-z]{2})?\.php$/',
920
            'types' => "file"
921
        ));
922
923
        $langs = array();
924
        if (is_array($files))
0 ignored issues
show
introduced by
The condition is_array($files) is always false.
Loading history...
925
            foreach ($files as $file) {
926
                include $file;
927
                $id = substr(basename($file), 0, -4);
928
                $langs[$id] = isset($lang['_native'])
929
                    ? $lang['_native']
930
                    : (isset($lang['_lang'])
931
                        ? $lang['_lang']
932
                        : $id);
933
            }
934
935
        $this->session['langs'] = $langs;
936
        return $langs;
937
    }
938
}
939