1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
|
<?php
/**
* @copyright Copyright (c) 2016-2017 Lukas Reschke <lukas@statuscode.ch>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Richdocuments\Controller;
use OC\Files\View;
use OCA\Richdocuments\Db\Wopi;
use OCA\Richdocuments\AppConfig;
use OCA\Richdocuments\Db\WopiMapper;
use OCA\Richdocuments\Service\UserScopeService;
use OCA\Richdocuments\TemplateManager;
use OCA\Richdocuments\TokenManager;
use OCA\Richdocuments\Helper;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\GenericFileException;
use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\ILogger;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\AppFramework\Http\StreamResponse;
use OCP\IUserManager;
use OCP\Lock\LockedException;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
class WopiController extends Controller {
/** @var IRootFolder */
private $rootFolder;
/** @var IURLGenerator */
private $urlGenerator;
/** @var IConfig */
private $config;
/** @var AppConfig */
private $appConfig;
/** @var TokenManager */
private $tokenManager;
/** @var IUserManager */
private $userManager;
/** @var WopiMapper */
private $wopiMapper;
/** @var ILogger */
private $logger;
/** @var TemplateManager */
private $templateManager;
/** @var IManager */
private $shareManager;
/** @var UserScopeService */
private $userScopeService;
// Signifies LOOL that document has been changed externally in this storage
const LOOL_STATUS_DOC_CHANGED = 1010;
/**
* @param string $appName
* @param IRequest $request
* @param IRootFolder $rootFolder
* @param IURLGenerator $urlGenerator
* @param IConfig $config
* @param TokenManager $tokenManager
* @param IUserManager $userManager
* @param WopiMapper $wopiMapper
* @param ILogger $logger
* @param TemplateManager $templateManager
*/
public function __construct(
$appName,
IRequest $request,
IRootFolder $rootFolder,
IURLGenerator $urlGenerator,
IConfig $config,
AppConfig $appConfig,
TokenManager $tokenManager,
IUserManager $userManager,
WopiMapper $wopiMapper,
ILogger $logger,
TemplateManager $templateManager,
IManager $shareManager,
UserScopeService $userScopeService
) {
parent::__construct($appName, $request);
$this->rootFolder = $rootFolder;
$this->urlGenerator = $urlGenerator;
$this->config = $config;
$this->appConfig = $appConfig;
$this->tokenManager = $tokenManager;
$this->userManager = $userManager;
$this->wopiMapper = $wopiMapper;
$this->logger = $logger;
$this->templateManager = $templateManager;
$this->shareManager = $shareManager;
$this->userScopeService = $userScopeService;
}
/**
* Returns general info about a file.
*
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
*
* @param string $fileId
* @param string $access_token
* @return JSONResponse
* @throws InvalidPathException
* @throws NotFoundException
*/
public function checkFileInfo($fileId, $access_token) {
try {
list($fileId, , $version) = Helper::parseFileId($fileId);
$wopi = $this->wopiMapper->getWopiForToken($access_token);
if ($wopi->isTemplateToken()) {
$this->templateManager->setUserId($wopi->getOwnerUid());
$file = $this->templateManager->get($wopi->getFileid());
} else {
$file = $this->getFileForWopiToken($wopi);
}
if(!($file instanceof File)) {
throw new NotFoundException('No valid file found for ' . $fileId);
}
} catch (NotFoundException $e) {
$this->logger->debug($e->getMessage(), ['app' => 'richdocuments', '']);
return new JSONResponse([], Http::STATUS_FORBIDDEN);
} catch (DoesNotExistException $e) {
$this->logger->debug($e->getMessage(), ['app' => 'richdocuments', '']);
return new JSONResponse([], Http::STATUS_FORBIDDEN);
} catch (\Exception $e) {
$this->logger->logException($e, ['app' => 'richdocuments']);
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
$isPublic = $wopi->getEditorUid() === null;
$guestUserId = 'Guest-' . \OC::$server->getSecureRandom()->generate(8);
$user = $this->userManager->get($wopi->getEditorUid());
$userDisplayName = $user !== null && !$isPublic ? $user->getDisplayName() : $wopi->getGuestDisplayname();
$isVersion = $version !== '0';
$response = [
'BaseFileName' => $file->getName(),
'Size' => $file->getSize(),
'Version' => $version,
'UserId' => !$isPublic ? $wopi->getEditorUid() : $guestUserId,
'OwnerId' => $wopi->getOwnerUid(),
'UserFriendlyName' => $userDisplayName,
'UserExtraInfo' => [
],
'UserCanWrite' => $wopi->getCanwrite(),
'UserCanNotWriteRelative' => \OC::$server->getEncryptionManager()->isEnabled() || $isPublic,
'PostMessageOrigin' => $wopi->getServerHost(),
'LastModifiedTime' => Helper::toISO8601($file->getMTime()),
'SupportsRename' => !$isVersion,
'UserCanRename' => !$isPublic && !$isVersion,
'EnableInsertRemoteImage' => true,
'EnableShare' => $file->isShareable() && !$isVersion,
'HideUserList' => 'desktop',
'DisablePrint' => $wopi->getHideDownload(),
'DisableExport' => $wopi->getHideDownload(),
'DisableCopy' => $wopi->getHideDownload(),
'HideExportOption' => $wopi->getHideDownload(),
'HidePrintOption' => $wopi->getHideDownload(),
'DownloadAsPostMessage' => $wopi->getDirect(),
];
if ($wopi->isTemplateToken()) {
$userFolder = $this->rootFolder->getUserFolder($wopi->getOwnerUid());
$file = $userFolder->getById($wopi->getTemplateDestination())[0];
$response['TemplateSaveAs'] = $file->getName();
}
if ($this->shouldWatermark($isPublic, $wopi->getEditorUid(), $fileId, $wopi)) {
$replacements = [
'userId' => $wopi->getEditorUid(),
'date' => (new \DateTime())->format('Y-m-d H:i:s'),
'themingName' => \OC::$server->getThemingDefaults()->getName(),
];
$watermarkTemplate = $this->appConfig->getAppValue('watermark_text');
$response['WatermarkText'] = preg_replace_callback('/{(.+?)}/', function ($matches) use ($replacements) {
return $replacements[$matches[1]];
}, $watermarkTemplate);
}
/**
* New approach for generating files from templates by creating an empty file
* and providing an URL which returns the actual template
*/
if ($wopi->hasTemplateId()) {
$templateUrl = 'index.php/apps/richdocuments/wopi/template/' . $wopi->getTemplateId() . '?access_token=' . $wopi->getToken();
$templateUrl = $this->urlGenerator->getAbsoluteURL($templateUrl);
$response['TemplateSource'] = $templateUrl;
}
$user = $this->userManager->get($wopi->getEditorUid());
if($user !== null) {
$response['UserExtraInfo']['avatar'] = $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => $wopi->getEditorUid(), 'size' => 32]);
}
if ($wopi->getRemoteServer() !== '') {
$response = $this->setFederationFileInfo($wopi, $response);
}
return new JSONResponse($response);
}
private function setFederationFileInfo($wopi, $response) {
$remoteUserId = $wopi->getGuestDisplayname();
$cloudID = \OC::$server->getCloudIdManager()->resolveCloudId($remoteUserId);
$response['UserFriendlyName'] = $cloudID->getDisplayId();
$response['UserExtraInfo']['avatar'] = $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => explode('@', $remoteUserId)[0], 'size' => 32]);
$cleanCloudId = str_replace(['http://', 'https://'], '', $cloudID->getId());
$addressBookEntries = \OC::$server->getContactsManager()->search($cleanCloudId, ['CLOUD']);
foreach ($addressBookEntries as $entry) {
if (isset($entry['CLOUD'])) {
foreach ($entry['CLOUD'] as $cloudID) {
if ($cloudID === $cleanCloudId) {
$response['UserFriendlyName'] = $entry['FN'];
break;
}
}
}
}
return $response;
}
private function shouldWatermark($isPublic, $userId, $fileId, Wopi $wopi) {
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_enabled', 'no') === 'no') {
return false;
}
if ($isPublic) {
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_linkAll', 'no') === 'yes') {
return true;
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_linkRead', 'no') === 'yes' && !$wopi->getCanwrite()) {
return true;
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_linkSecure', 'no') === 'yes' && $wopi->getHideDownload()) {
return true;
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_linkTags', 'no') === 'yes') {
$tags = $this->appConfig->getAppValueArray('watermark_linkTagsList');
$fileTags = \OC::$server->getSystemTagObjectMapper()->getTagIdsForObjects([$fileId], 'files')[$fileId];
foreach ($fileTags as $tagId) {
if (in_array($tagId, $tags, true)) {
return true;
}
}
}
} else {
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_shareAll', 'no') === 'yes') {
$files = $this->rootFolder->getUserFolder($userId)->getById($fileId);
if (count($files) !== 0 && $files[0]->getOwner()->getUID() !== $userId) {
return true;
}
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_shareRead', 'no') === 'yes' && !$wopi->getCanwrite()) {
return true;
}
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_allGroups', 'no') === 'yes') {
$groups = $this->appConfig->getAppValueArray('watermark_allGroupsList');
foreach ($groups as $group) {
if (\OC::$server->getGroupManager()->isInGroup($userId, $group)) {
return true;
}
}
}
if ($this->config->getAppValue(AppConfig::WATERMARK_APP_NAMESPACE, 'watermark_allTags', 'no') === 'yes') {
$tags = $this->appConfig->getAppValueArray('watermark_allTagsList');
$fileTags = \OC::$server->getSystemTagObjectMapper()->getTagIdsForObjects([$fileId], 'files')[$fileId];
foreach ($fileTags as $tagId) {
if (in_array($tagId, $tags, true)) {
return true;
}
}
}
return false;
}
/**
* Given an access token and a fileId, returns the contents of the file.
* Expects a valid token in access_token parameter.
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $fileId
* @param string $access_token
* @return Http\Response
* @throws DoesNotExistException
* @throws NotFoundException
* @throws NotPermittedException
*/
public function getFile($fileId,
$access_token) {
list($fileId, , $version) = Helper::parseFileId($fileId);
$wopi = $this->wopiMapper->getWopiForToken($access_token);
if ((int)$fileId !== $wopi->getFileid()) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
// Template is just returned as there is no version logic
if ($wopi->isTemplateToken()) {
$this->templateManager->setUserId($wopi->getOwnerUid());
$file = $this->templateManager->get($wopi->getFileid());
$response = new StreamResponse($file->fopen('rb'));
$response->addHeader('Content-Disposition', 'attachment');
$response->addHeader('Content-Type', 'application/octet-stream');
return $response;
}
try {
/** @var File $file */
$userFolder = $this->rootFolder->getUserFolder($wopi->getOwnerUid());
$file = $userFolder->getById($fileId)[0];
\OC_User::setIncognitoMode(true);
if ($version !== '0') {
$view = new View('/' . $wopi->getOwnerUid() . '/files');
$relPath = $view->getRelativePath($file->getPath());
$versionPath = '/files_versions/' . $relPath . '.v' . $version;
$view = new View('/' . $wopi->getOwnerUid());
if ($view->file_exists($versionPath)){
$response = new StreamResponse($view->fopen($versionPath, 'rb'));
}
else {
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}
}
else
{
$response = new StreamResponse($file->fopen('rb'));
}
$response->addHeader('Content-Disposition', 'attachment');
$response->addHeader('Content-Type', 'application/octet-stream');
return $response;
} catch (\Exception $e) {
$this->logger->logException($e, ['level' => ILogger::ERROR, 'app' => 'richdocuments', 'message' => 'getFile failed']);
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
}
/**
* Given an access token and a fileId, replaces the files with the request body.
* Expects a valid token in access_token parameter.
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $fileId
* @param string $access_token
* @return JSONResponse
* @throws DoesNotExistException
*/
public function putFile($fileId,
$access_token) {
list($fileId, ,) = Helper::parseFileId($fileId);
$isPutRelative = ($this->request->getHeader('X-WOPI-Override') === 'PUT_RELATIVE');
$isRenameFile = ($this->request->getHeader('X-WOPI-Override') === 'RENAME_FILE');
$wopi = $this->wopiMapper->getWopiForToken($access_token);
if (!$wopi->getCanwrite()) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
// Set the user to register the change under his name
$this->userScopeService->setUserScope($wopi->getUserForFileAccess());
$this->userScopeService->setFilesystemScope($isPutRelative ? $wopi->getEditorUid() : $wopi->getUserForFileAccess());
try {
if ($isPutRelative) {
// the new file needs to be installed in the current user dir
$userFolder = $this->rootFolder->getUserFolder($wopi->getEditorUid());
$file = $userFolder->getById($fileId);
if (count($file) === 0) {
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}
$file = $file[0];
$suggested = $this->request->getHeader('X-WOPI-SuggestedTarget');
$suggested = iconv('utf-7', 'utf-8', $suggested);
if ($suggested[0] === '.') {
$path = dirname($file->getPath()) . '/New File' . $suggested;
}
else if ($suggested[0] !== '/') {
$path = dirname($file->getPath()) . '/' . $suggested;
}
else {
$path = $userFolder->getPath() . $suggested;
}
if ($path === '') {
return new JSONResponse([
'status' => 'error',
'message' => 'Cannot create the file'
]);
}
// create the folder first
if (!$this->rootFolder->nodeExists(dirname($path))) {
$this->rootFolder->newFolder(dirname($path));
}
// create a unique new file
$path = $this->rootFolder->getNonExistingName($path);
$this->rootFolder->newFile($path);
$file = $this->rootFolder->get($path);
} else {
$file = $this->getFileForWopiToken($wopi);
$wopiHeaderTime = $this->request->getHeader('X-LOOL-WOPI-Timestamp');
if ($wopiHeaderTime !== null && $wopiHeaderTime !== Helper::toISO8601($file->getMTime() ?? 0)) {
$this->logger->debug('Document timestamp mismatch ! WOPI client says mtime {headerTime} but storage says {storageTime}', [
'headerTime' => $wopiHeaderTime,
'storageTime' => Helper::toISO8601($file->getMTime() ?? 0)
]);
// Tell WOPI client about this conflict.
return new JSONResponse(['LOOLStatusCode' => self::LOOL_STATUS_DOC_CHANGED], Http::STATUS_CONFLICT);
}
}
$content = fopen('php://input', 'rb');
try {
$this->retryOperation(function () use ($file, $content){
return $file->putContent($content);
});
} catch (LockedException $e) {
$this->logger->logException($e);
return new JSONResponse(['message' => 'File locked'], Http::STATUS_INTERNAL_SERVER_ERROR);
}
if ($isPutRelative) {
// generate a token for the new file (the user still has to be
// logged in)
list(, $wopiToken) = $this->tokenManager->getToken($file->getId(), null, $wopi->getEditorUid());
$wopi = 'index.php/apps/richdocuments/wopi/files/' . $file->getId() . '_' . $this->config->getSystemValue('instanceid') . '?access_token=' . $wopiToken;
$url = $this->urlGenerator->getAbsoluteURL($wopi);
return new JSONResponse([ 'Name' => $file->getName(), 'Url' => $url ], Http::STATUS_OK);
}
if ($wopi->hasTemplateId()) {
$wopi->setTemplateId(null);
$this->wopiMapper->update($wopi);
}
return new JSONResponse(['LastModifiedTime' => Helper::toISO8601($file->getMTime())]);
} catch (\Exception $e) {
$this->logger->logException($e, ['level' => ILogger::ERROR, 'app' => 'richdocuments', 'message' => 'getFile failed']);
return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
/**
* Given an access token and a fileId, replaces the files with the request body.
* Expects a valid token in access_token parameter.
* Just actually routes to the PutFile, the implementation of PutFile
* handles both saving and saving as.* Given an access token and a fileId, replaces the files with the request body.
*
* FIXME Cleanup this code as is a lot of shared logic between putFile and putRelativeFile
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $fileId
* @param string $access_token
* @return JSONResponse
* @throws DoesNotExistException
*/
public function putRelativeFile($fileId,
$access_token) {
list($fileId, ,) = Helper::parseFileId($fileId);
$wopi = $this->wopiMapper->getWopiForToken($access_token);
$isRenameFile = ($this->request->getHeader('X-WOPI-Override') === 'RENAME_FILE');
if (!$wopi->getCanwrite()) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
// Unless the editor is empty (public link) we modify the files as the current editor
$editor = $wopi->getEditorUid();
if ($editor === null || $wopi->getRemoteServer() !== '') {
$editor = $wopi->getOwnerUid();
}
try {
// the new file needs to be installed in the current user dir
$userFolder = $this->rootFolder->getUserFolder($editor);
if ($wopi->isTemplateToken()) {
$this->templateManager->setUserId($wopi->getOwnerUid());
$file = $userFolder->getById($wopi->getTemplateDestination())[0];
} else if ($isRenameFile) {
// the new file needs to be installed in the current user dir
$userFolder = $this->rootFolder->getUserFolder($wopi->getEditorUid());
$file = $userFolder->getById($fileId)[0];
$suggested = $this->request->getHeader('X-WOPI-RequestedName');
$suggested = iconv('utf-7', 'utf-8', $suggested) . '.' . $file->getExtension();
if (strpos($suggested, '.') === 0) {
$path = dirname($file->getPath()) . '/New File' . $suggested;
}
else if (strpos($suggested, '/') !== 0) {
$path = dirname($file->getPath()) . '/' . $suggested;
}
else {
$path = $userFolder->getPath() . $suggested;
}
if ($path === '') {
return new JSONResponse([
'status' => 'error',
'message' => 'Cannot rename the file'
]);
}
// create the folder first
if (!$this->rootFolder->nodeExists(dirname($path))) {
$this->rootFolder->newFolder(dirname($path));
}
// create a unique new file
$path = $this->rootFolder->getNonExistingName($path);
$file = $file->move($path);
} else {
$file = $userFolder->getById($fileId);
if (count($file) === 0) {
return new JSONResponse([], Http::STATUS_NOT_FOUND);
}
$file = $file[0];
$suggested = $this->request->getHeader('X-WOPI-SuggestedTarget');
$suggested = iconv('utf-7', 'utf-8', $suggested);
if ($suggested[0] === '.') {
$path = dirname($file->getPath()) . '/New File' . $suggested;
} else if ($suggested[0] !== '/') {
$path = dirname($file->getPath()) . '/' . $suggested;
} else {
$path = $userFolder->getPath() . $suggested;
}
if ($path === '') {
return new JSONResponse([
'status' => 'error',
'message' => 'Cannot create the file'
]);
}
// create the folder first
if (!$this->rootFolder->nodeExists(dirname($path))) {
$this->rootFolder->newFolder(dirname($path));
}
// create a unique new file
$path = $this->rootFolder->getNonExistingName($path);
$file = $this->rootFolder->newFile($path);
}
$content = fopen('php://input', 'rb');
// Set the user to register the change under his name
$this->userScopeService->setUserScope($wopi->getEditorUid());
$this->userScopeService->setFilesystemScope($wopi->getEditorUid());
try {
$this->retryOperation(function () use ($file, $content){
return $file->putContent($content);
});
} catch (LockedException $e) {
return new JSONResponse(['message' => 'File locked'], Http::STATUS_INTERNAL_SERVER_ERROR);
}
// generate a token for the new file (the user still has to be
// logged in)
list(, $wopiToken) = $this->tokenManager->getToken($file->getId(), null, $wopi->getEditorUid());
$wopi = 'index.php/apps/richdocuments/wopi/files/' . $file->getId() . '_' . $this->config->getSystemValue('instanceid') . '?access_token=' . $wopiToken;
$url = $this->urlGenerator->getAbsoluteURL($wopi);
return new JSONResponse([ 'Name' => $file->getName(), 'Url' => $url ], Http::STATUS_OK);
} catch (\Exception $e) {
$this->logger->logException($e, ['level' => ILogger::ERROR, 'app' => 'richdocuments', 'message' => 'putRelativeFile failed']);
return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
/**
* Retry operation if a LockedException occurred
* Other exceptions will still be thrown
* @param callable $operation
* @throws LockedException
* @throws GenericFileException
*/
private function retryOperation(callable $operation) {
for ($i = 0; $i < 5; $i++) {
try {
if ($operation() !== false) {
return;
}
} catch (LockedException $e) {
if ($i === 4) {
throw $e;
}
usleep(500000);
}
}
throw new GenericFileException('Operation failed after multiple retries');
}
/**
* @param Wopi $wopi
* @return File|Folder|Node|null
* @throws NotFoundException
* @throws ShareNotFound
*/
private function getFileForWopiToken(Wopi $wopi) {
$file = null;
if ($wopi->getRemoteServer() !== '') {
$share = $this->shareManager->getShareByToken($wopi->getEditorUid());
$node = $share->getNode();
if ($node instanceof Folder) {
$file = $node->getById($wopi->getFileid())[0];
} else {
$file = $node;
}
} else {
// Unless the editor is empty (public link) we modify the files as the current editor
// TODO: add related share token to the wopi table so we can obtain the
$userFolder = $this->rootFolder->getUserFolder($wopi->getUserForFileAccess());
$files = $userFolder->getById($wopi->getFileid());
if (isset($files[0]) && $files[0] instanceof File) {
$file = $files[0];
} else {
throw new NotFoundException('No valid file found for wopi token');
}
}
return $file;
}
/**
* Endpoint to return the template file that is requested by collabora to create a new document
*
* @PublicPage
* @NoCSRFRequired
*
* @param $fileId
* @param $access_token
* @return JSONResponse|StreamResponse
*/
public function getTemplate($fileId, $access_token) {
try {
$wopi = $this->wopiMapper->getPathForToken($access_token);
} catch (DoesNotExistException $e) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
if ((int)$fileId !== $wopi->getTemplateId()) {
return new JSONResponse([], Http::STATUS_FORBIDDEN);
}
try {
$this->templateManager->setUserId($wopi->getOwnerUid());
$file = $this->templateManager->get($wopi->getTemplateId());
$response = new StreamResponse($file->fopen('rb'));
$response->addHeader('Content-Disposition', 'attachment');
$response->addHeader('Content-Type', 'application/octet-stream');
return $response;
} catch (\Exception $e) {
$this->logger->logException($e, ['level' => ILogger::ERROR, 'app' => 'richdocuments', 'message' => 'getTemplate failed']);
return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
}
|