Passed
Push — master ( 262b3f...86674d )
by Yannick
09:44
created

OnlyofficeDocumentManager::getDocExtByType()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 16
rs 9.6111
1
<?php
2
/**
3
 * (c) Copyright Ascensio System SIA 2025.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
use DocumentManager as ChamiloDocumentManager;
18
use Onlyoffice\DocsIntegrationSdk\Manager\Document\DocumentManager;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, DocumentManager. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
20
class OnlyofficeDocumentManager extends DocumentManager
21
{
22
    private $docInfo;
23
24
    public function __construct($settingsManager, array $docInfo, $formats = null, $systemLangCode = 'en')
25
    {
26
        $formats = new OnlyofficeFormatsManager();
27
        parent::__construct($settingsManager, $formats, $systemLangCode);
28
        $this->docInfo = $docInfo;
29
    }
30
31
    public function getDocumentKey(string $fileId, $courseCode, bool $embedded = false)
32
    {
33
        if (!isset($this->docInfo['absolute_path'])) {
34
            return null;
35
        }
36
        $mtime = filemtime($this->docInfo['absolute_path']);
37
        $key = $mtime.$courseCode.$fileId;
38
39
        return self::generateRevisionId($key);
40
    }
41
42
    public function getDocumentName(string $fileId = '')
43
    {
44
        return $this->docInfo['title'];
45
    }
46
47
    public static function getLangMapping()
48
    {
49
    }
50
51
    public function getFileUrl(string $fileId)
52
    {
53
        $data = [
54
            'type' => 'download',
55
            'courseId' => api_get_course_int_id(),
56
            'userId' => api_get_user_id(),
57
            'docId' => $fileId,
58
            'sessionId' => api_get_session_id(),
59
        ];
60
61
        if (!empty($this->getGroupId())) {
62
            $data['groupId'] = $this->getGroupId();
63
        }
64
65
        if (isset($this->docInfo['path']) && str_contains($this->docInfo['path'], 'exercises/')) {
66
            $data['doctype'] = 'exercise';
67
            $data['docPath'] = urlencode($this->docInfo['path']);
68
        }
69
70
        $jwtManager = new OnlyofficeJwtManager($this->settingsManager);
71
        $hashUrl = $jwtManager->getHash($data);
72
73
        return api_get_path(WEB_PLUGIN_PATH).$this->settingsManager->plugin->getPluginName().'/callback.php?hash='.$hashUrl;
74
    }
75
76
    public function getGroupId()
77
    {
78
        $groupId = isset($_GET['groupId']) && !empty($_GET['groupId']) ? $_GET['groupId'] : null;
79
80
        return $groupId;
81
    }
82
83
    public function getCallbackUrl(string $fileId)
84
    {
85
        $data = [
86
            'type' => 'track',
87
            'courseId' => api_get_course_int_id(),
88
            'userId' => api_get_user_id(),
89
            'docId' => $fileId,
90
            'sessionId' => api_get_session_id(),
91
        ];
92
93
        if (!empty($this->getGroupId())) {
94
            $data['groupId'] = $this->getGroupId();
95
        }
96
97
        if (isset($this->docInfo['path']) && str_contains($this->docInfo['path'], 'exercises/')) {
98
            $data['doctype'] = 'exercise';
99
            $data['docPath'] = urlencode($this->docInfo['path']);
100
        }
101
102
        $jwtManager = new OnlyofficeJwtManager($this->settingsManager);
103
        $hashUrl = $jwtManager->getHash($data);
104
105
        return api_get_path(WEB_PLUGIN_PATH).'onlyoffice/callback.php?hash='.$hashUrl;
106
    }
107
108
    public function getGobackUrl(string $fileId): string
109
    {
110
        if (!empty($this->docInfo)) {
111
            if (isset($this->docInfo['path']) && str_contains($this->docInfo['path'], 'exercises/')) {
112
                return api_get_path(WEB_CODE_PATH).'exercise/exercise_submit.php'
113
                    .'?cidReq='.Security::remove_XSS(api_get_course_id())
114
                    .'&id_session='.Security::remove_XSS(api_get_session_id())
115
                    .'&gidReq='.Security::remove_XSS($this->getGroupId())
116
                    .'&exerciseId='.Security::remove_XSS($this->docInfo['exercise_id']);
117
            }
118
119
            return self::getUrlToLocation(api_get_course_id(), api_get_session_id(), $this->getGroupId(), $this->docInfo['parent_id'], $this->docInfo['path'] ?? '');
120
        }
121
122
        return '';
123
    }
124
125
    /**
126
     * Return location file in Chamilo documents or exercises.
127
     */
128
    public static function getUrlToLocation($courseCode, $sessionId, $groupId, $folderId, $filePath = ''): string
129
    {
130
        if (!empty($filePath) && str_contains($filePath, 'exercises/')) {
131
            return api_get_path(WEB_CODE_PATH).'exercise/exercise_submit.php'
132
                .'?cidReq='.Security::remove_XSS($courseCode)
133
                .'&id_session='.Security::remove_XSS($sessionId)
134
                .'&gidReq='.Security::remove_XSS($groupId)
135
                .'&exerciseId='.Security::remove_XSS($folderId);
136
        }
137
138
        return api_get_path(WEB_CODE_PATH).'document/document.php'
139
            .'?cidReq='.Security::remove_XSS($courseCode)
140
            .'&id_session='.Security::remove_XSS($sessionId)
141
            .'&gidReq='.Security::remove_XSS($groupId)
142
            .'&id='.Security::remove_XSS($folderId);
143
    }
144
145
    public function getCreateUrl(string $fileId)
146
    {
147
    }
148
149
    /**
150
     * Get the value of docInfo.
151
     */
152
    public function getDocInfo($elem = null)
153
    {
154
        if (empty($elem)) {
155
            return $this->docInfo;
156
        } else {
157
            if (isset($this->docInfo[$elem])) {
158
                return $this->docInfo[$elem];
159
            }
160
161
            return [];
162
        }
163
    }
164
165
    /**
166
     * Set the value of docInfo.
167
     */
168
    public function setDocInfo($docInfo)
169
    {
170
        $this->docInfo = $docInfo;
171
    }
172
173
    /**
174
     * Return file extension by file type.
175
     */
176
    public static function getDocExtByType(string $type): string
177
    {
178
        if ('text' === $type) {
179
            return 'docx';
180
        }
181
        if ('spreadsheet' === $type) {
182
            return 'xlsx';
183
        }
184
        if ('presentation' === $type) {
185
            return 'pptx';
186
        }
187
        if ('formTemplate' === $type) {
188
            return 'pdf';
189
        }
190
191
        return '';
192
    }
193
194
    /**
195
     * Create new file.
196
     */
197
    public static function createFile(
198
        string $basename,
199
        string $fileExt,
200
        int $folderId,
201
        int $userId,
202
        int $sessionId,
203
        int $courseId,
204
        int $groupId,
205
        string $templatePath = ''): array
206
    {
207
        $courseInfo = api_get_course_info_by_id($courseId);
208
        $courseCode = $courseInfo['code'];
209
        $groupInfo = GroupManager::get_group_properties($groupId);
210
211
        $fileTitle = Security::remove_XSS($basename).'.'.$fileExt;
212
213
        $fileNameSuffix = ChamiloDocumentManager::getDocumentSuffix($courseInfo, $sessionId, $groupId);
214
        // Try to avoid directories browsing (remove .., slashes and backslashes)
215
        $patterns = ['#\.\./#', '#\.\.#', '#/#', '#\\\#'];
216
        $replacements = ['', '', '', ''];
217
        $fileName = preg_replace($patterns, $replacements, $basename).$fileNameSuffix.'.'.$fileExt;
218
219
        if (empty($templatePath)) {
220
            $templatePath = TemplateManager::getEmptyTemplate($fileExt);
221
        }
222
223
        $folderPath = '';
224
        $fileRelatedPath = '/';
225
        if (!empty($folderId)) {
226
            $document_data = ChamiloDocumentManager::get_document_data_by_id(
0 ignored issues
show
Deprecated Code introduced by
The function DocumentManager::get_document_data_by_id() has been deprecated: use $repo->find() ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

226
            $document_data = /** @scrutinizer ignore-deprecated */ ChamiloDocumentManager::get_document_data_by_id(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
227
                $folderId,
228
                $courseCode,
229
                true,
230
                $sessionId
231
            );
232
            $folderPath = $document_data['absolute_path'];
233
            $fileRelatedPath = $fileRelatedPath.substr($document_data['absolute_path_from_document'], 10).'/'.$fileName;
234
        } else {
235
            $folderPath = api_get_path(SYS_COURSE_PATH).api_get_course_path($courseCode).'/document';
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function api_get_course_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

235
            $folderPath = api_get_path(SYS_COURSE_PATH)./** @scrutinizer ignore-call */ api_get_course_path($courseCode).'/document';
Loading history...
236
            if (!empty($groupId)) {
237
                $folderPath = $folderPath.'/'.$groupInfo['directory'];
238
                $fileRelatedPath = $groupInfo['directory'].'/';
239
            }
240
            $fileRelatedPath = $fileRelatedPath.$fileName;
241
        }
242
        $filePath = $folderPath.'/'.$fileName;
243
244
        if (file_exists($filePath)) {
245
            return ['error' => 'fileIsExist'];
246
        }
247
248
        if ($fp = @fopen($filePath, 'w')) {
249
            $content = file_get_contents($templatePath);
250
            fputs($fp, $content);
251
            fclose($fp);
252
253
            chmod($filePath, api_get_permissions_for_new_files());
254
255
            $documentId = add_document(
0 ignored issues
show
Bug introduced by
The function add_document was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

255
            $documentId = /** @scrutinizer ignore-call */ add_document(
Loading history...
256
                $courseInfo,
257
                $fileRelatedPath,
258
                'file',
259
                filesize($filePath),
260
                $fileTitle,
261
                null,
262
                false
263
            );
264
            if ($documentId) {
265
                api_item_property_update(
0 ignored issues
show
Bug introduced by
The function api_item_property_update was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

265
                /** @scrutinizer ignore-call */ 
266
                api_item_property_update(
Loading history...
266
                    $courseInfo,
267
                    TOOL_DOCUMENT,
268
                    $documentId,
269
                    'DocumentAdded',
270
                    $userId,
271
                    $groupInfo,
272
                    null,
273
                    null,
274
                    null,
275
                    $sessionId
276
                );
277
            } else {
278
                return ['error' => 'impossibleCreateFile'];
279
            }
280
        }
281
282
        return ['documentId' => $documentId];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $documentId does not seem to be defined for all execution paths leading up to this point.
Loading history...
283
    }
284
}
285