Completed
Push — master ( 35e246...47ce01 )
by Andras
02:26
created

DocumentController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 259
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 11
Bugs 0 Features 0
Metric Value
wmc 24
c 11
b 0
f 0
lcom 1
cbo 4
dl 0
loc 259
ccs 0
cts 180
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 24 1
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
	 * @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
			$encryptionManager = \OC::$server->getEncryptionManager();
120
			if ($encryptionManager->isEnabled())
121
			{
122
				// Update the current file to be accessible with system public shared key
123
				$owner = $item->getOwner()->getUID();
124
				$absPath = '/' . $owner . '/' .  $item->getInternalPath();
125
				$accessList = \OC::$server->getEncryptionFilesHelper()->getAccessList($absPath);
126
				$accessList['public'] = true;
127
				$encryptionManager->getEncryptionModule()->update($absPath, $owner, $accessList);
128
			}
129
130
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
131
			$policy = new ContentSecurityPolicy();
132
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
133
			$policy->allowInlineScript(true);
134
			$response->setContentSecurityPolicy($policy);
135
			return $response;
136
		} catch (\Exception $e) {
137
			$this->logger->logException($e, ['app'=>'richdocuments']);
138
			$params = [
139
				'remoteAddr' => $this->request->getRemoteAddress(),
140
				'requestID' => $this->request->getId(),
141
				'debugMode' => $this->settings->getSystemValue('debug'),
142
				'errorClass' => get_class($e),
143
				'errorCode' => $e->getCode(),
144
				'errorMsg' => $e->getMessage(),
145
				'file' => $e->getFile(),
146
				'line' => $e->getLine(),
147
				'trace' => $e->getTraceAsString()
148
			];
149
			return new TemplateResponse('core', 'exception', $params, 'guest');
150
		}
151
152
		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...
153
	}
154
155
	/**
156
	 * @PublicPage
157
	 *
158
	 * @param string $shareToken
159
	 * @param string $fileName
160
	 * @return TemplateResponse
161
	 * @throws \Exception
162
	 */
163
	public function publicPage($shareToken, $fileName) {
164
		try {
165
			$share = $this->shareManager->getShareByToken($shareToken);
166
			// not authenticated ?
167
			if($share->getPassword()){
168
				if (!$this->session->exists('public_link_authenticated')
169
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
170
				) {
171
					throw new \Exception('Invalid password');
172
				}
173
			}
174
175
			$node = $share->getNode();
176
			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...
177
				$item = $node->get($fileName);
178
			} else {
179
				$item = $node;
180
			}
181
			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...
182
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
183
				$params = [
184
					'permissions' => $share->getPermissions(),
185
					'title' => $item->getName(),
186
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
187
					'token' => $token,
188
					'urlsrc' => $urlSrc,
189
					'path' => '/',
190
					'instanceId' => $this->settings->getSystemValue('instanceid'),
191
				];
192
193
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
194
				$policy = new ContentSecurityPolicy();
195
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
196
				$policy->allowInlineScript(true);
197
				$response->setContentSecurityPolicy($policy);
198
				return $response;
199
			}
200
		} catch (\Exception $e) {
201
			$this->logger->logException($e, ['app'=>'richdocuments']);
202
			$params = [
203
				'remoteAddr' => $this->request->getRemoteAddress(),
204
				'requestID' => $this->request->getId(),
205
				'debugMode' => $this->settings->getSystemValue('debug'),
206
				'errorClass' => get_class($e),
207
				'errorCode' => $e->getCode(),
208
				'errorMsg' => $e->getMessage(),
209
				'file' => $e->getFile(),
210
				'line' => $e->getLine(),
211
				'trace' => $e->getTraceAsString()
212
			];
213
			return new TemplateResponse('core', 'exception', $params, 'guest');
214
		}
215
216
		return new TemplateResponse('core', '403', [], 'guest');
217
	}
218
219
	/**
220
	 * @NoAdminRequired
221
	 *
222
	 * @param string $mimetype
223
	 * @param string $filename
224
	 * @param string $dir
225
	 * @return JSONResponse
226
	 */
227
	public function create($mimetype,
228
						   $filename,
229
						   $dir){
230
231
		$view = new View('/' . $this->uid . '/files');
232
		if (!$dir){
233
			$dir = '/';
234
		}
235
236
		$basename = $this->l10n->t('New Document.odt');
237
		switch ($mimetype) {
238
			case 'application/vnd.oasis.opendocument.spreadsheet':
239
				$basename = $this->l10n->t('New Spreadsheet.ods');
240
				break;
241
			case 'application/vnd.oasis.opendocument.presentation':
242
				$basename = $this->l10n->t('New Presentation.odp');
243
				break;
244
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
245
				$basename = $this->l10n->t('New Document.docx');
246
				break;
247
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
248
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
249
				break;
250
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
251
				$basename = $this->l10n->t('New Presentation.pptx');
252
				break;
253
			default:
254
				// to be safe
255
				$mimetype = 'application/vnd.oasis.opendocument.text';
256
				break;
257
		}
258
259
		if (!$filename){
260
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
261
		} else {
262
			$path = $dir . '/' . $filename;
263
		}
264
265
		$content = '';
266
		if (class_exists('\OC\Files\Type\TemplateManager')){
267
			$manager = \OC_Helper::getFileTemplateManager();
268
			$content = $manager->getTemplate($mimetype);
269
		}
270
271
		if (!$content){
272
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
273
		}
274
275
		if ($content && $view->file_put_contents($path, $content)) {
276
			$info = $view->getFileInfo($path);
277
			$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...
278
			$response =  array(
279
				'status' => 'success',
280
				'data' => \OCA\Files\Helper::formatFileInfo($info)
281
			);
282
		} else {
283
			$response =  array(
284
				'status' => 'error',
285
				'message' => (string) $this->l10n->t('Can\'t create document')
286
			);
287
		}
288
289
		return $response;
290
	}
291
}
292