Completed
Push — master ( 6c3409...142a85 )
by Andras
05:48 queued 03:09
created

DocumentController::publicPage()   B

Complexity

Conditions 7
Paths 44

Size

Total Lines 55
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 55
ccs 0
cts 51
cp 0
rs 7.8235
cc 7
eloc 42
nc 44
nop 2
crap 56

How to fix   Long Method   

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
 * ownCloud - Richdocuments App
4
 *
5
 * @author Victor Dubiniuk
6
 * @copyright 2014 Victor Dubiniuk [email protected]
7
 *
8
 * This file is licensed under the Affero General Public License version 3 or
9
 * later.
10
 */
11
12
namespace OCA\Richdocuments\Controller;
13
14
use OCA\Richdocuments\TokenManager;
15
use OCA\Richdocuments\WOPI\Parser;
16
use \OCP\AppFramework\Controller;
17
use OCP\AppFramework\Http\JSONResponse;
18
use OCP\Files\Folder;
19
use OCP\Files\IRootFolder;
20
use OCP\Files\Node;
21
use \OCP\IRequest;
22
use \OCP\IConfig;
23
use \OCP\IL10N;
24
use \OCP\ILogger;
25
use \OCP\AppFramework\Http\ContentSecurityPolicy;
26
use \OCP\AppFramework\Http\TemplateResponse;
27
use \OCA\Richdocuments\AppConfig;
28
use \OCA\Richdocuments\Helper;
29
use \OC\Files\View;
30
use OCP\ISession;
31
use OCP\Share\IManager;
32
33
class DocumentController extends Controller {
34
	/** @var string */
35
	private $uid;
36
	/** @var IL10N */
37
	private $l10n;
38
	/** @var IConfig */
39
	private $settings;
40
	/** @var AppConfig */
41
	private $appConfig;
42
	/** @var ILogger */
43
	private $logger;
44
	/** @var Parser */
45
	private $wopiParser;
46
	/** @var IManager */
47
	private $shareManager;
48
	/** @var TokenManager */
49
	private $tokenManager;
50
	/** @var ISession */
51
	private $session;
52
	/** @var IRootFolder */
53
	private $rootFolder;
54
55
	const ODT_TEMPLATE_PATH = '/assets/odttemplate.odt';
56
57
	/**
58
	 * @param string $appName
59
	 * @param IRequest $request
60
	 * @param IConfig $settings
61
	 * @param AppConfig $appConfig
62
	 * @param IL10N $l10n
63
	 * @param Parser $wopiParser
64
	 * @param IManager $shareManager
65
	 * @param TokenManager $tokenManager
66
	 * @param IRootFolder $rootFolder
67
	 * @param ISession $session
68
	 * @param string $UserId
69
	 */
70
	public function __construct($appName,
71
								IRequest $request,
72
								IConfig $settings,
73
								AppConfig $appConfig,
74
								IL10N $l10n,
75
								Parser $wopiParser,
76
								IManager $shareManager,
77
								TokenManager $tokenManager,
78
								IRootFolder $rootFolder,
79
								ISession $session,
80
								$UserId,
81
								ILogger $logger) {
82
		parent::__construct($appName, $request);
83
		$this->uid = $UserId;
84
		$this->l10n = $l10n;
85
		$this->settings = $settings;
86
		$this->appConfig = $appConfig;
87
		$this->wopiParser = $wopiParser;
88
		$this->shareManager = $shareManager;
89
		$this->tokenManager = $tokenManager;
90
		$this->rootFolder = $rootFolder;
91
		$this->session = $session;
92
		$this->logger = $logger;
93
	}
94
95
	/**
96
	 * @NoAdminRequired
97
	 *
98
	 * @param string $fileId
99
	 * @return TemplateResponse
100
	 */
101
	public function index($fileId) {
102
		try {
103
			$folder = $this->rootFolder->getUserFolder($this->uid);
104
			$item = $folder->getById($fileId)[0];
105
			if(!($item instanceof Node)) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Node does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
106
				throw new \Exception();
107
			}
108
			list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
109
			$params = [
110
				'permissions' => $item->getPermissions(),
111
				'title' => $item->getName(),
112
				'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
113
				'token' => $token,
114
				'urlsrc' => $urlSrc,
115
				'path' => $folder->getRelativePath($item->getPath()),
116
				'instanceId' => $this->settings->getSystemValue('instanceid'),
117
			];
118
119
			// Update the current file to be accessible with system public shared key
120
			$owner = $item->getOwner()->getUID();
121
			$absPath = '/' . $owner . '/' .  $item->getInternalPath();
122
			$accessList = \OC::$server->getEncryptionFilesHelper()->getAccessList($absPath);
123
			$accessList['public'] = true;
124
			\OC::$server->getEncryptionManager()->getEncryptionModule()->update($absPath, $owner, $accessList);
125
126
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
127
			$policy = new ContentSecurityPolicy();
128
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
129
			$policy->allowInlineScript(true);
130
			$response->setContentSecurityPolicy($policy);
131
			return $response;
132
		} catch (\Exception $e) {
133
			$this->logger->logException($e, ['app'=>'richdocuments']);
134
			$params = [
135
				'remoteAddr' => $this->request->getRemoteAddress(),
136
				'requestID' => $this->request->getId(),
137
				'debugMode' => $this->settings->getSystemValue('debug'),
138
				'errorClass' => get_class($e),
139
				'errorCode' => $e->getCode(),
140
				'errorMsg' => $e->getMessage(),
141
				'file' => $e->getFile(),
142
				'line' => $e->getLine(),
143
				'trace' => $e->getTraceAsString()
144
			];
145
			return new TemplateResponse('core', 'exception', $params, 'guest');
146
		}
147
148
		return new TemplateResponse('core', '403', [], 'guest');
0 ignored issues
show
Unused Code introduced by
return new \OCP\AppFrame...03', array(), 'guest'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
149
	}
150
151
	/**
152
	 * @PublicPage
153
	 *
154
	 * @param string $shareToken
155
	 * @param string $fileName
156
	 * @return TemplateResponse
157
	 * @throws \Exception
158
	 */
159
	public function publicPage($shareToken, $fileName) {
160
		try {
161
			$share = $this->shareManager->getShareByToken($shareToken);
162
			// not authenticated ?
163
			if($share->getPassword()){
164
				if (!$this->session->exists('public_link_authenticated')
165
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
166
				) {
167
					throw new \Exception('Invalid password');
168
				}
169
			}
170
171
			$node = $share->getNode();
172
			if($node instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
173
				$item = $node->get($fileName);
174
			} else {
175
				$item = $node;
176
			}
177
			if ($item instanceof Node) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Node does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
178
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
179
				$params = [
180
					'permissions' => $share->getPermissions(),
181
					'title' => $item->getName(),
182
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
183
					'token' => $token,
184
					'urlsrc' => $urlSrc,
185
					'path' => '/',
186
					'instanceId' => $this->settings->getSystemValue('instanceid'),
187
				];
188
189
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
190
				$policy = new ContentSecurityPolicy();
191
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
192
				$policy->allowInlineScript(true);
193
				$response->setContentSecurityPolicy($policy);
194
				return $response;
195
			}
196
		} catch (\Exception $e) {
197
			$this->logger->logException($e, ['app'=>'richdocuments']);
198
			$params = [
199
				'remoteAddr' => $this->request->getRemoteAddress(),
200
				'requestID' => $this->request->getId(),
201
				'debugMode' => $this->settings->getSystemValue('debug'),
202
				'errorClass' => get_class($e),
203
				'errorCode' => $e->getCode(),
204
				'errorMsg' => $e->getMessage(),
205
				'file' => $e->getFile(),
206
				'line' => $e->getLine(),
207
				'trace' => $e->getTraceAsString()
208
			];
209
			return new TemplateResponse('core', 'exception', $params, 'guest');
210
		}
211
212
		return new TemplateResponse('core', '403', [], 'guest');
213
	}
214
215
	/**
216
	 * @NoAdminRequired
217
	 *
218
	 * @param string $mimetype
219
	 * @param string $filename
220
	 * @param string $dir
221
	 * @return JSONResponse
222
	 */
223
	public function create($mimetype,
224
						   $filename,
225
						   $dir){
226
227
		$view = new View('/' . $this->uid . '/files');
228
		if (!$dir){
229
			$dir = '/';
230
		}
231
232
		$basename = $this->l10n->t('New Document.odt');
233
		switch ($mimetype) {
234
			case 'application/vnd.oasis.opendocument.spreadsheet':
235
				$basename = $this->l10n->t('New Spreadsheet.ods');
236
				break;
237
			case 'application/vnd.oasis.opendocument.presentation':
238
				$basename = $this->l10n->t('New Presentation.odp');
239
				break;
240
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
241
				$basename = $this->l10n->t('New Document.docx');
242
				break;
243
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
244
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
245
				break;
246
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
247
				$basename = $this->l10n->t('New Presentation.pptx');
248
				break;
249
			default:
250
				// to be safe
251
				$mimetype = 'application/vnd.oasis.opendocument.text';
252
				break;
253
		}
254
255
		if (!$filename){
256
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
257
		} else {
258
			$path = $dir . '/' . $filename;
259
		}
260
261
		$content = '';
262
		if (class_exists('\OC\Files\Type\TemplateManager')){
263
			$manager = \OC_Helper::getFileTemplateManager();
264
			$content = $manager->getTemplate($mimetype);
265
		}
266
267
		if (!$content){
268
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
269
		}
270
271
		if ($content && $view->file_put_contents($path, $content)) {
272
			$info = $view->getFileInfo($path);
273
			$ret = $this->wopiParser->getUrlSrc($mimetype);
0 ignored issues
show
Unused Code introduced by
$ret is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
274
			$response =  array(
275
				'status' => 'success',
276
				'data' => \OCA\Files\Helper::formatFileInfo($info)
277
			);
278
		} else {
279
			$response =  array(
280
				'status' => 'error',
281
				'message' => (string) $this->l10n->t('Can\'t create document')
282
			);
283
		}
284
285
		return $response;
286
	}
287
}
288