Completed
Push — master ( 1dcb59...0b8422 )
by Julito
09:48
created

CourseDriver   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 404
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 202
dl 0
loc 404
rs 8.8798
c 0
b 0
f 0
wmc 44

11 Methods

Rating   Name   Duplication   Size   Complexity  
B upload() 0 72 10
A rm() 0 26 2
A allowToEdit() 0 5 2
A getCourseDocumentRelativeWebPath() 0 9 2
A mkdir() 0 42 5
A getCourseDocumentWebPath() 0 9 2
A getCourseDocumentSysPath() 0 10 2
C getConfiguration() 0 97 10
A getCourseDirectory() 0 3 1
A allow() 0 12 4
A setup() 0 52 4

How to fix   Complexity   

Complex Class

Complex classes like CourseDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CourseDriver, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Component\Editor\Driver;
5
6
/**
7
 * Class CourseDriver.
8
 *
9
 * @package Chamilo\CoreBundle\Component\Editor\Driver
10
 */
11
class CourseDriver extends Driver implements DriverInterface
12
{
13
    public $name = 'CourseDriver';
14
    public $visibleFiles = [];
15
    private $coursePath;
16
17
    /**
18
     * Setups the folder.
19
     */
20
    public function setup()
21
    {
22
        $userId = api_get_user_id();
23
        $userInfo = api_get_user_info();
24
        $sessionId = api_get_session_id();
25
        $course = $this->connector->course;
26
27
        if (!empty($course)) {
28
            $coursePath = api_get_path(SYS_COURSE_PATH);
29
            $courseDir = $course->getDirectory().'/document';
30
            $baseDir = $coursePath.$courseDir;
31
            $this->coursePath = $baseDir;
32
33
            $courseInfo = [
34
                'real_id' => $this->connector->course->getId(),
35
                'code' => $this->connector->course->getCode(),
36
            ];
37
38
            // Creates shared folder
39
            if (!file_exists($baseDir.'/shared_folder')) {
40
                $title = get_lang('UserFolders');
41
                $folderName = '/shared_folder';
42
43
                $visibility = 0;
44
                create_unexisting_directory(
45
                    $courseInfo,
46
                    $userId,
47
                    $sessionId,
48
                    0,
49
                    null,
50
                    $baseDir,
51
                    $folderName,
52
                    $title,
53
                    $visibility
54
                );
55
            }
56
57
            // Creates user-course folder
58
            if (!file_exists($baseDir.'/shared_folder/sf_user_'.$userId)) {
59
                $title = $userInfo['complete_name'];
60
                $folderName = '/shared_folder/sf_user_'.$userId;
61
                $visibility = 1;
62
                create_unexisting_directory(
63
                    $courseInfo,
64
                    $userId,
65
                    $sessionId,
66
                    0,
67
                    null,
68
                    $baseDir,
69
                    $folderName,
70
                    $title,
71
                    $visibility
72
                );
73
            }
74
        }
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getConfiguration()
81
    {
82
        if ($this->connector->course && $this->allow()) {
83
            $courseCode = $this->connector->course->getCode();
84
            $alias = $courseCode.' '.get_lang('Documents');
85
            $userId = $this->connector->user->getId();
86
            // var_dump($this->getCourseDocumentSysPath());exit;
87
            $config = [
88
                'driver' => 'CourseDriver',
89
                'path' => $this->getCourseDocumentSysPath(),
90
                'URL' => $this->getCourseDocumentRelativeWebPath(),
91
                'accessControl' => [$this, 'access'],
92
                'alias' => $alias,
93
                'attributes' => [
94
                    // Hide shared_folder
95
                    [
96
                        'pattern' => '/shared_folder/',
97
                        'read' => false,
98
                        'write' => false,
99
                        'hidden' => true,
100
                        'locked' => false,
101
                    ],
102
                ],
103
            ];
104
105
            // admin/teachers can create dirs from ckeditor
106
            if ($this->allowToEdit()) {
107
                $defaultDisabled = $this->connector->getDefaultDriverSettings()['disabled'];
108
                $defaultDisabled = array_flip($defaultDisabled);
109
                unset($defaultDisabled['mkdir']);
110
                $defaultDisabled = array_flip($defaultDisabled);
111
                $config['disabled'] = $defaultDisabled;
112
            }
113
114
            $courseInfo = [
115
                'real_id' => $this->connector->course->getId(),
116
                'code' => $this->connector->course->getCode(),
117
            ];
118
119
            $foldersToHide = \DocumentManager::get_all_document_folders(
120
                $courseInfo,
121
                null,
122
                false,
123
                true
124
            );
125
126
            // Teachers can see all files and folders see #1425
127
            if ($this->allowToEdit()) {
128
                $foldersToHide = [];
129
            }
130
131
            if (!empty($foldersToHide)) {
132
                foreach ($foldersToHide as $folder) {
133
                    $config['attributes'][] = [
134
                        'pattern' => '!'.$folder.'!',
135
                        'read' => false,
136
                        'write' => false,
137
                        'hidden' => true,
138
                        'locked' => false,
139
                    ];
140
                }
141
            }
142
143
            // Hide all groups folders
144
            $config['attributes'][] = [
145
                'pattern' => '!_groupdocs_!',
146
                'read' => false,
147
                'write' => false,
148
                'hidden' => true,
149
                'locked' => false,
150
            ];
151
152
            // Allow only the groups I have access
153
            $allGroups = \GroupManager::getAllGroupPerUserSubscription($userId);
154
            if (!empty($allGroups)) {
155
                foreach ($allGroups as $groupInfo) {
156
                    $groupId = $groupInfo['iid'];
157
                    if (\GroupManager::user_has_access(
158
                        $userId,
159
                        $groupId,
160
                        \GroupManager::GROUP_TOOL_DOCUMENTS
161
                    )) {
162
                        $config['attributes'][] = [
163
                            'pattern' => '!'.$groupInfo['secret_directory'].'!',
164
                            'read' => true,
165
                            'write' => false,
166
                            'hidden' => false,
167
                            'locked' => false,
168
                        ];
169
                    }
170
                }
171
            }
172
173
            return $config;
174
        }
175
176
        return [];
177
    }
178
179
    /**
180
     * This is the absolute document course path like
181
     * /var/www/portal/data/courses/XXX/document/.
182
     *
183
     * @return string
184
     */
185
    public function getCourseDocumentSysPath()
186
    {
187
        $url = '';
188
        if ($this->allow()) {
189
            $directory = $this->getCourseDirectory();
190
            $coursePath = $this->connector->paths['sys_course_path'];
191
            $url = $coursePath.$directory.'/document/';
192
        }
193
194
        return $url;
195
    }
196
197
    /**
198
     * @return string
199
     */
200
    public function getCourseDocumentRelativeWebPath()
201
    {
202
        $url = null;
203
        if ($this->allow()) {
204
            $directory = $this->getCourseDirectory();
205
            $url = api_get_path(REL_COURSE_PATH).$directory.'/document/';
206
        }
207
208
        return $url;
209
    }
210
211
    /**
212
     * @return string
213
     */
214
    public function getCourseDocumentWebPath()
215
    {
216
        $url = null;
217
        if ($this->allow()) {
218
            $directory = $this->getCourseDirectory();
219
            $url = api_get_path(WEB_COURSE_PATH).$directory.'/document/';
220
        }
221
222
        return $url;
223
    }
224
225
    /**
226
     * @return string
227
     */
228
    public function getCourseDirectory(): string
229
    {
230
        return $this->connector->course->getDirectory();
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    public function upload($fp, $dst, $name, $tmpname, $hashes = [])
237
    {
238
        // Needed to load course information in elfinder
239
        $this->setConnectorFromPlugin();
240
241
        if ($this->allowToEdit()) {
242
            // upload file by elfinder.
243
            //$result = parent::upload($fp, $dst, $name, $tmpname);
244
//            var_dump($tmpname);exit;
245
            //$name = $result['name'];
246
            //$filtered = \URLify::filter($result['name'], 80, '', true);
247
            /*if (strcmp($name, $filtered) != 0) {
248
                $result = $this->customRename($result['hash'], $filtered);
249
            }*/
250
            //var_dump($fp, $dst, $name);exit;
251
            //$realPath = $this->realpath($result['hash']);
252
            //if (!empty($realPath)) {
253
            // Removing course path
254
255
            $directoryParentId = isset($_REQUEST['directory_parent_id']) ? $_REQUEST['directory_parent_id'] : 0;
256
            $currentDirectory = '';
257
            if (empty($directoryParentId)) {
258
                $currentDirectory = isset($_REQUEST['curdirpath']) ? $_REQUEST['curdirpath'] : '';
259
            } else {
260
                $documentData = \DocumentManager::get_document_data_by_id($directoryParentId, api_get_course_id());
261
                if ($documentData) {
262
                    $currentDirectory = $documentData['path'];
263
                }
264
            }
265
266
            if (!empty($_FILES)) {
267
                $files = $_FILES['upload'];
268
                $fileList = [];
269
                foreach ($files as $tempName => $array) {
270
                    $counter = 0;
271
                    foreach ($array as $data) {
272
                        $fileList[$counter][$tempName] = $data;
273
                        $counter++;
274
                    }
275
                }
276
277
                $resultList = [];
278
                foreach ($fileList as $file) {
279
                    $globalFile = [];
280
                    $globalFile['files'] = $file;
281
                    $document = \DocumentManager::upload_document(
282
                        $globalFile,
283
                        $currentDirectory,
284
                        '',
285
                        '', // comment
286
                        false,
287
                        'rename',
288
                        false,
289
                        false,
290
                        'files',
291
                        true,
292
                        0
293
                    );
294
                }
295
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
296
297
                /*\DocumentManager::addDocument(
298
                    $this->connector->course,
299
                    $realPath,
300
                    'file',
301
                    (int) $result['size'],
302
                    $result['name']
303
                );*/
304
            }
305
        }
306
307
        return false;
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     */
313
    public function rm($hash)
314
    {
315
        // elfinder does not delete the file
316
        //parent::rm($hash);
317
        $this->setConnectorFromPlugin();
318
319
        if ($this->allowToEdit()) {
320
            $path = $this->decode($hash);
321
            $stat = $this->stat($path);
322
            $stat['realpath'] = $path;
323
            $this->removed[] = $stat;
324
325
            $realFilePath = $path;
326
            $coursePath = $this->getCourseDocumentSysPath();
327
            $filePath = str_replace($coursePath, '/', $realFilePath);
328
329
            \DocumentManager::delete_document(
330
                $this->connector->course,
331
                $filePath,
332
                $coursePath
333
            );
334
335
            return true;
336
        }
337
338
        return false;
339
    }
340
341
    /**
342
     * @return bool
343
     */
344
    public function allow()
345
    {
346
        //if ($this->connector->security->isGranted('ROLE_ADMIN')) {
347
        if (api_is_anonymous()) {
348
            return false;
349
        }
350
351
        if (isset($this->connector->course) && !empty($this->connector->course)) {
352
            return true;
353
        }
354
355
        return false;
356
    }
357
358
    /**
359
     * Allow to upload/delete folder or files.
360
     *
361
     * @return bool
362
     */
363
    public function allowToEdit()
364
    {
365
        $allow = $this->allow();
366
367
        return $allow && api_is_allowed_to_edit(null, true);
368
    }
369
370
    /**
371
     * {@inheritdoc}
372
     */
373
    public function mkdir($path, $name)
374
    {
375
        // Needed to load course information in elfinder
376
        $this->setConnectorFromPlugin();
377
378
        if ($this->allowToEdit() === false) {
379
            return false;
380
        }
381
382
        $result = parent::mkdir($path, $name);
383
384
        if ($result && isset($result['hash'])) {
385
            $_course = $this->connector->course;
386
            $realPathRoot = $this->getCourseDocumentSysPath();
387
            $realPath = $this->realpath($result['hash']);
388
389
            // Removing course path
390
            $newPath = str_replace($realPathRoot, '/', $realPath);
391
            $documentId = DocumentManager::addDocument(
392
                $_course,
393
                $newPath,
394
                'folder',
395
                0,
396
                $name,
397
                null,
398
                0,
399
                true,
400
                api_get_group_id(),
401
                api_get_session_id(),
402
                api_get_user_id()
403
            );
404
405
            if (empty($documentId)) {
406
                $this->rm($result['hash']);
407
408
                return false;
409
            }
410
411
            return $result;
412
        }
413
414
        return false;
415
    }
416
417
    /**
418
     * @param string $attr
419
     * @param string $path
420
     * @param $data
421
     * @param CourseDriver $volume
422
     */
423
    /*public function access($attr, $path, $data, $volume)
424
    {
425
        if ($path == $this->coursePath) {
426
427
            return true;
428
        }
429
430
        $allowToEdit = $this->allowToEdit();
431
        if ($allowToEdit) {
432
            return true;
433
        }
434
435
        $path = str_replace($this->coursePath, '', $path);
436
        $documentId = \DocumentManager::get_document_id($this->connector->course, $path);
437
438
        if ($documentId) {
439
440
            $result = \DocumentManager::is_visible_by_id(
441
                $documentId,
442
                $this->connector->course,
443
                api_get_session_id(),
444
                api_get_user_id()
445
            );
446
            return false;
447
        }
448
449
        return false;
450
451
    }*/
452
}
453