files.php ➔ ls()   F
last analyzed

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 121

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 36
nc 221229
nop 2
dl 0
loc 121
rs 0
c 0
b 0
f 0

How to fix   Long Method    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
if(!function_exists('add_dot')) {
3
    /**
4
     * @param array $array
5
     * @return array
6
     */
7
    function add_dot($array)
8
    {
9
        $count = count($array);
10
        for ($i = 0; $i < $count; $i++) {
11
            $array[$i] = '.' . strtolower(trim($array[$i])); // add a dot :)
12
        }
13
14
        return $array;
15
    }
16
}
17
18 View Code Duplication
if(!function_exists('determineIcon')) {
19
    /**
20
     * @param string $file
21
     * @param string $selFile
22
     * @param string $mode
23
     * @return string
24
     */
25
    function determineIcon($file, $selFile, $mode)
26
    {
27
        $icons = array(
28
            'default' => 'fa fa-file-o',
29
            'edit'    => 'fa fa-pencil-square-o',
30
            'view'    => 'fa fa-eye'
31
        );
32
        $icon = $icons['default'];
33
        if ($file == $selFile) {
34
            $icon = isset($icons[$mode]) ? $icons[$mode] : $icons['default'];
35
        }
36
37
        return '<i class="' . $icon . ' FilesPage"></i>';
38
    }
39
}
40
41 View Code Duplication
if(!function_exists('markRow')) {
42
    /**
43
     * @param string $file
44
     * @param string $selFile
45
     * @param string $mode
46
     * @return string
47
     */
48
    function markRow($file, $selFile, $mode)
49
    {
50
        $classNames = array(
51
            'default' => '',
52
            'edit'    => 'editRow',
53
            'view'    => 'viewRow'
54
        );
55
        if ($file == $selFile) {
56
            $class = isset($classNames[$mode]) ? $classNames[$mode] : $classNames['default'];
57
58
            return ' class="' . $class . '"';
59
        }
60
61
        return '';
62
    }
63
}
64
65
if(!function_exists('ls')) {
66
    /**
67
     * @param string $curpath
68
     * @param array $options
69
     */
70
    function ls($curpath, array $options = [])
71
    {
72
        extract($options, EXTR_OVERWRITE);
73
74
        $_lang = ManagerTheme::getLexicon();
75
        $_style = ManagerTheme::getStyle();
76
        $dircounter = 0;
77
        $filecounter = 0;
78
        $filesizes = 0;
79
        $dirs_array = array();
80
        $files_array = array();
81
        $curpath = str_replace('//', '/', $curpath . '/');
82
83
        if (!is_dir($curpath)) {
84
            echo 'Invalid path "', $curpath, '"<br />';
85
86
            return;
87
        }
88
        $dir = scandir($curpath);
89
90
        // first, get info
91
        foreach ($dir as $file) {
92
            $newpath = $curpath . $file;
93
            if ($file === '..' || $file === '.') {
94
                continue;
95
            }
96
            if (is_dir($newpath)) {
97
                $dirs_array[$dircounter]['dir'] = $newpath;
98
                $dirs_array[$dircounter]['stats'] = lstat($newpath);
99
                if ($file === '..' || $file === '.') {
100
                    continue;
101
                } elseif (!in_array($file, $excludes) && !in_array($newpath, $protected_path)) {
102
                    $dirs_array[$dircounter]['text'] = '<i class="' . $_style['files_folder'] . ' FilesFolder"></i> <a href="index.php?a=31&mode=drill&path=' . urlencode($newpath) . '"><b>' . $file . '</b></a>';
103
104
                    $dfiles = scandir($newpath);
105
                    foreach ($dfiles as $i => $infile) {
106
                        switch ($infile) {
107
                            case '..':
108
                            case '.':
109
                                unset($dfiles[$i]);
110
                                break;
111
                        }
112
                    }
113
                    $file_exists = (0 < count($dfiles)) ? 'file_exists' : '';
114
115
                    $dirs_array[$dircounter]['delete'] = is_writable($curpath) ? '<a href="javascript: deleteFolder(\'' . urlencode($file) . '\',\'' . $file_exists . '\');"><i class="' . $_style['files_delete'] . '" title="' . $_lang['file_delete_folder'] . '"></i></a>' : '';
116
                } else {
117
                    $dirs_array[$dircounter]['text'] = '<span><i class="' . $_style['files_deleted_folder'] . ' FilesDeletedFolder"></i> ' . $file . '</span>';
118
                    $dirs_array[$dircounter]['delete'] = is_writable($curpath) ? '<span class="disabled"><i class="' . $_style['files_delete'] . '" title="' . $_lang['file_delete_folder'] . '"></i></span>' : '';
119
                }
120
121
                $dirs_array[$dircounter]['rename'] = is_writable($curpath) ? '<a href="javascript:renameFolder(\'' . urlencode($file) . '\');"><i class="' . $_style['files_rename'] . '" title="' . $_lang['rename'] . '"></i></a> ' : '';
122
123
                // increment the counter
124
                $dircounter++;
125
            } else {
126
                $type = getExtension($newpath);
127
                $files_array[$filecounter]['file'] = $newpath;
128
                $files_array[$filecounter]['stats'] = lstat($newpath);
129
                $files_array[$filecounter]['text'] = determineIcon($newpath, get_by_key($_REQUEST, 'path', ''), get_by_key($_REQUEST, 'mode', '')) . ' ' . $file;
130
                $files_array[$filecounter]['view'] = (in_array($type,
131
                    $viewablefiles)) ? '<a href="javascript:;" onclick="viewfile(\'' . $webstart_path . substr($newpath,
132
                        $len,
133
                        strlen($newpath)) . '\');"><i class="' . $_style['files_view'] . '" title="' . $_lang['files_viewfile'] . '"></i></a>' : (($enablefiledownload && in_array($type,
134
                        $uploadablefiles)) ? '<a href="' . $webstart_path . implode('/', array_map('rawurlencode',
135
                        explode('/', substr($newpath, $len,
136
                            strlen($newpath))))) . '" style="cursor:pointer;"><i class="' . $_style['files_download'] . '" title="' . $_lang['file_download_file'] . '"></i></a>' : '<span class="disabled"><i class="' . $_style['files_view'] . '" title="' . $_lang['files_viewfile'] . '"></i></span>');
137
                $files_array[$filecounter]['view'] = (in_array($type,
138
                    $inlineviewablefiles)) ? '<a href="index.php?a=31&mode=view&path=' . urlencode($newpath) . '"><i class="' . $_style['files_view'] . '" title="' . $_lang['files_viewfile'] . '"></i></a>' : $files_array[$filecounter]['view'];
139
                $files_array[$filecounter]['unzip'] = ($enablefileunzip && $type == '.zip') ? '<a href="javascript:unzipFile(\'' . urlencode($file) . '\');"><i class="' . $_style['files_unzip'] . '" title="' . $_lang['file_download_unzip'] . '"></i></a>' : '';
140
                $files_array[$filecounter]['edit'] = (in_array($type,
141
                        $editablefiles) && is_writable($curpath) && is_writable($newpath)) ? '<a href="index.php?a=31&mode=edit&path=' . urlencode($newpath) . '#file_editfile"><i class="' . $_style['files_edit'] . '" title="' . $_lang['files_editfile'] . '"></i></a>' : '<span class="disabled"><i class="' . $_style['files_edit'] . '" title="' . $_lang['files_editfile'] . '"></i></span>';
142
                $files_array[$filecounter]['duplicate'] = (in_array($type,
143
                        $editablefiles) && is_writable($curpath) && is_writable($newpath)) ? '<a href="javascript:duplicateFile(\'' . urlencode($file) . '\');"><i class="' . $_style['files_duplicate'] . '" title="' . $_lang['duplicate'] . '"></i></a>' : '<span class="disabled"><i class="' . $_style['files_duplicate'] . '" align="absmiddle" title="' . $_lang['duplicate'] . '"></i></span>';
144
                $files_array[$filecounter]['rename'] = (in_array($type,
145
                        $editablefiles) && is_writable($curpath) && is_writable($newpath)) ? '<a href="javascript:renameFile(\'' . urlencode($file) . '\');"><i class="' . $_style['files_rename'] . '" align="absmiddle" title="' . $_lang['rename'] . '"></i></a>' : '<span class="disabled"><i class="' . $_style['files_rename'] . '" align="absmiddle" title="' . $_lang['rename'] . '"></i></span>';
146
                $files_array[$filecounter]['delete'] = is_writable($curpath) && is_writable($newpath) ? '<a href="javascript:deleteFile(\'' . urlencode($file) . '\');"><i class="' . $_style['files_delete'] . '" title="' . $_lang['file_delete_file'] . '"></i></a>' : '<span class="disabled"><i class="' . $_style['files_delete'] . '" title="' . $_lang['file_delete_file'] . '"></i></span>';
147
148
                // increment the counter
149
                $filecounter++;
150
            }
151
        }
152
153
        // dump array entries for directories
154
        $folders = count($dirs_array);
155
        sort($dirs_array); // sorting the array alphabetically (Thanks pxl8r!)
156
        for ($i = 0; $i < $folders; $i++) {
157
            $filesizes += $dirs_array[$i]['stats']['7'];
158
            echo '<tr>';
159
            echo '<td>' . $dirs_array[$i]['text'] . '</td>';
160
            echo '<td class="text-nowrap">' . evolutionCMS()->toDateFormat($dirs_array[$i]['stats']['9']) . '</td>';
161
            echo '<td class="text-right">' . nicesize($dirs_array[$i]['stats']['7']) . '</td>';
162
            echo '<td class="actions text-right">';
163
            echo $dirs_array[$i]['rename'];
164
            echo $dirs_array[$i]['delete'];
165
            echo '</td>';
166
            echo '</tr>';
167
        }
168
169
        // dump array entries for files
170
        $files = count($files_array);
171
        sort($files_array); // sorting the array alphabetically (Thanks pxl8r!)
172
        for ($i = 0; $i < $files; $i++) {
173
            $filesizes += $files_array[$i]['stats']['7'];
174
            echo '<tr ' . markRow($files_array[$i]['file'], get_by_key($_REQUEST, 'path'), get_by_key($_REQUEST, 'mode')) . '>';
175
            echo '<td>' . $files_array[$i]['text'] . '</td>';
176
            echo '<td class="text-nowrap">' . evolutionCMS()->toDateFormat($files_array[$i]['stats']['9']) . '</td>';
177
            echo '<td class="text-right">' . nicesize($files_array[$i]['stats']['7']) . '</td>';
178
            echo '<td class="actions text-right">';
179
            echo $files_array[$i]['unzip'];
180
            echo $files_array[$i]['view'];
181
            echo $files_array[$i]['edit'];
182
            echo $files_array[$i]['duplicate'];
183
            echo $files_array[$i]['rename'];
184
            echo $files_array[$i]['delete'];
185
            echo '</td>';
186
            echo '</tr>';
187
        }
188
189
        return compact('filesizes', 'files', 'folders');
190
    }
191
}
192
193 View Code Duplication
if(!function_exists('removeLastPath')) {
194
    /**
195
     * @param string $string
196
     * @return bool|string
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
197
     */
198
    function removeLastPath($string)
199
    {
200
        $pos = strrpos($string, '/');
201
        if ($pos !== false) {
202
            $path = substr($string, 0, $pos);
203
        } else {
204
            $path = false;
205
        }
206
207
        return $path;
208
    }
209
}
210
211 View Code Duplication
if(!function_exists('getExtension')) {
212
    /**
213
     * @param string $string
214
     * @return bool|string
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
215
     *
216
     * @TODO: not work if $string contains folder name with dot
217
     */
218
    function getExtension($string)
219
    {
220
        $pos = strrpos($string, '.');
221
        if ($pos !== false) {
222
            $ext = substr($string, $pos);
223
            $ext = strtolower($ext);
224
        } else {
225
            $ext = false;
226
        }
227
228
        return $ext;
229
    }
230
}
231
232
if(!function_exists('checkExtension')) {
233
    /**
234
     * @param string $path
235
     * @return bool
236
     */
237
    function checkExtension($path = '')
238
    {
239
        global $uploadablefiles;
240
241
        if (in_array(getExtension($path), $uploadablefiles)) {
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return in_array(getExten...th), $uploadablefiles);.
Loading history...
242
            return true;
243
        } else {
244
            return false;
245
        }
246
    }
247
}
248
249
if(!function_exists('mkdirs')) {
250
    /**
251
     * recursive mkdir function
252
     *
253
     * @param string $strPath
254
     * @param int $mode
255
     * @return bool
256
     */
257
    function mkdirs($strPath, $mode)
258
    {
259
        if (is_dir($strPath)) {
260
            return true;
261
        }
262
        $pStrPath = dirname($strPath);
263
        if (!mkdirs($pStrPath, $mode)) {
264
            return false;
265
        }
266
267
        return @mkdir($strPath);
268
    }
269
}
270
271
if(!function_exists('logFileChange')) {
272
    /**
273
     * @param string $type
274
     * @param string $filename
275
     */
276
    function logFileChange($type, $filename)
277
    {
278
        //global $_lang;
279
280
        $log = new EvolutionCMS\Legacy\LogHandler();
281
282
        switch ($type) {
283
            case 'upload':
284
                $string = 'Uploaded File';
285
                break;
286
            case 'delete':
287
                $string = 'Deleted File';
288
                break;
289
            case 'modify':
290
                $string = 'Modified File';
291
                break;
292
            default:
293
                $string = 'Viewing File';
294
                break;
295
        }
296
297
        $string = sprintf($string, $filename);
298
        $log->initAndWriteLog($string, '', '', '', $type, $filename);
299
300
        // HACK: change the global action to prevent double logging
301
        // @see index.php @ 915
302
        global $action;
303
        $action = 1;
304
    }
305
}
306
307
if(!function_exists('unzip')) {
308
    /**
309
     * by patrick_allaert - php user notes
310
     *
311
     * @param string $file
312
     * @param string $path
313
     * @return bool|int
314
     */
315
    function unzip($file, $path)
316
    {
317
        global $newfolderaccessmode, $token_check;
318
319
        if (!$token_check) {
320
            return false;
321
        }
322
323
        // added by Raymond
324
        if (!extension_loaded('zip')) {
325
            return 0;
326
        }
327
        // end mod
328
        $zip = zip_open($file);
329
        if ($zip) {
330
            $old_umask = umask(0);
331
            $path = rtrim($path, '/') . '/';
332
            while ($zip_entry = zip_read($zip)) {
333
                if (zip_entry_filesize($zip_entry) > 0) {
334
                    // str_replace must be used under windows to convert "/" into "\"
335
                    $zip_entry_name = zip_entry_name($zip_entry);
336
                    $complete_path = $path . str_replace('\\', '/', dirname($zip_entry_name));
337
                    $complete_name = $path . str_replace('\\', '/', $zip_entry_name);
338
                    if (!file_exists($complete_path)) {
339
                        $tmp = '';
340
                        foreach (explode('/', $complete_path) AS $k) {
341
                            $tmp .= $k . '/';
342
                            if (!is_dir($tmp)) {
343
                                mkdir($tmp, 0777);
344
                            }
345
                        }
346
                    }
347
                    if (zip_entry_open($zip, $zip_entry, 'r')) {
348
                        file_put_contents($complete_name, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
349
                        zip_entry_close($zip_entry);
350
                    }
351
                }
352
            }
353
            umask($old_umask);
354
            zip_close($zip);
355
356
            return true;
357
        }
358
        zip_close($zip);
359
    }
360
}
361
362
if(!function_exists('rrmdir')) {
363
    /**
364
     * @param string $dir
365
     * @return bool
366
     */
367
    function rrmdir($dir)
368
    {
369
        foreach (glob($dir . '/*') as $file) {
370
            if (is_dir($file)) {
371
                rrmdir($file);
372
            } else {
373
                unlink($file);
374
            }
375
        }
376
377
        return rmdir($dir);
378
    }
379
}
380
381
if(!function_exists('fileupload')) {
382
    /**
383
     * @return string
384
     */
385
    function fileupload()
386
    {
387
        $modx = evolutionCMS();
388
        global $_lang, $startpath, $filemanager_path, $uploadablefiles, $new_file_permissions;
389
        $msg = '';
390
        foreach ($_FILES['userfile']['name'] as $i => $name) {
391
            if (empty($_FILES['userfile']['tmp_name'][$i])) {
392
                continue;
393
            }
394
            $userfile = array();
395
396
            $userfile['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
397
            $userfile['error'] = $_FILES['userfile']['error'][$i];
398
            $name = $_FILES['userfile']['name'][$i];
399
            if ($modx->getConfig('clean_uploaded_filename') == 1) {
400
                $nameparts = explode('.', $name);
401
                $nameparts = array_map(array(
402
                    $modx,
403
                    'stripAlias'
404
                ), $nameparts, array('file_manager'));
405
                $name = implode('.', $nameparts);
406
            }
407
            $userfile['name'] = $name;
408
            $userfile['type'] = $_FILES['userfile']['type'][$i];
409
410
            // this seems to be an upload action.
411
            $path = MODX_SITE_URL . substr($startpath, strlen($filemanager_path), strlen($startpath));
412
            $path = rtrim($path, '/') . '/' . $userfile['name'];
413
            $msg .= $path;
414
            if ($userfile['error'] == 0) {
415
                $img = (strpos($userfile['type'],
416
                        'image') !== false) ? '<br /><img src="' . $path . '" height="75" />' : '';
417
                $msg .= "<p>" . $_lang['files_file_type'] . $userfile['type'] . ", " . nicesize(filesize($userfile['tmp_name'])) . $img . '</p>';
418
            }
419
420
            $userfilename = $userfile['tmp_name'];
421
422
            if (is_uploaded_file($userfilename)) {
423
                // file is uploaded file, process it!
424
                if (!checkExtension($userfile['name'])) {
425
                    $msg .= '<p><span class="warning">' . $_lang['files_filetype_notok'] . '</span></p>';
426
                } else {
427
                    if (@move_uploaded_file($userfile['tmp_name'], $_POST['path'] . '/' . $userfile['name'])) {
428
                        // Ryan: Repair broken permissions issue with file manager
429
                        if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') {
430
                            @chmod($_POST['path'] . "/" . $userfile['name'], $new_file_permissions);
431
                        }
432
                        // Ryan: End
433
                        $msg .= '<p><span class="success">' . $_lang['files_upload_ok'] . '</span></p><hr/>';
434
435
                        // invoke OnFileManagerUpload event
436
                        $modx->invokeEvent('OnFileManagerUpload', array(
437
                            'filepath' => $_POST['path'],
438
                            'filename' => $userfile['name']
439
                        ));
440
                        // Log the change
441
                        logFileChange('upload', $_POST['path'] . '/' . $userfile['name']);
442
                    } else {
443
                        $msg .= '<p><span class="warning">' . $_lang['files_upload_copyfailed'] . '</span> ' . $_lang["files_upload_permissions_error"] . '</p>';
444
                    }
445
                }
446
            } else {
447
                $msg .= '<br /><span class="warning"><b>' . $_lang['files_upload_error'] . ':</b>';
448
                switch ($userfile['error']) {
449
                    case 0: //no error; possible file attack!
450
                        $msg .= $_lang['files_upload_error0'];
451
                        break;
452
                    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
453
                        $msg .= $_lang['files_upload_error1'];
454
                        break;
455
                    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
456
                        $msg .= $_lang['files_upload_error2'];
457
                        break;
458
                    case 3: //uploaded file was only partially uploaded
459
                        $msg .= $_lang['files_upload_error3'];
460
                        break;
461
                    case 4: //no file was uploaded
462
                        $msg .= $_lang['files_upload_error4'];
463
                        break;
464
                    default: //a default error, just in case!  :)
465
                        $msg .= $_lang['files_upload_error5'];
466
                        break;
467
                }
468
                $msg .= '</span><br />';
469
            }
470
        }
471
472
        return $msg . '<br/>';
473
    }
474
}
475
476
if(!function_exists('textsave')) {
477
    /**
478
     * @return string
479
     */
480
    function textsave()
481
    {
482
        global $_lang;
483
484
        $msg = $_lang['editing_file'];
485
        $filename = $_POST['path'];
486
        $content = $_POST['content'];
487
488
        // Write $content to our opened file.
489
        if (file_put_contents($filename, $content) === false) {
490
            $msg .= '<span class="warning"><b>' . $_lang['file_not_saved'] . '</b></span><br /><br />';
491
        } else {
492
            $msg .= '<span class="success"><b>' . $_lang['file_saved'] . '</b></span><br /><br />';
493
            $_REQUEST['mode'] = 'edit';
494
        }
495
        // Log the change
496
        logFileChange('modify', $filename);
497
498
        return $msg;
499
    }
500
}
501
502
if(!function_exists('delete_file')) {
503
    /**
504
     * @return string
505
     */
506
    function delete_file()
507
    {
508
        global $_lang, $token_check;
509
510
        $msg = sprintf($_lang['deleting_file'], str_replace('\\', '/', $_REQUEST['path']));
511
512
        $file = $_REQUEST['path'];
513
        if (!$token_check || !@unlink($file)) {
514
            $msg .= '<span class="warning"><b>' . $_lang['file_not_deleted'] . '</b></span><br /><br />';
515
        } else {
516
            $msg .= '<span class="success"><b>' . $_lang['file_deleted'] . '</b></span><br /><br />';
517
        }
518
519
        // Log the change
520
        logFileChange('delete', $file);
521
522
        return $msg;
523
    }
524
}
525
526 View Code Duplication
if(!function_exists('parsePlaceholder')) {
527
    /**
528
     * @param string $tpl
529
     * @param array $ph
530
     * @return string
531
     */
532
    function parsePlaceholder($tpl, $ph)
0 ignored issues
show
Best Practice introduced by
The function parsePlaceholder() has been defined more than once; this definition is ignored, only the first definition in core/functions/actions/bkmanager.php (L131-143) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
533
    {
534
        foreach ($ph as $k => $v) {
535
            $k = "[+{$k}+]";
536
            $tpl = str_replace($k, $v, $tpl);
537
        }
538
539
        return $tpl;
540
    }
541
}
542
543
if(!function_exists('checkToken')) {
544
    /**
545
     * @return bool
546
     */
547
    function checkToken()
548
    {
549
        if (isset($_POST['token']) && !empty($_POST['token'])) {
550
            $token = $_POST['token'];
551
        } elseif (isset($_GET['token']) && !empty($_GET['token'])) {
552
            $token = $_GET['token'];
553
        } else {
554
            $token = false;
555
        }
556
557
        if (isset($_SESSION['token']) && !empty($_SESSION['token']) && $_SESSION['token'] === $token) {
558
            $rs = true;
559
        } else {
560
            $rs = false;
561
        }
562
        $_SESSION['token'] = '';
563
564
        return $rs;
565
    }
566
}
567
568
if(!function_exists('makeToken')) {
569
    /**
570
     * @return string
571
     */
572
    function makeToken()
573
    {
574
        $newToken = uniqid('');
575
        $_SESSION['token'] = $newToken;
576
577
        return $newToken;
578
    }
579
}
580