Completed
Push — master ( efe13b...719b15 )
by Lukas
02:55
created

DocumentController::publicPage()   C

Complexity

Conditions 7
Paths 44

Size

Total Lines 41
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 41
ccs 0
cts 37
cp 0
rs 6.7272
cc 7
eloc 29
nc 44
nop 2
crap 56
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\AppFramework\Http\ContentSecurityPolicy;
25
use \OCP\AppFramework\Http\TemplateResponse;
26
use \OCA\Richdocuments\AppConfig;
27
use \OCA\Richdocuments\Helper;
28
use \OC\Files\View;
29
use OCP\ISession;
30
use OCP\Share\IManager;
31
32
class DocumentController extends Controller {
33
	/** @var string */
34
	private $uid;
35
	/** @var IL10N */
36
	private $l10n;
37
	/** @var IConfig */
38
	private $settings;
39
	/** @var AppConfig */
40
	private $appConfig;
41
	/** @var Parser */
42
	private $wopiParser;
43
	/** @var IManager */
44
	private $shareManager;
45
	/** @var TokenManager */
46
	private $tokenManager;
47
	/** @var ISession */
48
	private $session;
49
	/** @var IRootFolder */
50
	private $rootFolder;
51
52
	const ODT_TEMPLATE_PATH = '/assets/odttemplate.odt';
53
54
	/**
55
	 * @param string $appName
56
	 * @param IRequest $request
57
	 * @param IConfig $settings
58
	 * @param AppConfig $appConfig
59
	 * @param IL10N $l10n
60
	 * @param Parser $wopiParser
61
	 * @param IManager $shareManager
62
	 * @param TokenManager $tokenManager
63
	 * @param IRootFolder $rootFolder
64
	 * @param ISession $session
65
	 * @param string $UserId
66
	 */
67
	public function __construct($appName,
68
								IRequest $request,
69
								IConfig $settings,
70
								AppConfig $appConfig,
71
								IL10N $l10n,
72
								Parser $wopiParser,
73
								IManager $shareManager,
74
								TokenManager $tokenManager,
75
								IRootFolder $rootFolder,
76
								ISession $session,
77
								$UserId) {
78
		parent::__construct($appName, $request);
79
		$this->uid = $UserId;
80
		$this->l10n = $l10n;
81
		$this->settings = $settings;
82
		$this->appConfig = $appConfig;
83
		$this->wopiParser = $wopiParser;
84
		$this->shareManager = $shareManager;
85
		$this->tokenManager = $tokenManager;
86
		$this->rootFolder = $rootFolder;
87
		$this->session = $session;
88
	}
89
90
	/**
91
	 * @NoAdminRequired
92
	 *
93
	 * @param string $fileId
94
	 * @return TemplateResponse
95
	 */
96
	public function index($fileId) {
97
		try {
98
			$folder = $this->rootFolder->getUserFolder($this->uid);
99
			$item = $folder->getById($fileId)[0];
100
			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...
101
				throw new \Exception();
102
			}
103
			list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
104
			$params = [
105
				'permissions' => $item->getPermissions(),
106
				'title' => $item->getName(),
107
				'fileId' => $item->getId(),
108
				'token' => $token,
109
				'urlsrc' => $urlSrc,
110
				'path' => '/',
111
			];
112
113
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
114
			$policy = new ContentSecurityPolicy();
115
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
116
			$policy->allowInlineScript(true);
117
			$response->setContentSecurityPolicy($policy);
118
			return $response;
119
		} catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
120
		}
121
122
		return new TemplateResponse('core', '403', [], 'guest');
123
	}
124
125
	/**
126
	 * @PublicPage
127
	 *
128
	 * @param string $shareToken
129
	 * @param string $fileName
130
	 * @return TemplateResponse
131
	 * @throws \Exception
132
	 */
133
	public function publicPage($shareToken, $fileName) {
134
		try {
135
			$share = $this->shareManager->getShareByToken($shareToken);
136
			// not authenticated ?
137
			if($share->getPassword()){
138
				if (!$this->session->exists('public_link_authenticated')
139
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
140
				) {
141
					throw new \Exception('Invalid password');
142
				}
143
			}
144
145
			$node = $share->getNode();
146
			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...
147
				$item = $node->get($fileName);
148
			} else {
149
				$item = $node;
150
			}
151
			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...
152
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
153
				$params = [
154
					'permissions' => $share->getPermissions(),
155
					'title' => $item->getName(),
156
					'fileId' => $item->getId(),
157
					'token' => $token,
158
					'urlsrc' => $urlSrc,
159
					'path' => '/',
160
				];
161
162
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
163
				$policy = new ContentSecurityPolicy();
164
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
165
				$policy->allowInlineScript(true);
166
				$response->setContentSecurityPolicy($policy);
167
				return $response;
168
			}
169
		} catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
170
		}
171
172
		return new TemplateResponse('core', '403', [], 'guest');
173
	}
174
175
	/**
176
	 * @NoAdminRequired
177
	 *
178
	 * @param string $mimetype
179
	 * @param string $filename
180
	 * @param string $dir
181
	 * @return JSONResponse
182
	 */
183
	public function create($mimetype,
184
						   $filename,
185
						   $dir){
186
187
		$view = new View('/' . $this->uid . '/files');
188
		if (!$dir){
189
			$dir = '/';
190
		}
191
192
		$basename = $this->l10n->t('New Document.odt');
193
		switch ($mimetype) {
194
			case 'application/vnd.oasis.opendocument.spreadsheet':
195
				$basename = $this->l10n->t('New Spreadsheet.ods');
196
				break;
197
			case 'application/vnd.oasis.opendocument.presentation':
198
				$basename = $this->l10n->t('New Presentation.odp');
199
				break;
200
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
201
				$basename = $this->l10n->t('New Document.docx');
202
				break;
203
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
204
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
205
				break;
206
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
207
				$basename = $this->l10n->t('New Presentation.pptx');
208
				break;
209
			default:
210
				// to be safe
211
				$mimetype = 'application/vnd.oasis.opendocument.text';
212
				break;
213
		}
214
215
		if (!$filename){
216
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
217
		} else {
218
			$path = $dir . '/' . $filename;
219
		}
220
221
		$content = '';
222
		if (class_exists('\OC\Files\Type\TemplateManager')){
223
			$manager = \OC_Helper::getFileTemplateManager();
224
			$content = $manager->getTemplate($mimetype);
225
		}
226
227
		if (!$content){
228
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
229
		}
230
231
		if ($content && $view->file_put_contents($path, $content)) {
232
			$info = $view->getFileInfo($path);
233
			$ret = $this->wopiParser->getUrlSrc($mimetype);
234
			$response =  array(
235
				'status' => 'success',
236
				'fileid' => $info['fileid'],
237
				'urlsrc' => $ret['urlsrc'],
238
				'action' => $ret['action'],
239
				'lolang' => $this->settings->getUserValue($this->uid, 'core', 'lang', 'en'),
240
				'data' => \OCA\Files\Helper::formatFileInfo($info)
241
			);
242
		} else {
243
			$response =  array(
244
				'status' => 'error',
245
				'message' => (string) $this->l10n->t('Can\'t create document')
246
			);
247
		}
248
249
		return $response;
250
	}
251
}
252