Completed
Push — 1.11.x ( 65444a...8a35a0 )
by
unknown
01:41 queued 56s
created

CourseDriver::upload()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 57
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 57
rs 8.5386
cc 7
nc 7
nop 5

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Component\Editor\Driver;
5
6
use CourseHome;
7
8
/**
9
 * Class CourseDriver.
10
 *
11
 * @package Chamilo\CoreBundle\Component\Editor\Driver
12
 */
13
class CourseDriver extends Driver implements DriverInterface
14
{
15
    public $name = 'CourseDriver';
16
    public $visibleFiles = [];
17
    private $coursePath;
18
19
    /**
20
     * Setups the folder.
21
     */
22
    public function setup()
23
    {
24
        $userId = api_get_user_id();
25
        $userInfo = api_get_user_info();
26
        $sessionId = api_get_session_id();
27
        $courseInfo = $this->connector->course;
28
29
        if (!empty($courseInfo)) {
30
            $coursePath = api_get_path(SYS_COURSE_PATH);
31
            $courseDir = $courseInfo['directory'].'/document';
32
            $baseDir = $coursePath.$courseDir;
33
            $this->coursePath = $baseDir;
34
35
            // Creates shared folder
36
            if (!file_exists($baseDir.'/shared_folder')) {
37
                $title = get_lang('UserFolders');
38
                $folderName = '/shared_folder';
39
                //$groupId = 0;
40
                $visibility = 0;
41
                create_unexisting_directory(
42
                    $courseInfo,
43
                    $userId,
44
                    $sessionId,
45
                    0,
46
                    null,
47
                    $baseDir,
48
                    $folderName,
49
                    $title,
50
                    $visibility
51
                );
52
            }
53
54
            // Creates user-course folder
55
            if (!file_exists($baseDir.'/shared_folder/sf_user_'.$userId)) {
56
                $title = $userInfo['complete_name'];
57
                $folderName = '/shared_folder/sf_user_'.$userId;
58
                $visibility = 1;
59
                create_unexisting_directory(
60
                    $courseInfo,
61
                    $userId,
62
                    $sessionId,
63
                    0,
64
                    null,
65
                    $baseDir,
66
                    $folderName,
67
                    $title,
68
                    $visibility
69
                );
70
            }
71
        }
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function getConfiguration()
78
    {
79
        if ($this->allow()) {
80
            //$translator = $this->connector->translator;
81
            //$code = $this->connector->course->getCode();
82
            $courseCode = $this->connector->course['code'];
83
            $alias = $courseCode.' '.get_lang('Documents');
84
            $userId = api_get_user_id();
85
            $config = [
86
                'driver' => 'CourseDriver',
87
                'path' => $this->getCourseDocumentSysPath(),
88
                'URL' => $this->getCourseDocumentRelativeWebPath(),
89
                'accessControl' => [$this, 'access'],
90
                'alias' => $alias,
91
                'attributes' => [
92
                    // Hide shared_folder
93
                    [
94
                        'pattern' => '/shared_folder/',
95
                        'read' => false,
96
                        'write' => false,
97
                        'hidden' => true,
98
                        'locked' => false,
99
                    ],
100
                    [
101
                        'pattern' => '/^\/index.html$/',
102
                        'read' => false,
103
                        'write' => false,
104
                        'hidden' => true,
105
                        'locked' => false,
106
                    ],
107
                ],
108
            ];
109
110
            // admin/teachers can create dirs from ckeditor
111
            if ($this->allowToEdit()) {
112
                $config['attributes'][] = [
113
                    'pattern' => '/^\/learning_path$/', // block delete learning_path
114
                    'read' => true,
115
                    'write' => false,
116
                    'hidden' => false,
117
                    'locked' => true,
118
                ];
119
                $config['attributes'][] = [
120
                    'pattern' => '/learning_path\/(.*)/', // allow edit/delete inside learning_path
121
                    'read' => true,
122
                    'write' => true,
123
                    'hidden' => false,
124
                    'locked' => false,
125
                ];
126
127
                $defaultDisabled = $this->connector->getDefaultDriverSettings()['disabled'];
128
                $defaultDisabled = array_flip($defaultDisabled);
129
                unset($defaultDisabled['mkdir']);
130
                $defaultDisabled = array_flip($defaultDisabled);
131
                $config['disabled'] = $defaultDisabled;
132
            } else {
133
                $protectedFolders = \DocumentManager::getProtectedFolderFromStudent();
134
                foreach ($protectedFolders as $folder) {
135
                    $config['attributes'][] = [
136
                        'pattern' => $folder.'/',
137
                        'read' => false,
138
                        'write' => false,
139
                        'hidden' => true,
140
                        'locked' => false,
141
                    ];
142
                }
143
            }
144
145
            $foldersToHide = \DocumentManager::get_all_document_folders(
146
                $this->connector->course,
147
                null,
148
                false,
149
                true
150
            );
151
152
            // Teachers can see all files and folders see #1425
153
            if ($this->allowToEdit()) {
154
                $foldersToHide = [];
155
            }
156
157
            if (!empty($foldersToHide)) {
158
                foreach ($foldersToHide as $folder) {
159
                    $config['attributes'][] = [
160
                        'pattern' => '!'.$folder.'!',
161
                        'read' => false,
162
                        'write' => false,
163
                        'hidden' => true,
164
                        'locked' => false,
165
                    ];
166
                }
167
            }
168
169
            // Hide all groups folders
170
            $config['attributes'][] = [
171
                'pattern' => '!_groupdocs_!',
172
                'read' => false,
173
                'write' => false,
174
                'hidden' => true,
175
                'locked' => false,
176
            ];
177
178
            // Allow only the groups I have access
179
            $allGroups = \GroupManager::getAllGroupPerUserSubscription($userId);
180
            if (!empty($allGroups)) {
181
                foreach ($allGroups as $groupInfo) {
182
                    $groupId = $groupInfo['iid'];
183
                    if (\GroupManager::user_has_access(
184
                        $userId,
185
                        $groupId,
186
                        \GroupManager::GROUP_TOOL_DOCUMENTS
187
                    )) {
188
                        $config['attributes'][] = [
189
                            'pattern' => '!'.$groupInfo['secret_directory'].'!',
190
                            'read' => true,
191
                            'write' => false,
192
                            'hidden' => false,
193
                            'locked' => false,
194
                        ];
195
                    }
196
                }
197
            }
198
199
            return $config;
200
        }
201
202
        return [];
203
    }
204
205
    /**
206
     * This is the absolute document course path like
207
     * /var/www/portal/data/courses/XXX/document/.
208
     *
209
     * @return string
210
     */
211
    public function getCourseDocumentSysPath()
212
    {
213
        $url = '';
214
        if ($this->allow()) {
215
            $directory = $this->getCourseDirectory();
216
            $coursePath = $this->connector->paths['sys_course_path'];
217
            $url = $coursePath.$directory.'/document/';
218
        }
219
220
        return $url;
221
    }
222
223
    /**
224
     * @return string
225
     */
226
    public function getCourseDocumentRelativeWebPath()
227
    {
228
        $url = null;
229
        if ($this->allow()) {
230
            $directory = $this->getCourseDirectory();
231
            $url = api_get_path(REL_COURSE_PATH).$directory.'/document/';
232
        }
233
234
        return $url;
235
    }
236
237
    /**
238
     * @return string
239
     */
240
    public function getCourseDocumentWebPath()
241
    {
242
        $url = null;
243
        if ($this->allow()) {
244
            $directory = $this->getCourseDirectory();
245
            $url = api_get_path(WEB_COURSE_PATH).$directory.'/document/';
246
        }
247
248
        return $url;
249
    }
250
251
    /**
252
     * @return string
253
     */
254
    public function getCourseDirectory()
255
    {
256
        return $this->connector->course['directory'];
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262
    public function upload($fp, $dst, $name, $tmpname, $hashes = [])
263
    {
264
        // Needed to load course information in elfinder
265
        $this->setConnectorFromPlugin();
266
267
        if ($this->allowToEdit()) {
268
            // upload file by elfinder.
269
            $size = filesize($tmpname);
270
271
            // check the max filesize.
272
            $maxFileSize = getIniMaxFileSizeInBytes();
273
            if ($maxFileSize > 0 && $size > $maxFileSize) {
274
                $errorUploadMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
275
                $this->addError($errorUploadMessage);
276
277
                return false;
278
            }
279
280
            $maxSpace = \DocumentManager::get_course_quota($this->connector->course['code']);
281
            // Check if there is enough space to save the file.
282
            if (!\DocumentManager::enough_space($size, $maxSpace)) {
283
                return false;
284
            }
285
286
            $result = parent::upload($fp, $dst, $name, $tmpname);
287
            $name = $result['name'];
288
            $filtered = \URLify::filter($result['name'], 80, '', true);
289
290
            if (strcmp($name, $filtered) != 0) {
291
                $result = $this->customRename($result['hash'], $filtered);
292
            }
293
294
            $realPath = $this->realpath($result['hash']);
295
            if (!empty($realPath)) {
296
                // Getting file info
297
                //$info = $elFinder->exec('file', array('target' => $file['hash']));
298
                /** @var elFinderVolumeLocalFileSystem $volume */
299
                //$volume = $info['volume'];
300
                //$root = $volume->root();
301
                //var/www/chamilogits/data/courses/NEWONE/document
302
                $realPathRoot = $this->getCourseDocumentSysPath();
303
304
                // Removing course path
305
                $realPath = str_replace($realPathRoot, '/', $realPath);
306
                add_document(
307
                    $this->connector->course,
308
                    $realPath,
309
                    'file',
310
                    (int) $result['size'],
311
                    $result['name']
312
                );
313
            }
314
315
            return $result;
316
        }
317
318
        return false;
319
    }
320
321
    /**
322
     * {@inheritdoc}
323
     */
324
    public function rm($hash)
325
    {
326
        // elfinder does not delete the file
327
        //parent::rm($hash);
328
        $this->setConnectorFromPlugin();
329
330
        if ($this->allowToEdit()) {
331
            $path = $this->decode($hash);
332
            $stat = $this->stat($path);
333
            $stat['realpath'] = $path;
334
            $this->removed[] = $stat;
335
336
            $realFilePath = $path;
337
            $coursePath = $this->getCourseDocumentSysPath();
338
            $filePath = str_replace($coursePath, '/', $realFilePath);
339
340
            \DocumentManager::delete_document(
341
                $this->connector->course,
342
                $filePath,
343
                $coursePath
344
            );
345
346
            return true;
347
        }
348
349
        return false;
350
    }
351
352
    /**
353
     * @return bool
354
     */
355
    public function allow()
356
    {
357
        //if ($this->connector->security->isGranted('ROLE_ADMIN')) {
358
        if (api_is_anonymous()) {
359
            return false;
360
        }
361
362
        $isAllowedToEdit = api_is_allowed_to_edit();
363
364
        $block = api_get_configuration_value('block_editor_file_manager_for_students');
365
        if ($block && !$isAllowedToEdit) {
366
            return false;
367
        }
368
369
        if (isset($this->connector->course) && !empty($this->connector->course)) {
370
            $isDocumentsToolVisible = CourseHome::getToolVisibility(
371
                TOOL_DOCUMENT,
372
                api_get_course_int_id(),
373
                api_get_session_id()
374
            );
375
376
            if (!$isDocumentsToolVisible && !$isAllowedToEdit) {
377
                return false;
378
            }
379
380
            return true;
381
        }
382
383
        return false;
384
    }
385
386
    /**
387
     * Allow to upload/delete folder or files.
388
     *
389
     * @return bool
390
     */
391
    public function allowToEdit()
392
    {
393
        $allow = $this->allow();
394
395
        return $allow && api_is_allowed_to_edit(null, true);
396
    }
397
398
    /**
399
     * {@inheritdoc}
400
     */
401
    public function mkdir($path, $name)
402
    {
403
        // Needed to load course information in elfinder
404
        $this->setConnectorFromPlugin();
405
406
        if ($this->allowToEdit() === false) {
407
            return false;
408
        }
409
410
        $name = api_replace_dangerous_char($name);
411
        $result = parent::mkdir($path, $name);
412
413
        if ($result && isset($result['hash'])) {
414
            $_course = $this->connector->course;
415
            $realPathRoot = $this->getCourseDocumentSysPath();
416
            $realPath = $this->realpath($result['hash']);
417
418
            // Removing course path
419
            $newPath = str_replace($realPathRoot, '/', $realPath);
420
            $documentId = add_document(
421
                $_course,
422
                $newPath,
423
                'folder',
424
                0,
425
                $name,
426
                null,
427
                0,
428
                true,
429
                api_get_group_id(),
430
                api_get_session_id(),
431
                api_get_user_id()
432
            );
433
434
            if (empty($documentId)) {
435
                $this->rm($result['hash']);
436
437
                return false;
438
            }
439
440
            return $result;
441
        }
442
443
        return false;
444
    }
445
446
    /**
447
     * @param string $attr
448
     * @param string $path
449
     * @param $data
450
     * @param CourseDriver $volume
451
     */
452
    /*public function access($attr, $path, $data, $volume)
453
    {
454
        error_log($path);
455
        return true;
456
        if ($path == $this->coursePath) {
457
458
            return true;
459
        }
460
461
        $allowToEdit = $this->allowToEdit();
462
        if ($allowToEdit) {
463
            return true;
464
        }
465
466
        $path = str_replace($this->coursePath, '', $path);
467
        $documentId = \DocumentManager::get_document_id($this->connector->course, $path);
468
469
        if ($documentId) {
470
471
            $result = \DocumentManager::is_visible_by_id(
472
                $documentId,
473
                $this->connector->course,
474
                api_get_session_id(),
475
                api_get_user_id()
476
            );
477
            return false;
478
        }
479
480
        return false;
481
    }*/
482
}
483