FileManager::onMove()   C
last analyzed

Complexity

Conditions 13
Paths 23

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 24
c 1
b 0
f 0
nc 23
nop 0
dl 0
loc 39
rs 6.6166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
Script: FileManager.php
4
	MooTools FileManager - Backend for the FileManager Script
5
6
License:
7
	MIT-style license.
8
9
Copyright:
10
	Copyright (c) 2009 [Christoph Pojer](http://cpojer.net).
11
12
Dependencies:
13
	- Upload.php
14
	- Image.php
15
	- getId3 Library
16
17
Options:
18
	- directory: (string) The base directory to be used for the FileManger
19
	- baseURL: (string) Absolute URL to the FileManager files
20
	- assetBasePath: (string) The path to all images and swf files
21
	- id3Path: (string, optional) The path to the getid3.php file
22
	- mimeTypesPath: (string, optional) The path to the MimTypes.ini file.
23
	- dateFormat: (string, defaults to *j M Y - H:i*) The format in which dates should be displayed
24
	- upload: (boolean, defaults to *false*) Whether to allow uploads or not
25
	- destroy: (boolean, defaults to *false*) Whether to allow deletion of files or not
26
	- maxUploadSize: (integeter, defaults to *3145728* bytes) The maximum file size for upload in bytes
27
	- safe: (string, defaults to *true*) If true, disallows 
28
	- filter: (string) If specified, the mimetypes to be allowed (for display and upload).
29
		Example: image/ allows all Image Mimetypes
30
*/
31
32
require_once(FileManagerUtility::getPath() . '/Upload.php');
0 ignored issues
show
Bug introduced by
Are you sure FileManagerUtility::getPath() of type array|mixed|string can be used in concatenation? ( Ignorable by Annotation )

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

32
require_once(/** @scrutinizer ignore-type */ FileManagerUtility::getPath() . '/Upload.php');
Loading history...
33
require_once(FileManagerUtility::getPath() . '/Image.php');
34
35
class FileManager
36
{
37
38
    protected $path     = null;
39
    protected $length   = null;
40
    protected $basedir  = null;
41
    protected $basename = null;
42
    protected $options;
43
    protected $post;
44
    protected $get;
45
46
    public function __construct($options)
47
    {
48
        $path = FileManagerUtility::getPath();
49
50
        $this->options = array_merge(
51
            [
52
                'directory'                  => '../Demos/Files',
53
                'baseURL'                    => '',
54
                'assetBasePath'              => '../Assets',
55
                'id3Path'                    => $path . '/Assets/getid3/getid3.php',
0 ignored issues
show
Bug introduced by
Are you sure $path of type array|mixed|string can be used in concatenation? ( Ignorable by Annotation )

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

55
                'id3Path'                    => /** @scrutinizer ignore-type */ $path . '/Assets/getid3/getid3.php',
Loading history...
56
                'mimeTypesPath'              => $path . '/MimeTypes.ini',
57
                'dateFormat'                 => 'j M Y - H:i',
58
                'maxUploadSize'              => 1024 * 1024 * 3,
59
                'upload'                     => false,
60
                'destroy'                    => false,
61
                'safe'                       => true,
62
                'filter'                     => null,
63
64
                // Xinha: Allow to specify the "Resize Large Images" tolerance level.
65
                'suggestedMaxImageDimension' => ['width' => 800, 'height' => 600],
66
            ],
67
            $options
68
        );
69
70
        $this->basedir  = realpath($this->options['directory']);
71
        $this->basename = pathinfo($this->basedir, PATHINFO_BASENAME) . '/';
0 ignored issues
show
Bug introduced by
Are you sure pathinfo($this->basedir, PATHINFO_BASENAME) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

71
        $this->basename = /** @scrutinizer ignore-type */ pathinfo($this->basedir, PATHINFO_BASENAME) . '/';
Loading history...
72
        $this->path     = realpath($this->options['directory'] . '/../');
73
        $this->length   = strlen($this->path);
74
75
        header('Expires: Fri, 01 Jan 1990 00:00:00 GMT');
76
        header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
77
78
        $this->get  = $_GET;
79
        $this->post = $_POST;
80
    }
81
82
    public function fireEvent($event)
83
    {
84
        $event = $event ? 'on' . ucfirst($event) : null;
85
        if (!$event || !method_exists($this, $event)) {
86
            $event = 'onView';
87
        }
88
89
        $this->{$event}();
90
    }
91
92
    protected function onView()
93
    {
94
        $dir   = $this->getDir(!empty($this->post['directory']) ? $this->post['directory'] : null);
95
        $files = ($files = glob($dir . '/*')) ? $files : [];
96
97
        if ($dir != $this->basedir) {
98
            array_unshift($files, $dir . '/..');
99
        }
100
        natcasesort($files);
101
        foreach ($files as $file) {
102
            $mime = $this->getMimeType($file);
103
            if ($this->options['filter'] && 'text/directory' != $mime && !FileManagerUtility::startsWith($mime, $this->options['filter'])) {
104
                continue;
105
            }
106
107
            $out[is_dir($file) ? 0 : 1][] = [
108
                'name' => pathinfo($file, PATHINFO_BASENAME),
109
                'date' => date($this->options['dateFormat'], filemtime($file)),
110
                'mime' => $this->getMimeType($file),
111
                'icon' => $this->getIcon($this->normalize($file)),
112
                'size' => filesize($file)
113
            ];
114
        }
115
116
        echo json_encode(
117
            [
118
                'path'  => $this->getPath($dir),
119
                'dir'   => [
120
                    'name' => pathinfo($dir, PATHINFO_BASENAME),
121
                    'date' => date($this->options['dateFormat'], filemtime($dir)),
122
                    'mime' => 'text/directory',
123
                    'icon' => 'dir'
124
                ],
125
                'files' => array_merge(!empty($out[0]) ? $out[0] : [], !empty($out[1]) ? $out[1] : [])
126
            ]
127
        );
128
    }
129
130
    protected function onDetail()
131
    {
132
        if (empty($this->post['directory']) || empty($this->post['file'])) {
133
            return;
134
        }
135
136
        $file = realpath($this->path . '/' . $this->post['directory'] . '/' . $this->post['file']);
137
        if (!$this->checkFile($file)) {
138
            return;
139
        }
140
141
        require_once($this->options['id3Path']);
142
143
        // Xinha: The URL is weird in the standard distribution of filemanager, it seems to expect
144
        // that the files directory (where you are selecting/uploading) is always within the filemanager
145
        // directory itself somewhere.
146
        //
147
        // Also the 'baseURL' seems to be wanted as the parent of the 'basedir' ("directory" option)
148
        // Xinha is supplying both the same (eg url = /foo/test and dir = /home/bar/public_html/foo/test )
149
        // so we will rip off the first part of directory, below.
150
        $url = $this->options['baseURL'] . '/' . preg_replace('/^[^\/]*\//', '', $this->post['directory'] . '/' . $this->post['file']);
151
152
        $mime    = $this->getMimeType($file);
153
        $content = null;
154
155
        // Xinha: We want to get some more information about what has been selected in a way
156
        // we can use it.  Effectively what gets put in here will be passed into the
157
        // 'onDetails' event handler of your FileManager object (if any).
158
        $extra_return_detail = [
159
            'url'  => $url,
160
            'mime' => $mime
161
        ];
162
163
        if (FileManagerUtility::startsWith($mime, 'image/')) {
164
            $size    = getimagesize($file);
165
            $content = '<img src="' . $url . '" class="preview" alt="" />
166
				<h2>${more}</h2>
167
				<dl>
168
					<dt>${width}</dt><dd>' . $size[0] . 'px</dd>
169
					<dt>${height}</dt><dd>' . $size[1] . 'px</dd>
170
				</dl>';
171
172
            // Xinha: Return some information about the image which can be access
173
            // from the onDetails event handler in FileManager
174
            $extra_return_detail['width']  = $size[0];
175
            $extra_return_detail['height'] = $size[1];
176
        } elseif (FileManagerUtility::startsWith($mime, 'text/') || 'application/x-javascript' == $mime) {
177
            $filecontent = file_get_contents($file, null, null, 0, 300);
0 ignored issues
show
Bug introduced by
null of type null is incompatible with the type boolean expected by parameter $use_include_path of file_get_contents(). ( Ignorable by Annotation )

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

177
            $filecontent = file_get_contents($file, /** @scrutinizer ignore-type */ null, null, 0, 300);
Loading history...
178
            if (!FileManagerUtility::isBinary($filecontent)) {
179
                $content = '<div class="textpreview">' . nl2br(str_replace(['$', "\t"], ['&#36;', '&nbsp;&nbsp;'], htmlentities($filecontent))) . '</div>';
180
            }
181
        } elseif ('application/zip' == $mime) {
182
            $out    = [[], []];
183
            $getid3 = new getID3();
184
            $getid3->Analyze($file);
185
            foreach ($getid3->info['zip']['files'] as $name => $size) {
186
                $icon                                 = is_array($size) ? 'dir' : $this->getIcon($name);
187
                $out[('dir' == $icon) ? 0 : 1][$name] = '<li><a><img src="' . $this->options['assetBasePath'] . '/Icons/' . $icon . '.png" alt="" /> ' . $name . '</a></li>';
0 ignored issues
show
Bug introduced by
Are you sure $icon of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

187
                $out[('dir' == $icon) ? 0 : 1][$name] = '<li><a><img src="' . $this->options['assetBasePath'] . '/Icons/' . /** @scrutinizer ignore-type */ $icon . '.png" alt="" /> ' . $name . '</a></li>';
Loading history...
188
            }
189
            natcasesort($out[0]);
190
            natcasesort($out[1]);
191
            $content = '<ul>' . implode(array_merge($out[0], $out[1])) . '</ul>';
192
        } elseif (FileManagerUtility::startsWith($mime, 'audio/')) {
193
            $getid3 = new getID3();
194
            $getid3->Analyze($file);
195
196
            $content = '<div class="object">
197
					<object type="application/x-shockwave-flash" data="' . $this->options['assetBasePath'] . '/dewplayer.swf?mp3=' . rawurlencode($url) . '&volume=30" width="200" height="20">
198
						<param name="movie" value="' . $this->options['assetBasePath'] . '/dewplayer.swf?mp3=' . rawurlencode($url) . '&volume=30" />
199
					</object>
200
				</div>
201
				<h2>${more}</h2>
202
				<dl>
203
					<dt>${title}</dt><dd>' . $getid3->info['comments']['title'][0] . '</dd>
204
					<dt>${artist}</dt><dd>' . $getid3->info['comments']['artist'][0] . '</dd>
205
					<dt>${album}</dt><dd>' . $getid3->info['comments']['album'][0] . '</dd>
206
					<dt>${length}</dt><dd>' . $getid3->info['playtime_string'] . '</dd>
207
					<dt>${bitrate}</dt><dd>' . round($getid3->info['bitrate'] / 1000) . 'kbps</dd>
208
				</dl>';
209
        }
210
211
        echo json_encode(
212
            array_merge(
213
                [
214
                    'content' => $content ? $content : '<div class="margin">
215
				${nopreview}<br/><button value="' . $url . '">${download}</button>
216
			</div>'
217
                ],
218
                $extra_return_detail
219
            )
220
        );
221
    }
222
223
    protected function onDestroy()
224
    {
225
        if (!$this->options['destroy'] || empty($this->post['directory']) || empty($this->post['file'])) {
226
            return;
227
        }
228
229
        $file = realpath($this->path . '/' . $this->post['directory'] . '/' . $this->post['file']);
230
        if (!$this->checkFile($file)) {
231
            return;
232
        }
233
234
        $this->unlink($file);
235
236
        echo json_encode(
237
            [
238
                'content' => 'destroyed'
239
            ]
240
        );
241
    }
242
243
    protected function onCreate()
244
    {
245
        if ($this->options['upload']) {
246
            if (empty($this->post['directory']) || empty($this->post['file'])) {
247
                return;
248
            }
249
250
            $file = $this->getName($this->post['file'], $this->getDir($this->post['directory']));
251
            if (!$file) {
252
                return;
253
            }
254
255
            mkdir($file);
256
        }
257
258
        $this->onView();
259
    }
260
261
    protected function onUpload()
262
    {
263
        try {
264
            if (!$this->options['upload']) {
265
                throw new FileManagerException('disabled');
266
            }
267
            if (empty($this->get['directory']) || (function_exists('UploadIsAuthenticated') && !UploadIsAuthenticated($this->get))) {
268
                throw new FileManagerException('authenticated');
269
            }
270
271
            $dir  = $this->getDir($this->get['directory']);
272
            $name = pathinfo((Upload::exists('Filedata')) ? $this->getName($_FILES['Filedata']['name'], $dir) : null, PATHINFO_FILENAME);
0 ignored issues
show
Bug Best Practice introduced by
The method Upload::exists() is not static, but was called statically. ( Ignorable by Annotation )

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

272
            $name = pathinfo((Upload::/** @scrutinizer ignore-call */ exists('Filedata')) ? $this->getName($_FILES['Filedata']['name'], $dir) : null, PATHINFO_FILENAME);
Loading history...
Bug introduced by
It seems like Upload::exists('Filedata...]['name'], $dir) : null can also be of type null; however, parameter $path of pathinfo() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

272
            $name = pathinfo(/** @scrutinizer ignore-type */ (Upload::exists('Filedata')) ? $this->getName($_FILES['Filedata']['name'], $dir) : null, PATHINFO_FILENAME);
Loading history...
273
            $file = Upload::move(
274
                'Filedata',
275
                $dir . '/',
276
                [
277
                    'name'      => $name,
278
                    'extension' => $this->options['safe'] && $name && in_array(strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION)), ['exe', 'dll', 'php', 'php3', 'php4', 'php5', 'phps']) ? 'txt' : null,
0 ignored issues
show
Bug introduced by
It seems like pathinfo($_FILES['Fileda...'], PATHINFO_EXTENSION) can also be of type array; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

278
                    'extension' => $this->options['safe'] && $name && in_array(strtolower(/** @scrutinizer ignore-type */ pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION)), ['exe', 'dll', 'php', 'php3', 'php4', 'php5', 'phps']) ? 'txt' : null,
Loading history...
279
                    'size'      => $this->options['maxUploadSize'],
280
                    'mimes'     => $this->getAllowedMimeTypes()
281
                ]
282
            );
283
284
            if (FileManagerUtility::startsWith(Upload::mime($file), 'image/') && !empty($this->get['resize'])) {
0 ignored issues
show
Bug Best Practice introduced by
The method Upload::mime() is not static, but was called statically. ( Ignorable by Annotation )

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

284
            if (FileManagerUtility::startsWith(Upload::/** @scrutinizer ignore-call */ mime($file), 'image/') && !empty($this->get['resize'])) {
Loading history...
Bug introduced by
It seems like $file can also be of type false; however, parameter $file of Upload::mime() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

284
            if (FileManagerUtility::startsWith(Upload::mime(/** @scrutinizer ignore-type */ $file), 'image/') && !empty($this->get['resize'])) {
Loading history...
285
                $img  = new Image($file);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $file of Image::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

285
                $img  = new Image(/** @scrutinizer ignore-type */ $file);
Loading history...
286
                $size = $img->getSize();
287
                if ($size['width'] > $this->options['suggestedMaxImageDimension']['width']) {
288
                    $img->resize($this->options['suggestedMaxImageDimension']['width'])->save();
289
                } elseif ($size['height'] > $this->options['suggestedMaxImageDimension']['height']) {
290
                    $img->resize(null, $this->options['suggestedMaxImageDimension']['height'])->save();
291
                }
292
            }
293
294
            echo json_encode(
295
                [
296
                    'status' => 1,
297
                    'name'   => pathinfo($file, PATHINFO_BASENAME)
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $path of pathinfo() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

297
                    'name'   => pathinfo(/** @scrutinizer ignore-type */ $file, PATHINFO_BASENAME)
Loading history...
298
                ]
299
            );
300
        } catch (UploadException $e) {
301
            echo json_encode(
302
                [
303
                    'status' => 0,
304
                    'error'  => class_exists('ValidatorException') ? strip_tags($e->getMessage()) : '${upload.' . $e->getMessage() . '}' // This is for Styx :)
305
                ]
306
            );
307
        } catch (FileManagerException $e) {
308
            echo json_encode(
309
                [
310
                    'status' => 0,
311
                    'error'  => '${upload.' . $e->getMessage() . '}'
312
                ]
313
            );
314
        }
315
    }
316
317
    /* This method is used by both move and rename */
318
    protected function onMove()
319
    {
320
        if (empty($this->post['directory']) || empty($this->post['file'])) {
321
            return;
322
        }
323
324
        $rename = empty($this->post['newDirectory']) && !empty($this->post['name']);
325
        $dir    = $this->getDir($this->post['directory']);
326
        $file   = realpath($dir . '/' . $this->post['file']);
327
328
        $is_dir = is_dir($file);
329
        if (!$this->checkFile($file) || (!$rename && $is_dir)) {
330
            return;
331
        }
332
333
        if ($rename || $is_dir) {
334
            if (empty($this->post['name'])) {
335
                return;
336
            }
337
            $newname = $this->getName($this->post['name'], $dir);
338
            $fn      = 'rename';
339
        } else {
340
            $newname = $this->getName(pathinfo($file, PATHINFO_FILENAME), $this->getDir($this->post['newDirectory']));
341
            $fn      = !empty($this->post['copy']) ? 'copy' : 'rename';
342
        }
343
344
        if (!$newname) {
345
            return;
346
        }
347
348
        $ext = pathinfo($file, PATHINFO_EXTENSION);
349
        if ($ext) {
350
            $newname .= '.' . $ext;
0 ignored issues
show
Bug introduced by
Are you sure $ext of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

350
            $newname .= '.' . /** @scrutinizer ignore-type */ $ext;
Loading history...
351
        }
352
        $fn($file, $newname);
353
354
        echo json_encode(
355
            [
356
                'name' => pathinfo($this->normalize($newname), PATHINFO_BASENAME),
357
            ]
358
        );
359
    }
360
361
    protected function unlink($file)
362
    {
363
        $file = realpath($file);
364
        if ($this->basedir == $file || strlen($this->basedir) >= strlen($file)) {
365
            return;
366
        }
367
368
        if (is_dir($file)) {
369
            $files = glob($file . '/*');
370
            if (is_array($files)) {
0 ignored issues
show
introduced by
The condition is_array($files) is always true.
Loading history...
371
                foreach ($files as $f) {
372
                    $this->unlink($f);
373
                }
374
            }
375
376
            rmdir($file);
377
        } else {
378
            try {
379
                if ($this->checkFile($file)) {
380
                    unlink($file);
381
                }
382
            } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
383
            }
384
        }
385
    }
386
387
    protected function getName($file, $dir)
388
    {
389
        $files = [];
390
        foreach ((array)glob($dir . '/*') as $f) {
391
            $files[] = pathinfo($f, PATHINFO_FILENAME);
392
        }
393
394
        $pathinfo = pathinfo($file);
395
        $file     = $dir . '/' . FileManagerUtility::pagetitle($pathinfo['filename'], $files) . (!empty($pathinfo['extension']) ? '.' . $pathinfo['extension'] : null);
396
397
        return !$file || !FileManagerUtility::startsWith($file, $this->basedir) || file_exists($file) ? null : $file;
398
    }
399
400
    protected function getIcon($file)
401
    {
402
        if (FileManagerUtility::endsWith($file, '/..')) {
403
            return 'dir_up';
404
        } elseif (is_dir($file)) {
405
            return 'dir';
406
        }
407
408
        $ext = pathinfo($file, PATHINFO_EXTENSION);
409
        return ($ext && file_exists(realpath($this->options['assetBasePath'] . '/Icons/' . $ext . '.png'))) ? $ext : 'default';
0 ignored issues
show
Bug introduced by
Are you sure $ext of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

409
        return ($ext && file_exists(realpath($this->options['assetBasePath'] . '/Icons/' . /** @scrutinizer ignore-type */ $ext . '.png'))) ? $ext : 'default';
Loading history...
410
    }
411
412
    protected function getMimeType($file)
413
    {
414
        return is_dir($file) ? 'text/directory' : Upload::mime($file);
0 ignored issues
show
Bug Best Practice introduced by
The method Upload::mime() is not static, but was called statically. ( Ignorable by Annotation )

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

414
        return is_dir($file) ? 'text/directory' : Upload::/** @scrutinizer ignore-call */ mime($file);
Loading history...
415
    }
416
417
    protected function getDir($dir)
418
    {
419
        $dir = realpath($this->path . '/' . (FileManagerUtility::startsWith($dir, $this->basename) ? $dir : $this->basename));
420
        return $this->checkFile($dir) ? $dir : $this->basedir;
421
    }
422
423
    protected function getPath($file)
424
    {
425
        $file = $this->normalize(substr($file, $this->length));
426
        return substr($file, FileManagerUtility::startsWith($file, '/') ? 1 : 0);
427
    }
428
429
    protected function checkFile($file)
430
    {
431
        $mimes     = $this->getAllowedMimeTypes();
432
        $hasFilter = $this->options['filter'] && count($mimes);
0 ignored issues
show
Bug introduced by
It seems like $mimes can also be of type null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

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

432
        $hasFilter = $this->options['filter'] && count(/** @scrutinizer ignore-type */ $mimes);
Loading history...
433
        if ($hasFilter) {
434
            array_push($mimes, 'text/directory');
0 ignored issues
show
Bug introduced by
It seems like $mimes can also be of type null; however, parameter $array of array_push() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

434
            array_push(/** @scrutinizer ignore-type */ $mimes, 'text/directory');
Loading history...
435
        }
436
        return !(!$file || !FileManagerUtility::startsWith($file, $this->basedir) || !file_exists($file) || ($hasFilter && !in_array($this->getMimeType($file), $mimes)));
437
    }
438
439
    protected function normalize($file)
440
    {
441
        return preg_replace('/\\\|\/{2,}/', '/', $file);
442
    }
443
444
    protected function getAllowedMimeTypes()
445
    {
446
        $filter = $this->options['filter'];
447
448
        if (!$filter) {
449
            return null;
450
        }
451
        if (!FileManagerUtility::endsWith($filter, '/')) {
452
            return [$filter];
453
        }
454
455
        static $mimes;
456
        if (!$mimes) {
457
            $mimes = parse_ini_file($this->options['mimeTypesPath']);
458
        }
459
460
        foreach ($mimes as $mime) {
461
            if (FileManagerUtility::startsWith($mime, $filter)) {
462
                $mimeTypes[] = strtolower($mime);
463
            }
464
        }
465
466
        return $mimeTypes;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mimeTypes does not seem to be defined for all execution paths leading up to this point.
Loading history...
467
    }
468
469
}
470
471
class FileManagerException extends Exception
472
{
473
}
474
475
/* Stripped-down version of some Styx PHP Framework-Functionality bundled with this FileBrowser. Styx is located at: http://styx.og5.net */
476
477
class FileManagerUtility
478
{
479
480
    public static function endsWith($string, $look)
481
    {
482
        return strrpos($string, $look) === strlen($string) - strlen($look);
483
    }
484
485
    public static function startsWith($string, $look)
486
    {
487
        return 0 === strpos($string, $look);
488
    }
489
490
    public static function pagetitle($data, $options = [])
491
    {
492
        static $regex;
493
        if (!$regex) {
494
            $regex = [
495
                explode(
496
                    ' ',
497
                    'Æ æ Œ œ ß Ü ü Ö ö Ä ä À Á Â Ã Ä Å &#260; &#258; Ç &#262; &#268; &#270; &#272; Ð È É Ê Ë &#280; &#282; &#286; Ì Í Î Ï &#304; &#321; &#317; &#313; Ñ &#323; &#327; Ò Ó Ô Õ Ö Ø &#336; &#340; &#344; Š &#346; &#350; &#356; &#354; Ù Ú Û Ü &#366; &#368; Ý Ž &#377; &#379; à á â ã ä å &#261; &#259; ç &#263; &#269; &#271; &#273; è é ê ë &#281; &#283; &#287; ì í î ï &#305; &#322; &#318; &#314; ñ &#324; &#328; ð ò ó ô õ ö ø &#337; &#341; &#345; &#347; š &#351; &#357; &#355; ù ú û ü &#367; &#369; ý ÿ ž &#378; &#380;'
498
                ),
499
                explode(' ', 'Ae ae Oe oe ss Ue ue Oe oe Ae ae A A A A A A A A C C C D D D E E E E E E G I I I I I L L L N N N O O O O O O O R R S S S T T U U U U U U Y Z Z Z a a a a a a a a c c c d d e e e e e e g i i i i i l l l n n n o o o o o o o o r r s s s t t u u u u u u y y z z z'),
500
            ];
501
502
            $regex[0][] = '"';
503
            $regex[0][] = "'";
504
        }
505
506
        $data = trim(substr(preg_replace('/(?:[^A-z0-9]|_|\^)+/i', '_', str_replace($regex[0], $regex[1], $data)), 0, 64), '_');
507
        return !empty($options) ? self::checkTitle($data, $options) : $data;
508
    }
509
510
    protected static function checkTitle($data, $options = [], $i = 0)
511
    {
512
        if (!is_array($options)) {
513
            return $data;
514
        }
515
516
        foreach ($options as $content) {
517
            if ($content && strtolower($content) == strtolower($data . ($i ? '_' . $i : ''))) {
518
                return self::checkTitle($data, $options, ++$i);
519
            }
520
        }
521
522
        return $data . ($i ? '_' . $i : '');
523
    }
524
525
    public static function isBinary($str)
526
    {
527
        $array = [0, 255];
528
        for ($i = 0; $i < strlen($str); $i++) {
529
            if (in_array(ord($str[$i]), $array)) {
530
                return true;
531
            }
532
        }
533
534
        return false;
535
    }
536
537
    public static function getPath()
538
    {
539
        static $path;
540
        return $path ? $path : $path = pathinfo(__FILE__, PATHINFO_DIRNAME);
541
    }
542
543
}
544