Completed
Push — stable8.2 ( 2a29d7...300953 )
by Morris
94:00
created

Helper   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 98
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 71.21%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 19
c 1
b 0
f 0
lcom 0
cbo 6
dl 0
loc 98
ccs 47
cts 66
cp 0.7121
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A formatFileInfos() 0 12 2
C getTrashFiles() 0 68 17
1
<?php
2
/**
3
 * @author Björn Schießle <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Jörn Friedrich Dreyer <[email protected]>
6
 * @author Robin Appelman <[email protected]>
7
 * @author Robin McCorkell <[email protected]>
8
 * @author Roeland Jago Douma <[email protected]>
9
 * @author Vincent Petry <[email protected]>
10
 *
11
 * @copyright Copyright (c) 2015, ownCloud, Inc.
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
25
 *
26
 */
27
namespace OCA\Files_Trashbin;
28
29
use OC\Files\FileInfo;
30
use OCP\Constants;
31
32
class Helper
33
{
34
	/**
35
	 * Retrieves the contents of a trash bin directory.
36
	 *
37
	 * @param string $dir path to the directory inside the trashbin
38
	 * or empty to retrieve the root of the trashbin
39
	 * @param string $user
40
	 * @param string $sortAttribute attribute to sort on or empty to disable sorting
41
	 * @param bool $sortDescending true for descending sort, false otherwise
42
	 * @return \OCP\Files\FileInfo[]
43
	 */
44 12
	public static function getTrashFiles($dir, $user, $sortAttribute = '', $sortDescending = false){
45 12
		$result = array();
46 12
		$timestamp = null;
47
48 12
		$view = new \OC\Files\View('/' . $user . '/files_trashbin/files');
49
50 12
		if (ltrim($dir, '/') !== '' && !$view->is_dir($dir)) {
51
			throw new \Exception('Directory does not exists');
52
		}
53
54 12
		$dirContent = $view->opendir($dir);
55 12
		if ($dirContent === false) {
56
			return $result;
57
		}
58
59 12
		$mount = $view->getMount($dir);
60 12
		$storage = $mount->getStorage();
61 12
		$absoluteDir = $view->getAbsolutePath($dir);
62 12
		$internalPath = $mount->getInternalPath($absoluteDir);
63
64 12
		if (is_resource($dirContent)) {
65 12
			$originalLocations = \OCA\Files_Trashbin\Trashbin::getLocations($user);
66 12
			while (($entryName = readdir($dirContent)) !== false) {
67 12
				if (!\OC\Files\Filesystem::isIgnoredDir($entryName)) {
68 12
					$id = $entryName;
69 12
					if ($dir === '' || $dir === '/') {
70 12
						$size = $view->filesize($id);
71 12
						$pathparts = pathinfo($entryName);
72 12
						$timestamp = substr($pathparts['extension'], 1);
73 12
						$id = $pathparts['filename'];
74
75 12
					} else if ($timestamp === null) {
76
						// for subfolders we need to calculate the timestamp only once
77
						$size = $view->filesize($dir . '/' . $id);
78
						$parts = explode('/', ltrim($dir, '/'));
79
						$timestamp = substr(pathinfo($parts[0], PATHINFO_EXTENSION), 1);
80
					}
81 12
					$originalPath = '';
82 12
					if (isset($originalLocations[$id][$timestamp])) {
83 12
						$originalPath = $originalLocations[$id][$timestamp];
84 12
						if (substr($originalPath, -1) === '/') {
85
							$originalPath = substr($originalPath, 0, -1);
86
						}
87 12
					}
88
					$i = array(
89 12
						'name' => $id,
90 12
						'mtime' => $timestamp,
91 12
						'mimetype' => $view->is_dir($dir . '/' . $entryName) ? 'httpd/unix-directory' : \OC_Helper::getFileNameMimeType($id),
92 12
						'type' => $view->is_dir($dir . '/' . $entryName) ? 'dir' : 'file',
93 12
						'directory' => ($dir === '/') ? '' : $dir,
94 12
						'size' => $size,
0 ignored issues
show
Bug introduced by
The variable $size does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
95 12
						'etag' => '',
96 12
						'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE
97 12
					);
98 12
					if ($originalPath) {
99 12
						$i['extraData'] = $originalPath.'/'.$id;
100 12
					}
101 12
					$result[] = new FileInfo($absoluteDir . '/' . $i['name'], $storage, $internalPath . '/' . $i['name'], $i, $mount);
0 ignored issues
show
Bug introduced by
It seems like $mount defined by $view->getMount($dir) on line 59 can be null; however, OC\Files\FileInfo::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
102 12
				}
103 12
			}
104 12
			closedir($dirContent);
105 12
		}
106
107 12
		if ($sortAttribute !== '') {
108 11
			return \OCA\Files\Helper::sortFiles($result, $sortAttribute, $sortDescending);
109
		}
110 4
		return $result;
111
	}
112
113
	/**
114
	 * Format file infos for JSON
115
	 * @param \OCP\Files\FileInfo[] $fileInfos file infos
116
	 */
117
	public static function formatFileInfos($fileInfos) {
118
		$files = array();
119
		$id = 0;
120
		foreach ($fileInfos as $i) {
121
			$entry = \OCA\Files\Helper::formatFileInfo($i);
122
			$entry['id'] = $id++;
123
			$entry['etag'] = $entry['mtime']; // add fake etag, it is only needed to identify the preview image
124
			$entry['permissions'] = \OCP\Constants::PERMISSION_READ;
125
			$files[] = $entry;
126
		}
127
		return $files;
128
	}
129
}
130