Completed
Push — master ( d80a97...21504e )
by Andras
01:47
created

DocumentController   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 319
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 30
c 5
b 0
f 0
lcom 1
cbo 4
dl 0
loc 319
ccs 0
cts 227
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 24 1
B extAppGetData() 0 48 6
B index() 0 53 4
B publicPage() 0 55 7
C create() 0 64 12
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
	 * @PublicPage
97
	 * @NoCSRFRequired
98
	 *
99
	 * Returns the access_token and urlsrc for WOPI access for given $fileId
100
	 * Requests is accepted only when a secret_token is provided set by admin in
101
	 * settings page
102
	 *
103
	 * @param string $fileId
104
	 * @return access_token, urlsrc
0 ignored issues
show
Documentation introduced by
The doc-type access_token, could not be parsed: Expected "|" or "end of type", but got "," at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
105
	 */
106
	public function extAppGetData($fileId) {
107
		$secretToken = $this->request->getParam('secret_token');
108
		$apps = array_filter(explode(',', $this->appConfig->getAppValue('external_apps')));
109
		foreach($apps as $app) {
110
			if ($app !== '') {
111
				if ($secretToken === $app) {
112
					$appName = explode(':', $app);
113
					\OC::$server->getLogger()->debug('External app "{extApp}" authenticated; issuing access token for fileId {fileId}', [
114
						'app' => $this->appName,
115
						'extApp' => $appName[0],
116
						'fileId' => $fileId
117
					]);
118
					try {
119
						$folder = $this->rootFolder->getUserFolder($this->uid);
120
						$item = $folder->getById($fileId)[0];
121
						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...
122
							throw new \Exception();
123
						}
124
						list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
125
						return array(
126
							'status' => 'success',
127
							'urlsrc' => $urlSrc,
128
							'token' => $token
129
						);
130
					} catch (\Exception $e) {
131
						$this->logger->logException($e, ['app'=>'richdocuments']);
132
						$params = [
133
							'remoteAddr' => $this->request->getRemoteAddress(),
134
							'requestID' => $this->request->getId(),
135
							'debugMode' => $this->settings->getSystemValue('debug'),
136
							'errorClass' => get_class($e),
137
							'errorCode' => $e->getCode(),
138
							'errorMsg' => $e->getMessage(),
139
							'file' => $e->getFile(),
140
							'line' => $e->getLine(),
141
							'trace' => $e->getTraceAsString()
142
						];
143
						return new TemplateResponse('core', 'exception', $params, 'guest');
144
					}
145
				}
146
			}
147
148
			return array(
149
				'status' => 'error',
150
				'message' => 'Permission denied'
151
			);
152
		}
153
	}
154
155
	/**
156
	 * @NoAdminRequired
157
	 *
158
	 * @param string $fileId
159
	 * @return TemplateResponse
160
	 */
161
	public function index($fileId) {
162
		try {
163
			$folder = $this->rootFolder->getUserFolder($this->uid);
164
			$item = $folder->getById($fileId)[0];
165
			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...
166
				throw new \Exception();
167
			}
168
			list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
169
			$params = [
170
				'permissions' => $item->getPermissions(),
171
				'title' => $item->getName(),
172
				'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
173
				'token' => $token,
174
				'urlsrc' => $urlSrc,
175
				'path' => $folder->getRelativePath($item->getPath()),
176
				'instanceId' => $this->settings->getSystemValue('instanceid'),
177
			];
178
179
			$encryptionManager = \OC::$server->getEncryptionManager();
180
			if ($encryptionManager->isEnabled())
181
			{
182
				// Update the current file to be accessible with system public shared key
183
				$owner = $item->getOwner()->getUID();
184
				$absPath = '/' . $owner . '/' .  $item->getInternalPath();
185
				$accessList = \OC::$server->getEncryptionFilesHelper()->getAccessList($absPath);
186
				$accessList['public'] = true;
187
				$encryptionManager->getEncryptionModule()->update($absPath, $owner, $accessList);
188
			}
189
190
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
191
			$policy = new ContentSecurityPolicy();
192
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
193
			$policy->allowInlineScript(true);
194
			$response->setContentSecurityPolicy($policy);
195
			return $response;
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');
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...
213
	}
214
215
	/**
216
	 * @PublicPage
217
	 *
218
	 * @param string $shareToken
219
	 * @param string $fileName
220
	 * @return TemplateResponse
221
	 * @throws \Exception
222
	 */
223
	public function publicPage($shareToken, $fileName, $fileId) {
224
		try {
225
			$share = $this->shareManager->getShareByToken($shareToken);
226
			// not authenticated ?
227
			if($share->getPassword()){
228
				if (!$this->session->exists('public_link_authenticated')
229
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
230
				) {
231
					throw new \Exception('Invalid password');
232
				}
233
			}
234
235
			$node = $share->getNode();
236
			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...
237
				$item = $node->getById($fileId)[0];
238
			} else {
239
				$item = $node;
240
			}
241
			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...
242
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
243
				$params = [
244
					'permissions' => $share->getPermissions(),
245
					'title' => $item->getName(),
246
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
247
					'token' => $token,
248
					'urlsrc' => $urlSrc,
249
					'path' => '/',
250
					'instanceId' => $this->settings->getSystemValue('instanceid'),
251
				];
252
253
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
254
				$policy = new ContentSecurityPolicy();
255
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
256
				$policy->allowInlineScript(true);
257
				$response->setContentSecurityPolicy($policy);
258
				return $response;
259
			}
260
		} catch (\Exception $e) {
261
			$this->logger->logException($e, ['app'=>'richdocuments']);
262
			$params = [
263
				'remoteAddr' => $this->request->getRemoteAddress(),
264
				'requestID' => $this->request->getId(),
265
				'debugMode' => $this->settings->getSystemValue('debug'),
266
				'errorClass' => get_class($e),
267
				'errorCode' => $e->getCode(),
268
				'errorMsg' => $e->getMessage(),
269
				'file' => $e->getFile(),
270
				'line' => $e->getLine(),
271
				'trace' => $e->getTraceAsString()
272
			];
273
			return new TemplateResponse('core', 'exception', $params, 'guest');
274
		}
275
276
		return new TemplateResponse('core', '403', [], 'guest');
277
	}
278
279
	/**
280
	 * @NoAdminRequired
281
	 *
282
	 * @param string $mimetype
283
	 * @param string $filename
284
	 * @param string $dir
285
	 * @return JSONResponse
286
	 */
287
	public function create($mimetype,
288
						   $filename,
289
						   $dir){
290
291
		$view = new View('/' . $this->uid . '/files');
292
		if (!$dir){
293
			$dir = '/';
294
		}
295
296
		$basename = $this->l10n->t('New Document.odt');
297
		switch ($mimetype) {
298
			case 'application/vnd.oasis.opendocument.spreadsheet':
299
				$basename = $this->l10n->t('New Spreadsheet.ods');
300
				break;
301
			case 'application/vnd.oasis.opendocument.presentation':
302
				$basename = $this->l10n->t('New Presentation.odp');
303
				break;
304
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
305
				$basename = $this->l10n->t('New Document.docx');
306
				break;
307
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
308
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
309
				break;
310
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
311
				$basename = $this->l10n->t('New Presentation.pptx');
312
				break;
313
			default:
314
				// to be safe
315
				$mimetype = 'application/vnd.oasis.opendocument.text';
316
				break;
317
		}
318
319
		if (!$filename){
320
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
321
		} else {
322
			$path = $dir . '/' . $filename;
323
		}
324
325
		$content = '';
326
		if (class_exists('\OC\Files\Type\TemplateManager')){
327
			$manager = \OC_Helper::getFileTemplateManager();
328
			$content = $manager->getTemplate($mimetype);
329
		}
330
331
		if (!$content){
332
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
333
		}
334
335
		if ($content && $view->file_put_contents($path, $content)) {
336
			$info = $view->getFileInfo($path);
337
			$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...
338
			$response =  array(
339
				'status' => 'success',
340
				'data' => \OCA\Files\Helper::formatFileInfo($info)
341
			);
342
		} else {
343
			$response =  array(
344
				'status' => 'error',
345
				'message' => (string) $this->l10n->t('Can\'t create document')
346
			);
347
		}
348
349
		return $response;
350
	}
351
}
352