Completed
Push — master ( 83cfbe...44719a )
by Julius
08:01 queued 06:21
created

TokenManager::getToken()   F

Complexity

Conditions 17
Paths 195

Size

Total Lines 84

Duplication

Lines 10
Ratio 11.9 %

Code Coverage

Tests 0
CRAP Score 306

Importance

Changes 0
Metric Value
dl 10
loc 84
ccs 0
cts 67
cp 0
rs 3.889
c 0
b 0
f 0
cc 17
nc 195
nop 3
crap 306

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
/**
3
 * @copyright Copyright (c) 2016 Lukas Reschke <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OCA\Richdocuments;
23
24
use OC\Share\Constants;
25
use OCA\Richdocuments\Db\WopiMapper;
26
use OCA\Richdocuments\Helper;
27
use OCA\Richdocuments\Db\Wopi;
28
use OCA\Richdocuments\WOPI\Parser;
29
use OCP\Files\File;
30
use OCP\Files\IRootFolder;
31
use OCP\IURLGenerator;
32
use OCP\Share\IManager;
33
use OCP\IL10N;
34
35
class TokenManager {
36
	/** @var IRootFolder */
37
	private $rootFolder;
38
	/** @var IManager */
39
	private $shareManager;
40
	/** @var IURLGenerator */
41
	private $urlGenerator;
42
	/** @var Parser */
43
	private $wopiParser;
44
	/** @var AppConfig */
45
	private $appConfig;
46
	/** @var string */
47
	private $userId;
48
	/** @var WopiMapper */
49
	private $wopiMapper;
50
	/** @var IL10N */
51
	private $trans;
52
53
	/**
54
	 * @param IRootFolder $rootFolder
55
	 * @param IManager $shareManager
56
	 * @param IURLGenerator $urlGenerator
57
	 * @param Parser $wopiParser
58
	 * @param AppConfig $appConfig
59
	 * @param string $UserId
60
	 * @param WopiMapper $wopiMapper
61
	 * @param IL10N $trans
62
	 */
63
	public function __construct(IRootFolder $rootFolder,
64
								IManager $shareManager,
65
								IURLGenerator $urlGenerator,
66
								Parser $wopiParser,
67
								AppConfig $appConfig,
68
								$UserId,
69
								WopiMapper $wopiMapper,
70
								IL10N $trans) {
71
		$this->rootFolder = $rootFolder;
72
		$this->shareManager = $shareManager;
73
		$this->urlGenerator = $urlGenerator;
74
		$this->wopiParser = $wopiParser;
75
		$this->appConfig = $appConfig;
76
		$this->trans = $trans;
77
		$this->userId = $UserId;
78
		$this->wopiMapper = $wopiMapper;
79
	}
80
81
	/**
82
	 * @param string $fileId
83
	 * @param string $shareToken
84
	 * @param string $editoruid
85
	 * @return array
86
	 * @throws \Exception
87
	 */
88
	public function getToken($fileId, $shareToken = null, $editoruid = null) {
89
		list($fileId,, $version) = Helper::parseFileId($fileId);
90
		$owneruid = null;
91
		// if the user is not logged-in do use the sharers storage
92
		if($shareToken !== null) {
93
			/** @var File $file */
94
			$rootFolder = $this->rootFolder;
95
			$share = $this->shareManager->getShareByToken($shareToken);
96
			$updatable = (bool)($share->getPermissions() & \OCP\Constants::PERMISSION_UPDATE);
97
			$hideDownload = $share->getHideDownload();
98
			$owneruid = $share->getShareOwner();
99
		} else if (!is_null($this->userId)) {
100
			try {
101
				$editoruid = $this->userId;
102
				$rootFolder = $this->rootFolder->getUserFolder($editoruid);
103
104
				$files = $rootFolder->getById((int)$fileId);
105
				$updatable = false;
106
				foreach ($files as $file) {
107
					if ($file->isUpdateable()) {
108
						$updatable = true;
109
						break;
110
					}
111
				}
112
113
				// Check if the editor (user who is accessing) is in editable group
114
				// UserCanWrite only if
115
				// 1. No edit groups are set or
116
				// 2. if they are set, it is in one of the edit groups
117
				$editGroups = array_filter(explode('|', $this->appConfig->getAppValue('edit_groups')));
118 View Code Duplication
				if ($updatable && count($editGroups) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
					$updatable = false;
120
					foreach($editGroups as $editGroup) {
121
						 $editorGroup = \OC::$server->getGroupManager()->get($editGroup);
122
						 if ($editorGroup !== null && sizeof($editorGroup->searchUsers($editoruid)) > 0) {
123
							$updatable = true;
124
							break;
125
						 }
126
					}
127
				}
128
			} catch (\Exception $e) {
129
				throw $e;
130
			}
131
		} else {
132
			// no active user login while generating the token
133
			// this is required during WopiPutRelativeFile
134
			if (is_null($editoruid)) {
135
				\OC::$server->getLogger()->warning('Generating token for SaveAs without editoruid');
136
			}
137
			$rootFolder = $this->rootFolder;
138
			$updatable = true;
139
		}
140
		/** @var File $file */
141
		$file = $rootFolder->getById($fileId)[0];
142
		// If its a public share, use the owner from the share, otherwise check the file object
143
		if (is_null($owneruid)) {
144
			$owner = $file->getOwner();
145
			if (is_null($owner)) {
146
				// Editor UID instead of owner UID in case owner is null e.g. group folders
147
				$owneruid = $editoruid;
148
			} else {
149
				$owneruid = $owner->getUID();
150
			}
151
		}
152
		$serverHost = $this->urlGenerator->getAbsoluteURL('/');//$this->request->getServerProtocol() . '://' . $this->request->getServerHost();
153
154
		if ($this->userId === null && isset($_COOKIE['guestUser'])) {
155
			$guest_name = $this->trans->t('Guest: %s', \OC_Util::sanitizeHTML($_COOKIE['guestUser']));
156
		} else {
157
			$guest_name = NULL;
158
		}
159
160
		$wopi = $this->wopiMapper->generateFileToken($fileId, $owneruid, $editoruid, $version, (int)$updatable, $serverHost, $guest_name, 0, $hideDownload);
0 ignored issues
show
Bug introduced by
The variable $hideDownload 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...
161
162
		try {
163
164
			return [
165
				$this->wopiParser->getUrlSrc($file->getMimeType())['urlsrc'],
166
				$wopi->getToken(),
167
			];
168
		} catch (\Exception $e){
169
			throw $e;
170
		}
171
	}
172
173
	public function getTokenForTemplate(File $file, $userId, $templateDestination) {
174
		$owneruid = $userId;
175
		$editoruid = $userId;
176
		$updatable = $file->isUpdateable();
177
		// Check if the editor (user who is accessing) is in editable group
178
		// UserCanWrite only if
179
		// 1. No edit groups are set or
180
		// 2. if they are set, it is in one of the edit groups
181
		$editGroups = array_filter(explode('|', $this->appConfig->getAppValue('edit_groups')));
182 View Code Duplication
		if ($updatable && count($editGroups) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
			$updatable = false;
184
			foreach($editGroups as $editGroup) {
185
				$editorGroup = \OC::$server->getGroupManager()->get($editGroup);
186
				if ($editorGroup !== null && sizeof($editorGroup->searchUsers($editoruid)) > 0) {
187
					$updatable = true;
188
					break;
189
				}
190
			}
191
		}
192
193
		$serverHost = $this->urlGenerator->getAbsoluteURL('/');
194
195
		$wopi = $this->wopiMapper->generateFileToken($file->getId(), $owneruid, $editoruid, 0, (int)$updatable, $serverHost, null, $templateDestination);
196
197
		return [
198
			$this->wopiParser->getUrlSrc($file->getMimeType())['urlsrc'],
199
			$wopi->getToken(),
200
		];
201
	}
202
}
203