CollaboraOnlineController.php 29.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

/**
 * Copyright Maarch since 2008 under licence GPLv3.
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 */

/**
 * @brief Collabora Online Controller
 *
 * @author dev@maarch.org
 */

namespace ContentManagement\controllers;

17
use Attachment\models\AttachmentModel;
18
use Configuration\models\ConfigurationModel;
19
20
21
22
use Convert\models\AdrModel;
use Docserver\models\DocserverModel;
use Docserver\models\DocserverTypeModel;
use Firebase\JWT\JWT;
23
use Group\controllers\PrivilegeController;
24
25
26
27
28
29
use Resource\controllers\ResController;
use Resource\controllers\StoreController;
use Resource\models\ResModel;
use Respect\Validation\Validator;
use Slim\Http\Request;
use Slim\Http\Response;
30
use SrcCore\controllers\CoreController;
31
32
33
use SrcCore\controllers\UrlController;
use SrcCore\models\CoreConfigModel;
use SrcCore\models\CurlModel;
34
use SrcCore\models\ValidatorModel;
35
36
use Template\controllers\TemplateController;
use Template\models\TemplateAssociationModel;
37
use Template\models\TemplateModel;
38
use User\models\UserEntityModel;
39
40
41
42
43
44
45
46
47
48
49
50
use User\models\UserModel;

class CollaboraOnlineController
{
    public function getFileContent(Request $request, Response $response, array $args)
    {
        $queryParams = $request->getQueryParams();

        if (!Validator::stringType()->notEmpty()->validate($queryParams['access_token'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query access_token is empty or not a string']);
        }

51
52
        $tokenCheckResult = CollaboraOnlineController::checkToken(['token' => $queryParams['access_token'], 'id' => $args['id']]);
        if (!empty($tokenCheckResult['errors'])) {
53
            return $response->withStatus($tokenCheckResult['code'])->withJson(['errors' => $tokenCheckResult['errors']]);
54
55
        }

56
        $document = CollaboraOnlineController::getDocument([
57
58
59
            'id'     => $args['id'],
            'type'   => $tokenCheckResult['type'],
            'format' => $tokenCheckResult['format']
60
        ]);
61

62
63
        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
64
65
        }

66
67
68
69
70
71
72
        if (!empty($document['docserver_id'])) {
            $docserver = DocserverModel::getByDocserverId(['docserverId' => $document['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
            if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) {
                return $response->withStatus(400)->withJson(['errors' => 'Docserver does not exist']);
            }
        } else {
            $docserver['path_template'] = '';
73
74
75
76
77
78
79
        }

        $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $document['path']) . $document['filename'];
        if (!file_exists($pathToDocument)) {
            return $response->withStatus(404)->withJson(['errors' => 'Document not found on docserver']);
        }

80
        if ($tokenCheckResult['type'] == 'resourceModification' || $tokenCheckResult['type'] == 'attachmentModification') {
81
82
            $docserverType = DocserverTypeModel::getById(['id' => $docserver['docserver_type_id'], 'select' => ['fingerprint_mode']]);
            $fingerprint = StoreController::getFingerPrint(['filePath' => $pathToDocument, 'mode' => $docserverType['fingerprint_mode']]);
83

84
            if (empty($document['fingerprint']) && $tokenCheckResult['type'] == 'resourceModification') {
85
86
                ResModel::update(['set' => ['fingerprint' => $fingerprint], 'where' => ['res_id = ?'], 'data' => [$args['id']]]);
                $document['fingerprint'] = $fingerprint;
87
            } elseif (empty($document['fingerprint']) && $tokenCheckResult['type'] == 'attachmentModification') {
88
89
90
                AttachmentModel::update(['set' => ['fingerprint' => $fingerprint], 'where' => ['res_id = ?'], 'data' => [$args['id']]]);
                $document['fingerprint'] = $fingerprint;
            }
91

92
93
94
            if ($document['fingerprint'] != $fingerprint) {
                return $response->withStatus(400)->withJson(['errors' => 'Fingerprints do not match']);
            }
95
96
        }

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        if ($tokenCheckResult['type'] == 'resourceCreation' || $tokenCheckResult['type'] == 'attachmentCreation') {
            $dataToMerge = ['userId' => $GLOBALS['id']];
            if (!empty($tokenCheckResult['data']) && is_array($tokenCheckResult['data'])) {
                $dataToMerge = array_merge($dataToMerge, $tokenCheckResult['data']);
            }

            $mergedDocument = MergeController::mergeDocument([
                'path' => $pathToDocument,
                'data' => $dataToMerge
            ]);
            $content = $mergedDocument['encodedDocument'];
            $fileContent = base64_decode($content);
        } else {
            $fileContent = file_get_contents($pathToDocument);
            if ($fileContent === false) {
                return $response->withStatus(404)->withJson(['errors' => 'Document not found']);
            }

            $content = base64_encode($fileContent);
            $fileContent = base64_decode($content);
117
118
119
120
121
122
        }

        $finfo    = new \finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->buffer($fileContent);
        $pathInfo = pathinfo($pathToDocument);

123
        if ($tokenCheckResult['type'] == 'templateEncoded') {
124
125
126
            unlink($document['path'] . $document['filename']);
        }

127
128
129
130
131
132
133
134
135
136
137
138
139
        $response->write($fileContent);
        $response = $response->withAddedHeader('Content-Disposition', "attachment; filename=maarch.{$pathInfo['extension']}");
        return $response->withHeader('Content-Type', $mimeType);
    }

    public function getCheckFileInfo(Request $request, Response $response, array $args)
    {
        $queryParams = $request->getQueryParams();

        if (!Validator::stringType()->notEmpty()->validate($queryParams['access_token'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query access_token is empty or not a string']);
        }

140
141
142
        $tokenCheckResult = CollaboraOnlineController::checkToken(['token' => $queryParams['access_token'], 'id' => $args['id']]);
        if (!empty($tokenCheckResult['errors'])) {
            return $response->withStatus($tokenCheckResult['code'])->withJson(['errors' => $tokenCheckResult['errors']]);
143
144
        }

145
        $document = CollaboraOnlineController::getDocument([
146
147
148
            'id'     => $args['id'],
            'type'   => $tokenCheckResult['type'],
            'format' => $tokenCheckResult['format']
149
        ]);
150

151
152
        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
153
154
155
        }

        $modificationDate = new \DateTime($document['modification_date']);
156
        $modificationDate->setTimezone(new \DateTimeZone('UTC'));
157
158
159
160
161
162
163
        $modificationDate = $modificationDate->format(\DateTime::ISO8601);

        return $response->withJson([
            'BaseFileName'            => $document['filename'],
            'Size'                    => $document['filesize'],
            'UserCanNotWriteRelative' => true,
            'UserCanWrite'            => true,
164
165
            'DisablePrint'            => true,
            'HideSaveOption'          => true,
166
167
168
169
170
171
172
173
174
            'UserFriendlyName'        => UserModel::getLabelledUserById(['id' => $GLOBALS['id']]),
            'OwnerId'                 => $GLOBALS['id'],
            'UserId'                  => $GLOBALS['id'],
            'LastModifiedTime'        => $modificationDate
        ]);
    }

    public function saveFile(Request $request, Response $response, array $args)
    {
175
176
177
178
179
180
        $queryParams = $request->getQueryParams();

        if (!Validator::stringType()->notEmpty()->validate($queryParams['access_token'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query access_token is empty or not a string']);
        }

181
182
183
        $tokenCheckResult = CollaboraOnlineController::checkToken(['token' => $queryParams['access_token'], 'id' => $args['id']]);
        if (!empty($tokenCheckResult['errors'])) {
            return $response->withStatus($tokenCheckResult['code'])->withJson(['errors' => $tokenCheckResult['errors']]);
184
185
        }

186
        $document = CollaboraOnlineController::getDocument([
187
188
189
            'id'     => $args['id'],
            'type'   => $tokenCheckResult['type'],
            'format' => $tokenCheckResult['format']
190
        ]);
191

192
193
194
        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
        }
195

196
        $fileContent = $request->getBody()->getContents();
197

198
199
        $extension = pathinfo($document['filename'], PATHINFO_EXTENSION);
        $tmpPath = CoreConfigModel::getTmpPath();
200
        $filename = "collabora_{$GLOBALS['id']}_{$tokenCheckResult['type']}_{$args['id']}.{$extension}";
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

        $put = file_put_contents($tmpPath . $filename, $fileContent);
        if ($put === false) {
            return $response->withStatus(400)->withJson(['errors' => 'File put contents failed']);
        }

        return $response->withStatus(200);
    }

    public function getTmpFile(Request $request, Response $response)
    {
        $body = $request->getParsedBody();

        if (!Validator::stringType()->notEmpty()->validate($body['token'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query token is empty or not a string']);
        }

        $tokenCheckResult = CollaboraOnlineController::checkToken(['token' => $body['token']]);
        if (!empty($tokenCheckResult['errors'])) {
            return $response->withStatus($tokenCheckResult['code'])->withJson(['errors' => $tokenCheckResult['errors']]);
        }
222

223
        $document = CollaboraOnlineController::getDocument([
224
225
226
            'id'     => $tokenCheckResult['resId'],
            'type'   => $tokenCheckResult['type'],
            'format' => $tokenCheckResult['format']
227
228
229
230
        ]);
        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
        }
231

232
        $extension = pathinfo($document['filename'], PATHINFO_EXTENSION);
233
        $filename = "collabora_{$GLOBALS['id']}_{$tokenCheckResult['type']}_{$tokenCheckResult['resId']}.{$extension}";
234
235
236
        $tmpPath = CoreConfigModel::getTmpPath();
        $pathToDocument = $tmpPath . $filename;

237
238
239
240
        if (!file_exists($pathToDocument)) {
            return $response->withStatus(404)->withJson(['errors' => 'Document not found']);
        }

241
242
243
        $fileContent = file_get_contents($pathToDocument);
        if ($fileContent === false) {
            return $response->withStatus(404)->withJson(['errors' => 'Document not found']);
244
245
        }

246
247
        $content = base64_encode($fileContent);

248
        return $response->withJson(['content' => $content, 'format' => $extension]);
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
    public function deleteTmpFile(Request $request, Response $response)
    {
        $queryParams = $request->getQueryParams();

        if (!Validator::stringType()->notEmpty()->validate($queryParams['token'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query token is empty or not a string']);
        }

        $tokenCheckResult = CollaboraOnlineController::checkToken(['token' => $queryParams['token']]);
        if (!empty($tokenCheckResult['errors'])) {
            return $response->withStatus($tokenCheckResult['code'])->withJson(['errors' => $tokenCheckResult['errors']]);
        }

        $document = CollaboraOnlineController::getDocument([
            'id'     => $tokenCheckResult['resId'],
            'type'   => $tokenCheckResult['type'],
            'format' => $tokenCheckResult['format']
        ]);
        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
        }

        $extension = pathinfo($document['filename'], PATHINFO_EXTENSION);
274
        $filename = "collabora_{$GLOBALS['id']}_{$tokenCheckResult['type']}_{$tokenCheckResult['resId']}.{$extension}";
275
276
277
278
279
280
281
282
283
284
        $tmpPath = CoreConfigModel::getTmpPath();
        $pathToDocument = $tmpPath . $filename;

        if (file_exists($pathToDocument)) {
            unlink($pathToDocument);
        }

        return $response->withStatus(204);
    }

285
286
    public static function isAvailable(Request $request, Response $response)
    {
287
288
289
290
        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_document_editors', 'select' => ['value']]);
        $configuration = !empty($configuration['value']) ? json_decode($configuration['value'], true) : [];

        if (empty($configuration) || empty($configuration['collaboraonline'])) {
291
            return $response->withStatus(400)->withJson(['errors' => 'Collabora Online is not enabled', 'lang' => 'collaboraOnlineNotEnabled']);
292
        } elseif (empty($configuration['collaboraonline']['uri'])) {
293
            return $response->withStatus(400)->withJson(['errors' => 'Collabora Online server_uri is empty', 'lang' => 'uriIsEmpty']);
294
        } elseif (empty($configuration['collaboraonline']['port'])) {
295
296
297
            return $response->withStatus(400)->withJson(['errors' => 'Collabora Online server_port is empty', 'lang' => 'portIsEmpty']);
        }

298
299
        $uri  = $configuration['collaboraonline']['uri'];
        $port = (string)$configuration['collaboraonline']['port'];
300

301
        $isAvailable = DocumentEditorController::isAvailable(['uri' => $uri, 'port' => $port]);
302

303
304
        if (!empty($isAvailable['errors'])) {
            return $response->withStatus(400)->withJson($isAvailable);
305
306
307
308
309
310
311
        }

        return $response->withJson(['isAvailable' => $isAvailable]);
    }

    public static function getConfiguration(Request $request, Response $response)
    {
312
313
        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_document_editors', 'select' => ['value']]);
        $configuration = !empty($configuration['value']) ? json_decode($configuration['value'], true) : [];
314

315
        if (empty($configuration) || empty($configuration['collaboraonline']) || empty($configuration['collaboraonline']['uri'])) {
316
            return $response->withStatus(400)->withJson(['errors' => 'Collabora Online is not enabled', 'lang' => 'collaboraOnlineNotEnabled']);
317
318
319
320
321
322
323
324
325
        }

        $body = $request->getParsedBody();
        if (!Validator::intVal()->notEmpty()->validate($body['resId'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body resId is empty or not an integer']);
        }
        if (!Validator::stringType()->notEmpty()->validate($body['type'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body type is empty or not a string']);
        }
326
327
        if (!empty($body['format']) && !Validator::stringType()->validate($body['format'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body format is not a string']);
328
        }
329
330
331
        if (!empty($body['path']) && !Validator::stringType()->validate($body['path'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body path is not a string']);
        }
332
333
334
335
336
337
        if (!empty($body['data']) && !Validator::arrayType()->validate($body['data'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body data is not a string']);
        }
        if (!empty($body['lang']) && !Validator::stringType()->validate($body['lang'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body lang is not a string']);
        }
338

339
        $document = CollaboraOnlineController::getDocument([
340
341
            'id'     => $body['resId'],
            'type'   => $body['type'],
342
343
            'format' => $body['format'],
            'path'   => $body['path']
344
345
346
347
        ]);

        if (!empty($document['errors'])) {
            return $response->withStatus($document['code'])->withJson(['errors' => $document['errors']]);
348
        }
349

350
351
        $extension = pathinfo($document['filename'], PATHINFO_EXTENSION);

352
        $url = $configuration['collaboraonline']['uri'] . ':' . $configuration['collaboraonline']['port'];
353

354
        $coreUrl   = str_replace('rest/', '', UrlController::getCoreUrl());
355
        $serverSsl = $configuration['collaboraonline']['ssl'];
356
357
358
359
360
361
362
363
364
365
366
        if (!empty($serverSsl)) {
            if (strpos($coreUrl, 'https') === false) {
                return $response->withStatus(400)->withJson(['errors' => 'Collabora Online cannot be configured to use SSL if Maarch Courrier is not using SSL']);
            }
            $url = 'https://' . $url;
        } else {
            if (strpos($coreUrl, 'https') !== false) {
                return $response->withStatus(400)->withJson(['errors' => 'Collabora Online has to be configured to use SSL if Maarch Courrier is using SSL']);
            }
        }

367
        $discovery = CurlModel::exec([
368
369
            'url'    => $url . '/hosting/discovery',
            'method' => 'GET',
370
            'isXml'  => true
371
372
373
374
375
376
        ]);

        if ($discovery['code'] != 200) {
            return $response->withStatus(400)->withJson(['errors' => 'Collabora discovery failed']);
        }

377
378
379
380
381
382
383
        $version4 = false;
        foreach ($discovery['headers'] as $header) {
            if (strpos($header, 'UserAgent') !== false) {
                $version4 = strpos($header, 'LOOLWSD WOPI Agent 4') !== false;
            }
        }

384
        $urlSrc = null;
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        if ($version4) {
            foreach ($discovery['response']->{'net-zone'}->app as $app) {
                if ($app->action['ext'] == $extension) {
                    $urlSrc = (string) $app->action['urlsrc'];
                    break;
                }
            }
        } else {
            foreach ($discovery['response']->{'net-zone'}->app as $app) {
                foreach ($app->action as $action) {
                    if ($action['ext'] == $extension) {
                        $urlSrc = (string) $action['urlsrc'];
                        break;
                    }
                }
400
401
402
            }
        }

403
404
405
        if (empty($urlSrc)) {
            return $response->withStatus(400)->withJson(['errors' => 'File cannot be edited with Collabora Online', 'lang' => 'collaboraOnlineEditDenied']);
        }
406

407
408
409
410
411
        $dataToMerge = ['userId' => $GLOBALS['id']];
        if (!empty($body['data']) && is_array($body['data'])) {
            $dataToMerge = array_merge($dataToMerge, $body['data']);
        }

412
413
414
        $payload = [
            'userId' => $GLOBALS['id'],
            'resId'  => $body['resId'],
415
            'type'   => $body['type'],
416
417
            'format' => $extension,
            'data'   => json_encode($dataToMerge)
418
419
420
421
        ];

        $jwt = JWT::encode($payload, CoreConfigModel::getEncryptKey());

422
        $urlIFrame = $urlSrc . 'WOPISrc=' . $coreUrl . 'rest/wopi/files/' . $body['resId'] . '&access_token=' . $jwt . '&NotWOPIButIframe=true';
423

424
425
        if (!empty($body['lang'])) {
            $urlIFrame .= '&lang=' . $body['lang'];
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
        }

        return $response->withJson(['url' => $urlIFrame, 'token' => $jwt, 'coreUrl' => $coreUrl]);
    }

    public function saveTmpEncodedDocument(Request $request, Response $response)
    {
        $body = $request->getParsedBody();

        if (!PrivilegeController::hasPrivilege(['privilegeId' => 'admin_templates', 'userId' => $GLOBALS['id']])) {
            return ['code' => 403, 'errors' => 'Service forbidden'];
        }

        if (!Validator::stringType()->notEmpty()->validate($body['content'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body content is empty or not a string']);
        }
        if (!Validator::stringType()->notEmpty()->validate($body['format'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body format is empty or not a string']);
        }
        if (!Validator::intVal()->notEmpty()->validate($body['key'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body key is empty or not an integer']);
        }

        $fileContent = base64_decode($body['content']);
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->buffer($fileContent);
        if (!StoreController::isFileAllowed(['extension' => $body['format'], 'type' => $mimeType]) || !in_array($mimeType, TemplateController::AUTHORIZED_MIMETYPES)) {
            return $response->withStatus(400)->withJson(['errors' => _WRONG_FILE_TYPE . ' : '.$mimeType]);
        }

        $tmpPath = CoreConfigModel::getTmpPath();
457
        $filename = "collabora_encoded_{$GLOBALS['id']}_{$body['key']}.{$body['format']}";
458
459
460
461
462
463
464
465
        $fileContent = base64_decode($body['content']);

        $put = file_put_contents($tmpPath . $filename, $fileContent);
        if ($put === false) {
            return $response->withStatus(400)->withJson(['errors' => 'File put contents failed']);
        }

        return $response->withStatus(204);
466
    }
467
468
469

    private static function checkToken(array $args)
    {
470
        ValidatorModel::notEmpty($args, ['token']);
471
472
473
474
475
476
        ValidatorModel::stringType($args, ['token']);
        ValidatorModel::intVal($args, ['id']);

        try {
            $jwt = JWT::decode($args['token'], CoreConfigModel::getEncryptKey(), ['HS256']);
        } catch (\Exception $e) {
477
            return ['code' => 401, 'errors' => 'Collabora Online access token is invalid'];
478
479
        }

480
        if (empty($jwt->resId) || empty($jwt->userId) || empty($jwt->type)) {
481
            return ['code' => 401, 'errors' => 'Collabora Online access token is invalid'];
482
483
        }

484
485
        if (!empty($args['id']) && $jwt->resId != $args['id']) {
            return ['code' => 401, 'errors' => 'Collabora Online access token is invalid'];
486
487
488
489
490
        }

        CoreController::setGlobals(['userId' => $jwt->userId]);

        return [
491
492
            'type'   => $jwt->type,
            'resId'  => $jwt->resId,
493
494
            'format' => $jwt->format,
            'data'   => json_decode($jwt->data, true)
495
496
        ];
    }
497

498
    public static function getDocument(array $args)
499
    {
500
501
        ValidatorModel::notEmpty($args, ['id', 'type']);
        ValidatorModel::stringType($args, ['type', 'format', 'path']);
502
503
        ValidatorModel::intVal($args, ['id']);

504
        if ($args['type'] == 'resourceCreation' || $args['type'] == 'attachmentCreation') {
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
            $document = TemplateModel::getById(['select' => ['template_file_name', 'template_target', 'template_path', 'template_file_name'], 'id' => $args['id']]);
            if (empty($document)) {
                return ['code' => 400, 'errors' => 'Document does not exist'];
            }

            $templateAssociation = TemplateAssociationModel::get([
                'select' => ['value_field'],
                'where'  => ['template_id = ?'],
                'data'   => [$args['id']]
            ]);
            $templateAssociation = array_column($templateAssociation, 'value_field');

            $userEntities = UserEntityModel::get([
                'select' => ['entity_id'],
                'where'  => ['user_id = ?'],
                'data'   => [$GLOBALS['id']]
            ]);
            $userEntities = array_column($userEntities, 'entity_id');

            $inPerimeter = false;
            foreach ($userEntities as $userEntity) {
                if (in_array($userEntity, $templateAssociation)) {
                    $inPerimeter = true;
                    break;
                }
            }

            if (!$inPerimeter) {
                return ['code' => 400, 'errors' => 'Template is out of perimeter'];
            }

536
            $templateTarget = $args['type'] == 'resourceCreation' ? 'indexingFile' : 'attachments';
537
538
539
540
541
542
543
544
545
            if ($document['template_target'] != $templateTarget) {
                return ['code' => 400, 'errors' => 'Template is not for resource creation'];
            }
            $document['filename'] = $document['template_file_name'];
            $document['docserver_id'] = 'TEMPLATES';
            $document['path'] = $document['template_path'];

            $document['modification_date'] = new \DateTime('now');
            $document['modification_date'] = $document['modification_date']->format(\DateTime::ISO8601);
546
        } elseif ($args['type'] == 'resourceModification') {
547
548
549
550
            if (!ResController::hasRightByResId(['resId' => [$args['id']], 'userId' => $GLOBALS['id']])) {
                return ['code' => 403, 'errors' => 'Document out of perimeter'];
            }

551
            $document = ResModel::getById(['select' => ['docserver_id', 'path', 'filename', 'version', 'fingerprint', 'modification_date'], 'resId' => $args['id']]);
552
553
554
555
556
557
558
559
560
561
562

            // If the document has a signed version, it cannot be edited
            $convertedDocument = AdrModel::getDocuments([
                'select' => ['docserver_id', 'path', 'filename', 'fingerprint'],
                'where'  => ['res_id = ?', 'type = ?', 'version = ?'],
                'data'   => [$args['resId'], 'SIGN', $document['version']],
                'limit'  => 1
            ]);
            if (!empty($convertedDocument[0])) {
                return ['code' => 400, 'errors' => 'Document was signed : it cannot be edited'];
            }
563
        } elseif ($args['type'] == 'attachmentModification') {
564
565
566
567
568
            $document = AttachmentModel::getById([
                'select' => ['res_id_master', 'filename', 'filesize', 'modification_date', 'docserver_id', 'path', 'fingerprint', 'status'],
                'id' => $args['id']
            ]);
            if (empty($document) || in_array($document['status'], ['DEL', 'OBS'])) {
569
570
571
572
573
574
575
                return ['code' => 400, 'errors' => 'Document does not exist'];
            }

            if (!ResController::hasRightByResId(['resId' => [$document['res_id_master']], 'userId' => $GLOBALS['id']])) {
                return ['code' => 403, 'errors' => 'Document out of perimeter'];
            }

576
577
578
            if ($document['status'] == 'SIGN') {
                return ['code' => 400, 'errors' => 'Document was signed : it cannot be edited'];
            }
579
        } elseif ($args['type'] == 'templateModification') {
580
581
582
583
584
            if (!PrivilegeController::hasPrivilege(['privilegeId' => 'admin_templates', 'userId' => $GLOBALS['id']])) {
                return ['code' => 403, 'errors' => 'Service forbidden'];
            }

            $document = TemplateModel::getById(['select' => ['template_file_name', 'template_target', 'template_path', 'template_file_name'], 'id' => $args['id']]);
585
586
587
588
589
590
591
592
            if (empty($document)) {
                return ['code' => 400, 'errors' => 'Document does not exist'];
            }

            $document['filename'] = $document['template_file_name'];
            $document['docserver_id'] = 'TEMPLATES';
            $document['path'] = $document['template_path'];

593
594
            $document['modification_date'] = new \DateTime('now');
            $document['modification_date'] = $document['modification_date']->format(\DateTime::ISO8601);
595
        } elseif ($args['type'] == 'templateEncoded') {
596
597
598
599
600
601
602
603
            if (!PrivilegeController::hasPrivilege(['privilegeId' => 'admin_templates', 'userId' => $GLOBALS['id']])) {
                return ['code' => 403, 'errors' => 'Service forbidden'];
            }

            $document['filename'] = "collabora_encoded_{$GLOBALS['id']}_{$args['id']}.{$args['format']}";
            $document['docserver_id'] = '';
            $document['path'] = CoreConfigModel::getTmpPath();

604
605
            $document['modification_date'] = new \DateTime('now');
            $document['modification_date'] = $document['modification_date']->format(\DateTime::ISO8601);
606
        } elseif ($args['type'] == 'templateCreation') {
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
            if (!PrivilegeController::hasPrivilege(['privilegeId' => 'admin_templates', 'userId' => $GLOBALS['id']])) {
                return ['code' => 403, 'errors' => 'Service forbidden'];
            }

            $document['filename'] = "collabora_template_{$GLOBALS['id']}_{$args['id']}.{$args['format']}";
            $document['docserver_id'] = '';
            $document['path'] = CoreConfigModel::getTmpPath();

            if (!file_exists($document['path'] . $document['filename'])) {
                if (empty($args['path'])) {
                    return ['code' => 400, 'errors' => 'Argument path is missing'];
                }

                $customId = CoreConfigModel::getCustomId();
                if (!empty($customId) && is_dir("custom/{$customId}/modules/templates/templates/styles/")) {
                    $stylesPath = "custom/{$customId}/modules/templates/templates/styles/";
                } else {
                    $stylesPath = 'modules/templates/templates/styles/';
                }
                if (strpos($args['path'], $stylesPath) !== 0 || substr_count($args['path'], '.') != 1) {
                    return ['code' => 400, 'errors' => 'Template path is not valid'];
                }

                if (!file_exists($args['path'])) {
                    return ['code' => 400, 'errors' => 'Document does not exists'];
                }

                $fileContent = file_get_contents($args['path']);
                if ($fileContent === false) {
                    return ['code' => 400, 'errors' => 'Document does not exists'];
                }

                $result = file_put_contents($document['path'] . $document['filename'], $fileContent);
                if ($result === false) {
                    return ['code' => 400, 'errors' => 'Document does not exists'];
                }
            }

645
            $document['modification_date'] = new \DateTime('now');
646
647
            $document['modification_date'] = $document['modification_date']->format(\DateTime::ISO8601);
        } else {
648
            return ['code' => 400, 'errors' => 'Not a valid document type'];
649
650
651
652
653
654
655
656
        }

        if (empty($document['filename'])) {
            return ['code' => 400, 'errors' => 'Document has no file'];
        }

        return $document;
    }
657
}