Passed
Push — master ( f5d059...7cc9b1 )
by Julito
09:53
created

add_document()   C

Complexity

Conditions 10
Paths 112

Size

Total Lines 144
Code Lines 83

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 10
eloc 83
nc 112
nop 13
dl 0
loc 144
rs 6.4242
c 1
b 1
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CDocument;
5
use Symfony\Component\HttpFoundation\File\UploadedFile;
6
7
/**
8
 * FILE UPLOAD LIBRARY.
9
 *
10
 * This is the file upload library for Chamilo.
11
 * Include/require it in your code to use its functionality.
12
 *
13
 * @package chamilo.library
14
 *
15
 * @todo test and reorganise
16
 */
17
18
/**
19
 * Changes the file name extension from .php to .phps
20
 * Useful for securing a site.
21
 *
22
 * @author Hugues Peeters <[email protected]>
23
 *
24
 * @param string $file_name Name of a file
25
 *
26
 * @return string the filename phps'ized
27
 */
28
function php2phps($file_name)
29
{
30
    return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
31
}
32
33
/**
34
 * Renames .htaccess & .HTACCESS to htaccess.txt.
35
 *
36
 * @param string $filename
37
 *
38
 * @return string
39
 */
40
function htaccess2txt($filename)
41
{
42
    return str_replace(['.htaccess', '.HTACCESS'], ['htaccess.txt', 'htaccess.txt'], $filename);
43
}
44
45
/**
46
 * This function executes our safety precautions
47
 * more functions can be added.
48
 *
49
 * @param string $filename
50
 *
51
 * @return string
52
 *
53
 * @see php2phps()
54
 * @see htaccess2txt()
55
 */
56
function disable_dangerous_file($filename)
57
{
58
    return htaccess2txt(php2phps($filename));
59
}
60
61
/**
62
 * Returns the name without extension, used for the title.
63
 *
64
 * @param string $name
65
 *
66
 * @return name without the extension
67
 */
68
function get_document_title($name)
69
{
70
    // If they upload .htaccess...
71
    $name = disable_dangerous_file($name);
72
    $ext = substr(strrchr($name, '.'), 0);
73
74
    return substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
75
}
76
77
/**
78
 * This function checks if the upload succeeded.
79
 *
80
 * @param array $uploaded_file ($_FILES)
81
 *
82
 * @return true if upload succeeded
83
 */
84
function process_uploaded_file($uploaded_file, $show_output = true)
85
{
86
    // Checking the error code sent with the file upload.
87
    if (isset($uploaded_file['error'])) {
88
        switch ($uploaded_file['error']) {
89
            case 1:
90
                // The uploaded file exceeds the upload_max_filesize directive in php.ini.
91
                if ($show_output) {
92
                    Display::addFlash(
93
                        Display::return_message(
94
                            get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize'),
95
                            'error'
96
                        )
97
                    );
98
                }
99
100
                return false;
101
            case 2:
102
                // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
103
                // Not used at the moment, but could be handy if we want to limit the size of an upload
104
                // (e.g. image upload in html editor).
105
                $max_file_size = intval($_POST['MAX_FILE_SIZE']);
106
                if ($show_output) {
107
                    Display::addFlash(
108
                        Display::return_message(
109
                            get_lang('UplExceedMaxPostSize').format_file_size($max_file_size),
110
                            'error'
111
                        )
112
                    );
113
                }
114
115
                return false;
116
            case 3:
117
                // The uploaded file was only partially uploaded.
118
                if ($show_output) {
119
                    Display::addFlash(
120
                        Display::return_message(
121
                            get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'),
122
                            'error'
123
                        )
124
                    );
125
                }
126
127
                return false;
128
            case 4:
129
                // No file was uploaded.
130
                if ($show_output) {
131
                    Display::addFlash(
132
                        Display::return_message(
133
                            get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst'),
134
                            'error'
135
                        )
136
                    );
137
                }
138
139
                return false;
140
        }
141
    }
142
143
    if (!file_exists($uploaded_file['tmp_name'])) {
144
        // No file was uploaded.
145
        if ($show_output) {
146
            Display::addFlash(Display::return_message(get_lang('UplUploadFailed'), 'error'));
147
        }
148
149
        return false;
150
    }
151
152
    if (file_exists($uploaded_file['tmp_name'])) {
153
        $filesize = filesize($uploaded_file['tmp_name']);
154
        if (empty($filesize)) {
155
            // No file was uploaded.
156
            if ($show_output) {
157
                Display::addFlash(
158
                    Display::return_message(
159
                        get_lang('UplUploadFailedSizeIsZero'),
160
                        'error'
161
                    )
162
                );
163
            }
164
165
            return false;
166
        }
167
    }
168
169
    $course_id = api_get_course_id();
170
171
    //Checking course quota if we are in a course
172
    if (!empty($course_id)) {
173
        $max_filled_space = DocumentManager::get_course_quota();
174
        // Check if there is enough space to save the file
175
        if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
176
            if ($show_output) {
177
                Display::addFlash(
178
                    Display::return_message(
179
                        get_lang('UplNotEnoughSpace'),
180
                        'error'
181
                    )
182
                );
183
            }
184
185
            return false;
186
        }
187
    }
188
189
    // case 0: default: We assume there is no error, the file uploaded with success.
190
    return true;
191
}
192
193
/**
194
 * This function does the save-work for the documents.
195
 * It handles the uploaded file and adds the properties to the database
196
 * If unzip=1 and the file is a zipfile, it is extracted
197
 * If we decide to save ALL kinds of documents in one database,
198
 * we could extend this with a $type='document', 'scormdocument',...
199
 *
200
 * @param array  $courseInfo
201
 * @param array  $uploadedFile            ($_FILES)
202
 *                                        array(
203
 *                                        'name' => 'picture.jpg',
204
 *                                        'tmp_name' => '...', // absolute path
205
 *                                        );
206
 * @param string $documentDir             Example: /var/www/chamilo/courses/ABC/document
207
 * @param string $uploadPath              Example: /folder1/folder2/
208
 * @param int    $userId
209
 * @param int    $groupId                 group.id
210
 * @param int    $toUserId                User ID, or NULL for everybody
211
 * @param int    $unzip                   1/0
212
 * @param string $whatIfFileExists        overwrite, rename or warn if exists (default)
213
 * @param bool   $output                  optional output parameter
214
 * @param bool   $onlyUploadFile
215
 * @param string $comment
216
 * @param int    $sessionId
217
 * @param bool   $treat_spaces_as_hyphens
218
 *
219
 * So far only use for unzip_uploaded_document function.
220
 * If no output wanted on success, set to false.
221
 *
222
 * @return string path of the saved file
223
 */
224
function handle_uploaded_document(
225
    $courseInfo,
226
    $uploadedFile,
227
    $documentDir,
228
    $uploadPath,
229
    $userId,
230
    $groupId = 0,
231
    $toUserId = null,
232
    $unzip = 0,
233
    $whatIfFileExists = '',
234
    $output = true,
235
    $onlyUploadFile = false,
236
    $comment = null,
237
    $sessionId = null,
238
    $treat_spaces_as_hyphens = true
239
) {
240
    if (!$userId) {
241
        return false;
242
    }
243
244
    $userInfo = api_get_user_info();
245
    $uploadedFile['name'] = stripslashes($uploadedFile['name']);
246
    // Add extension to files without one (if possible)
247
    $uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']);
248
    $sessionId = (int) $sessionId;
249
    if (empty($sessionId)) {
250
        $sessionId = api_get_session_id();
251
    }
252
253
    $groupInfo = [];
254
    if (!empty($groupId)) {
255
        $groupInfo = GroupManager::get_group_properties($groupId);
256
    }
257
258
    // Just in case process_uploaded_file is not called
259
    $maxSpace = DocumentManager::get_course_quota();
260
261
    // Check if there is enough space to save the file
262
    if (!DocumentManager::enough_space($uploadedFile['size'], $maxSpace)) {
263
        if ($output) {
264
            Display::addFlash(Display::return_message(get_lang('UplNotEnoughSpace'), 'error'));
265
        }
266
267
        return false;
268
    }
269
270
    // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
271
    if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
272
        return unzip_uploaded_document(
273
            $courseInfo,
274
            $userInfo,
275
            $uploadedFile,
276
            $uploadPath,
277
            $documentDir,
278
            $maxSpace,
279
            $sessionId,
280
            $groupId,
281
            $output,
282
            $onlyUploadFile,
283
            $whatIfFileExists
284
        );
285
    } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
286
        // We can only unzip ZIP files (no gz, tar,...)
287
        if ($output) {
288
            Display::addFlash(
289
                Display::return_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'), 'error')
290
            );
291
        }
292
293
        return false;
294
    } else {
295
        // Clean up the name, only ASCII characters should stay. (and strict)
296
        $cleanName = api_replace_dangerous_char($uploadedFile['name'], $treat_spaces_as_hyphens);
297
298
        // No "dangerous" files
299
        $cleanName = disable_dangerous_file($cleanName);
300
301
        // Checking file extension
302
        if (!filter_extension($cleanName)) {
303
            if ($output) {
304
                Display::addFlash(
305
                    Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error')
306
                );
307
            }
308
309
            return false;
310
        } else {
311
            // If the upload path differs from / (= root) it will need a slash at the end
312
            if ($uploadPath != '/') {
313
                $uploadPath = $uploadPath.'/';
314
            }
315
316
            // Full path to where we want to store the file with trailing slash
317
            $whereToSave = $documentDir.$uploadPath;
318
319
            // At least if the directory doesn't exist, tell so
320
            /*if (!is_dir($whereToSave)) {
321
                if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) {
322
                    if ($output) {
323
                        Display::addFlash(
324
                            Display::return_message(
325
                                get_lang('DestDirectoryDoesntExist').' ('.$uploadPath.')',
326
                                'error'
327
                            )
328
                        );
329
                    }
330
331
                    return false;
332
                }
333
            }*/
334
335
            // Just upload the file "as is"
336
            if ($onlyUploadFile) {
337
                $errorResult = moveUploadedFile($uploadedFile, $whereToSave.$cleanName);
338
                if ($errorResult) {
339
                    return $whereToSave.$cleanName;
340
                } else {
341
                    return $errorResult;
342
                }
343
            }
344
345
            /*
346
                Based in the clean name we generate a new filesystem name
347
                Using the session_id and group_id if values are not empty
348
            */
349
            $fileSystemName = DocumentManager::fixDocumentName(
350
                $cleanName,
351
                'file',
352
                $courseInfo,
353
                $sessionId,
354
                $groupId
355
            );
356
357
            // Name of the document without the extension (for the title)
358
            $documentTitle = get_document_title($uploadedFile['name']);
359
360
            // Size of the uploaded file (in bytes)
361
            $fileSize = $uploadedFile['size'];
362
363
            // File permissions
364
            $filePermissions = api_get_permissions_for_new_files();
365
366
            // Example: /var/www/chamilo/courses/xxx/document/folder/picture.jpg
367
            $fullPath = $whereToSave.$fileSystemName;
368
369
            // Example: /folder/picture.jpg
370
            $filePath = $uploadPath.$fileSystemName;
371
372
            $docId = DocumentManager::get_document_id(
373
                $courseInfo,
374
                $filePath,
375
                $sessionId
376
            );
377
378
            // What to do if the target file exists
379
            switch ($whatIfFileExists) {
380
                // Overwrite the file if it exists
381
                case 'overwrite':
382
                    // Check if the target file exists, so we can give another message
383
                    $fileExists = file_exists($fullPath);
384
385
                    if (moveUploadedFile($uploadedFile, $fullPath)) {
386
                        chmod($fullPath, $filePermissions);
387
388
                        if ($fileExists && $docId) {
389
                            // UPDATE DATABASE
390
                            $documentId = DocumentManager::get_document_id(
391
                                $courseInfo,
392
                                $filePath
393
                            );
394
                            if (is_numeric($documentId)) {
395
                                // Update file size
396
                                update_existing_document(
397
                                    $courseInfo,
398
                                    $documentId,
399
                                    $uploadedFile['size']
400
                                );
401
402
                                // Update document item_property
403
                                api_item_property_update(
404
                                    $courseInfo,
405
                                    TOOL_DOCUMENT,
406
                                    $documentId,
407
                                    'DocumentUpdated',
408
                                    $userId,
409
                                    $groupInfo,
410
                                    $toUserId,
411
                                    null,
412
                                    null,
413
                                    $sessionId
414
                                );
415
416
                                // Redo visibility
417
                                api_set_default_visibility(
418
                                    $documentId,
419
                                    TOOL_DOCUMENT,
420
                                    null,
421
                                    $courseInfo
422
                                );
423
                            } else {
424
                                // There might be cases where the file exists on disk but there is no registration of
425
                                // that in the database
426
                                // In this case, and if we are in overwrite mode, overwrite and create the db record
427
                                $documentId = add_document(
428
                                    $courseInfo,
429
                                    $filePath,
430
                                    'file',
431
                                    $fileSize,
432
                                    $documentTitle,
433
                                    $comment,
434
                                    0,
435
                                    true,
436
                                    $groupId,
437
                                    $sessionId
438
                                );
439
440
                                if ($documentId) {
441
                                    // Put the document in item_property update
442
                                    api_item_property_update(
443
                                        $courseInfo,
444
                                        TOOL_DOCUMENT,
445
                                        $documentId,
446
                                        'DocumentAdded',
447
                                        $userId,
448
                                        $groupInfo,
449
                                        $toUserId,
450
                                        null,
451
                                        null,
452
                                        $sessionId
453
                                    );
454
455
                                    // Redo visibility
456
                                    api_set_default_visibility(
457
                                        $documentId,
458
                                        TOOL_DOCUMENT,
459
                                        null,
460
                                        $courseInfo
461
                                    );
462
                                }
463
                            }
464
465
                            // If the file is in a folder, we need to update all parent folders
466
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
467
468
                            // Display success message with extra info to user
469
                            if ($output) {
470
                                Display::addFlash(
471
                                    Display::return_message(
472
                                        get_lang('UplUploadSucceeded').'<br /> '.
473
                                        $documentTitle.' '.get_lang('UplFileOverwritten'),
474
                                        'confirmation',
475
                                        false
476
                                    )
477
                                );
478
                            }
479
480
                            return $filePath;
481
                        } else {
482
                            // Put the document data in the database
483
                            $documentId = add_document(
484
                                $courseInfo,
485
                                $filePath,
486
                                'file',
487
                                $fileSize,
488
                                $documentTitle,
489
                                $comment,
490
                                0,
491
                                true,
492
                                $groupId,
493
                                $sessionId
494
                            );
495
496
                            if ($documentId) {
497
                                // Put the document in item_property update
498
                                api_item_property_update(
499
                                    $courseInfo,
500
                                    TOOL_DOCUMENT,
501
                                    $documentId,
502
                                    'DocumentAdded',
503
                                    $userId,
504
                                    $groupInfo,
505
                                    $toUserId,
506
                                    null,
507
                                    null,
508
                                    $sessionId
509
                                );
510
511
                                // Redo visibility
512
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
513
                            }
514
515
                            // If the file is in a folder, we need to update all parent folders
516
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
517
518
                            // Display success message to user
519
                            if ($output) {
520
                                Display::addFlash(
521
                                    Display::return_message(
522
                                        get_lang('UplUploadSucceeded').'<br /> '.$documentTitle,
523
                                        'confirmation',
524
                                        false
525
                                    )
526
                                );
527
                            }
528
529
                            return $filePath;
530
                        }
531
                    } else {
532
                        if ($output) {
533
                            Display::addFlash(
534
                                Display::return_message(
535
                                    get_lang('UplUnableToSaveFile'),
536
                                    'error',
537
                                    false
538
                                )
539
                            );
540
                        }
541
542
                        return false;
543
                    }
544
                    break;
545
                case 'rename':
546
                    // Rename the file if it exists
547
                    // Always rename.
548
                    $cleanName = DocumentManager::getUniqueFileName(
549
                        $uploadPath,
550
                        $cleanName,
551
                        $courseInfo,
552
                        $sessionId,
553
                        $groupId
554
                    );
555
556
                    $fileSystemName = DocumentManager::fixDocumentName(
557
                        $cleanName,
558
                        'file',
559
                        $courseInfo,
560
                        $sessionId,
561
                        $groupId
562
                    );
563
564
                    $documentTitle = disable_dangerous_file($cleanName);
565
                    $fullPath = $whereToSave.$fileSystemName;
566
                    $filePath = $uploadPath.$fileSystemName;
567
568
                    $request = \Chamilo\CoreBundle\Framework\Container::getRequest();
569
                    $content = $request->files->get('file');
570
571
                    //if (moveUploadedFile($uploadedFile, $fullPath)) {
572
                    if (true) {
573
                        ///chmod($fullPath, $filePermissions);
574
                        // Put the document data in the database
575
                        $documentId = add_document(
576
                            $courseInfo,
577
                            $filePath,
578
                            'file',
579
                            $fileSize,
580
                            $documentTitle,
581
                            $comment, // comment
582
                            0, // read only
583
                            true, // save visibility
584
                            $groupId,
585
                            $sessionId,
586
                            0,
587
                            true,
588
                            $content
589
                        );
590
591
                        if ($documentId) {
592
                            // Update document item_property
593
                            /*api_item_property_update(
594
                                $courseInfo,
595
                                TOOL_DOCUMENT,
596
                                $documentId,
597
                                'DocumentAdded',
598
                                $userId,
599
                                $groupInfo,
600
                                $toUserId,
601
                                null,
602
                                null,
603
                                $sessionId
604
                            );*/
605
606
                            // Redo visibility
607
                            //api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
608
                        }
609
610
                        // If the file is in a folder, we need to update all parent folders
611
                        //item_property_update_on_folder($courseInfo, $uploadPath, $userId);
612
613
                        // Display success message to user
614
                        if ($output) {
615
                            Display::addFlash(
616
                                Display::return_message(
617
                                    get_lang('UplUploadSucceeded').'<br />'.
618
                                    get_lang('UplFileSavedAs').' '.$documentTitle,
619
                                    'success',
620
                                    false
621
                                )
622
                            );
623
                        }
624
625
                        return $filePath;
626
                    } else {
627
                        /*if ($output) {
628
                            Display::addFlash(
629
                                Display::return_message(
630
                                    get_lang('UplUnableToSaveFile'),
631
                                    'error',
632
                                    false
633
                                )
634
                            );
635
                        }
636
637
                        return false;*/
638
                    }
639
                    break;
640
                case 'nothing':
641
                    $fileExists = file_exists($fullPath);
642
                    if ($fileExists) {
643
                        if ($output) {
644
                            Display::addFlash(
645
                                Display::return_message(
646
                                    $uploadPath.$cleanName.' '.get_lang('UplAlreadyExists'),
647
                                    'warning',
648
                                    false
649
                                )
650
                            );
651
                        }
652
                        break;
653
                    }
654
                    // no break
655
                default:
656
                    // Only save the file if it doesn't exist or warn user if it does exist
657
                    if (file_exists($fullPath) && $docId) {
658
                        if ($output) {
659
                            Display::addFlash(
660
                                Display::return_message($cleanName.' '.get_lang('UplAlreadyExists'), 'warning', false)
661
                            );
662
                        }
663
                    } else {
664
665
                        if (moveUploadedFile($uploadedFile, $fullPath)) {
666
                            //chmod($fullPath, $filePermissions);
667
668
                            // Put the document data in the database
669
                            $documentId = add_document(
670
                                $courseInfo,
671
                                $filePath,
672
                                'file',
673
                                $fileSize,
674
                                $documentTitle,
675
                                $comment,
676
                                0,
677
                                true,
678
                                $groupId,
679
                                $sessionId
680
                            );
681
682
                            if ($documentId) {
683
                                // Update document item_property
684
                                api_item_property_update(
685
                                    $courseInfo,
686
                                    TOOL_DOCUMENT,
687
                                    $documentId,
688
                                    'DocumentAdded',
689
                                    $userId,
690
                                    $groupInfo,
691
                                    $toUserId,
692
                                    null,
693
                                    null,
694
                                    $sessionId
695
                                );
696
                                // Redo visibility
697
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
698
                            }
699
700
                            // If the file is in a folder, we need to update all parent folders
701
                            item_property_update_on_folder(
702
                                $courseInfo,
703
                                $uploadPath,
704
                                $userId
705
                            );
706
707
                            // Display success message to user
708
                            if ($output) {
709
                                Display::addFlash(
710
                                    Display::return_message(
711
                                        get_lang('UplUploadSucceeded').'<br /> '.$documentTitle,
712
                                        'confirm',
713
                                        false
714
                                    )
715
                                );
716
                            }
717
718
                            return $filePath;
719
                        } else {
720
                            if ($output) {
721
                                Display::addFlash(
722
                                    Display::return_message(
723
                                        get_lang('UplUnableToSaveFile'),
724
                                        'error',
725
                                        false
726
                                    )
727
                                );
728
                            }
729
730
                            return false;
731
                        }
732
                    }
733
                    break;
734
            }
735
        }
736
    }
737
}
738
739
/**
740
 * @param string $file
741
 * @param string $storePath
742
 *
743
 * @return bool
744
 */
745
function moveUploadedFile($file, $storePath)
746
{
747
    $handleFromFile = isset($file['from_file']) && $file['from_file'] ? true : false;
748
    $moveFile = isset($file['move_file']) && $file['move_file'] ? true : false;
749
    if ($moveFile) {
750
        copy($file['tmp_name'], $storePath);
751
    }
752
    if ($handleFromFile) {
753
        return file_exists($file['tmp_name']);
754
    } else {
755
        return move_uploaded_file($file['tmp_name'], $storePath);
756
    }
757
}
758
759
/**
760
 * Checks if there is enough place to add a file on a directory
761
 * on the base of a maximum directory size allowed
762
 * deprecated: use enough_space instead!
763
 *
764
 * @author Hugues Peeters <[email protected]>
765
 *
766
 * @param int    $file_size     Size of the file in byte
767
 * @param string $dir           Path of the directory where the file should be added
768
 * @param int    $max_dir_space Maximum size of the diretory in byte
769
 *
770
 * @return bool true if there is enough space, false otherwise
771
 *
772
 * @see enough_size() uses  dir_total_space() function
773
 */
774
function enough_size($file_size, $dir, $max_dir_space)
775
{
776
    // If the directory is the archive directory, safely ignore the size limit
777
    if (api_get_path(SYS_ARCHIVE_PATH) == $dir) {
778
        return true;
779
    }
780
781
    if ($max_dir_space) {
782
        $already_filled_space = dir_total_space($dir);
783
        if (($file_size + $already_filled_space) > $max_dir_space) {
784
            return false;
785
        }
786
    }
787
788
    return true;
789
}
790
791
/**
792
 * Computes the size already occupied by a directory and is subdirectories.
793
 *
794
 * @author Hugues Peeters <[email protected]>
795
 *
796
 * @param string $dir_path Size of the file in byte
797
 *
798
 * @return int Return the directory size in bytes
799
 */
800
function dir_total_space($dir_path)
801
{
802
    $save_dir = getcwd();
803
    chdir($dir_path);
804
    $handle = opendir($dir_path);
805
    $sumSize = 0;
806
    $dirList = [];
807
    while ($element = readdir($handle)) {
808
        if ($element == '.' || $element == '..') {
809
            continue; // Skip the current and parent directories
810
        }
811
        if (is_file($element)) {
812
            $sumSize += filesize($element);
813
        }
814
        if (is_dir($element)) {
815
            $dirList[] = $dir_path.'/'.$element;
816
        }
817
    }
818
819
    closedir($handle);
820
821
    if (sizeof($dirList) > 0) {
822
        foreach ($dirList as $j) {
823
            $sizeDir = dir_total_space($j); // Recursivity
824
            $sumSize += $sizeDir;
825
        }
826
    }
827
    chdir($save_dir); // Return to initial position
828
829
    return $sumSize;
830
}
831
832
/**
833
 * Tries to add an extension to files without extension
834
 * Some applications on Macintosh computers don't add an extension to the files.
835
 * This subroutine try to fix this on the basis of the MIME type sent
836
 * by the browser.
837
 *
838
 * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
839
 *        We don't have solution for this kind of situation
840
 *
841
 * @author Hugues Peeters <[email protected]>
842
 * @author Bert Vanderkimpen
843
 *
844
 * @param string $file_name Name of the file
845
 * @param string $file_type Type of the file
846
 *
847
 * @return string File name
848
 */
849
function add_ext_on_mime($file_name, $file_type)
850
{
851
    // Check whether the file has an extension AND whether the browser has sent a MIME Type
852
853
    if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
854
        // Build a "MIME-types / extensions" connection table
855
        static $mime_type = [];
856
857
        $mime_type[] = 'application/msword';
858
        $extension[] = '.doc';
859
        $mime_type[] = 'application/rtf';
860
        $extension[] = '.rtf';
861
        $mime_type[] = 'application/vnd.ms-powerpoint';
862
        $extension[] = '.ppt';
863
        $mime_type[] = 'application/vnd.ms-excel';
864
        $extension[] = '.xls';
865
        $mime_type[] = 'application/pdf';
866
        $extension[] = '.pdf';
867
        $mime_type[] = 'application/postscript';
868
        $extension[] = '.ps';
869
        $mime_type[] = 'application/mac-binhex40';
870
        $extension[] = '.hqx';
871
        $mime_type[] = 'application/x-gzip';
872
        $extension[] = 'tar.gz';
873
        $mime_type[] = 'application/x-shockwave-flash';
874
        $extension[] = '.swf';
875
        $mime_type[] = 'application/x-stuffit';
876
        $extension[] = '.sit';
877
        $mime_type[] = 'application/x-tar';
878
        $extension[] = '.tar';
879
        $mime_type[] = 'application/zip';
880
        $extension[] = '.zip';
881
        $mime_type[] = 'application/x-tar';
882
        $extension[] = '.tar';
883
        $mime_type[] = 'text/html';
884
        $extension[] = '.html';
885
        $mime_type[] = 'text/plain';
886
        $extension[] = '.txt';
887
        $mime_type[] = 'text/rtf';
888
        $extension[] = '.rtf';
889
        $mime_type[] = 'img/gif';
890
        $extension[] = '.gif';
891
        $mime_type[] = 'img/jpeg';
892
        $extension[] = '.jpg';
893
        $mime_type[] = 'img/png';
894
        $extension[] = '.png';
895
        $mime_type[] = 'audio/midi';
896
        $extension[] = '.mid';
897
        $mime_type[] = 'audio/mpeg';
898
        $extension[] = '.mp3';
899
        $mime_type[] = 'audio/x-aiff';
900
        $extension[] = '.aif';
901
        $mime_type[] = 'audio/x-pn-realaudio';
902
        $extension[] = '.rm';
903
        $mime_type[] = 'audio/x-pn-realaudio-plugin';
904
        $extension[] = '.rpm';
905
        $mime_type[] = 'audio/x-wav';
906
        $extension[] = '.wav';
907
        $mime_type[] = 'video/mpeg';
908
        $extension[] = '.mpg';
909
        $mime_type[] = 'video/mpeg4-generic';
910
        $extension[] = '.mp4';
911
        $mime_type[] = 'video/quicktime';
912
        $extension[] = '.mov';
913
        $mime_type[] = 'video/x-msvideo';
914
        $extension[] = '.avi';
915
916
        $mime_type[] = 'video/x-ms-wmv';
917
        $extension[] = '.wmv';
918
        $mime_type[] = 'video/x-flv';
919
        $extension[] = '.flv';
920
        $mime_type[] = 'image/svg+xml';
921
        $extension[] = '.svg';
922
        $mime_type[] = 'image/svg+xml';
923
        $extension[] = '.svgz';
924
        $mime_type[] = 'video/ogg';
925
        $extension[] = '.ogv';
926
        $mime_type[] = 'audio/ogg';
927
        $extension[] = '.oga';
928
        $mime_type[] = 'application/ogg';
929
        $extension[] = '.ogg';
930
        $mime_type[] = 'application/ogg';
931
        $extension[] = '.ogx';
932
        $mime_type[] = 'application/x-freemind';
933
        $extension[] = '.mm';
934
935
        $mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12';
936
        $extension[] = '.docm';
937
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
938
        $extension[] = '.docx';
939
        $mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12';
940
        $extension[] = '.dotm';
941
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
942
        $extension[] = '.dotx';
943
        $mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12';
944
        $extension[] = '.potm';
945
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template';
946
        $extension[] = '.potx';
947
        $mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
948
        $extension[] = '.ppam';
949
        $mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
950
        $extension[] = '.ppsm';
951
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
952
        $extension[] = '.ppsx';
953
        $mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
954
        $extension[] = '.pptm';
955
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
956
        $extension[] = '.pptx';
957
        $mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12';
958
        $extension[] = '.xlam';
959
        $mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
960
        $extension[] = '.xlsb';
961
        $mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12';
962
        $extension[] = '.xlsm';
963
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
964
        $extension[] = '.xlsx';
965
        $mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12';
966
        $extension[] = '.xltm';
967
        $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
968
        $extension[] = '.xltx';
969
970
        // Test on PC (files with no extension get application/octet-stream)
971
        //$mime_type[] = 'application/octet-stream';      $extension[] = '.ext';
972
        // Check whether the MIME type sent by the browser is within the table
973
        foreach ($mime_type as $key => &$type) {
974
            if ($type == $file_type) {
975
                $file_name .= $extension[$key];
976
                break;
977
            }
978
        }
979
980
        unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
981
    }
982
983
    return $file_name;
984
}
985
986
/**
987
 * Manages all the unzipping process of an uploaded file.
988
 *
989
 * @author Hugues Peeters <[email protected]>
990
 *
991
 * @param array  $uploaded_file    - follows the $_FILES Structure
992
 * @param string $upload_path      - destination of the upload.
993
 *                                 This path is to append to $base_work_dir
994
 * @param string $base_work_dir    - base working directory of the module
995
 * @param int    $max_filled_space - amount of bytes to not exceed in the base
996
 *                                 working directory
997
 *
998
 * @return bool true if it succeeds false otherwise
999
 */
1000
function unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space)
1001
{
1002
    $zip_file = new PclZip($uploaded_file['tmp_name']);
1003
1004
    // Check the zip content (real size and file extension)
1005
    if (file_exists($uploaded_file['tmp_name'])) {
1006
        $zip_content_array = $zip_file->listContent();
1007
        $ok_scorm = false;
1008
        $realFileSize = 0;
1009
        foreach ($zip_content_array as &$this_content) {
1010
            if (preg_match('~.(php.*|phtml)$~i', $this_content['filename'])) {
1011
                Display::addFlash(
1012
                    Display::return_message(get_lang('ZipNoPhp'))
1013
                );
1014
1015
                return false;
1016
            } elseif (stristr($this_content['filename'], 'imsmanifest.xml')) {
1017
                $ok_scorm = true;
1018
            } elseif (stristr($this_content['filename'], 'LMS')) {
1019
                $ok_plantyn_scorm1 = true;
1020
            } elseif (stristr($this_content['filename'], 'REF')) {
1021
                $ok_plantyn_scorm2 = true;
1022
            } elseif (stristr($this_content['filename'], 'SCO')) {
1023
                $ok_plantyn_scorm3 = true;
1024
            } elseif (stristr($this_content['filename'], 'AICC')) {
1025
                $ok_aicc_scorm = true;
1026
            }
1027
            $realFileSize += $this_content['size'];
1028
        }
1029
1030
        if (($ok_plantyn_scorm1 && $ok_plantyn_scorm2 && $ok_plantyn_scorm3) || $ok_aicc_scorm) {
1031
            $ok_scorm = true;
1032
        }
1033
1034
        if (!$ok_scorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM) {
1035
            Display::addFlash(
1036
                Display::return_message(get_lang('NotScormContent'))
1037
            );
1038
1039
            return false;
1040
        }
1041
1042
        if (!enough_size($realFileSize, $base_work_dir, $max_filled_space)) {
1043
            Display::addFlash(
1044
                Display::return_message(get_lang('NoSpace'))
1045
            );
1046
1047
            return false;
1048
        }
1049
1050
        // It happens on Linux that $upload_path sometimes doesn't start with '/'
1051
        if ($upload_path[0] != '/' && substr($base_work_dir, -1, 1) != '/') {
1052
            $upload_path = '/'.$upload_path;
1053
        }
1054
1055
        if ($upload_path[strlen($upload_path) - 1] == '/') {
1056
            $upload_path = substr($upload_path, 0, -1);
1057
        }
1058
1059
        /*	Uncompressing phase */
1060
1061
        /*
1062
            The first version, using OS unzip, is not used anymore
1063
            because it does not return enough information.
1064
            We need to process each individual file in the zip archive to
1065
            - add it to the database
1066
            - parse & change relative html links
1067
        */
1068
        if (PHP_OS == 'Linux' && !get_cfg_var('safe_mode') && false) { // *** UGent, changed by OC ***
1069
            // Shell Method - if this is possible, it gains some speed
1070
            exec("unzip -d \"".$base_work_dir.$upload_path."/\"".$uploaded_file['name']." ".$uploaded_file['tmp_name']);
1071
        } else {
1072
            // PHP method - slower...
1073
            $save_dir = getcwd();
1074
            chdir($base_work_dir.$upload_path);
1075
            $unzippingState = $zip_file->extract();
1076
            for ($j = 0; $j < count($unzippingState); $j++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
1077
                $state = $unzippingState[$j];
1078
1079
                // Fix relative links in html files
1080
                $extension = strrchr($state['stored_filename'], '.');
1081
            }
1082
            if ($dir = @opendir($base_work_dir.$upload_path)) {
1083
                while ($file = readdir($dir)) {
1084
                    if ($file != '.' && $file != '..') {
1085
                        $filetype = 'file';
1086
                        if (is_dir($base_work_dir.$upload_path.'/'.$file)) {
1087
                            $filetype = 'folder';
1088
                        }
1089
1090
                        $safe_file = api_replace_dangerous_char($file);
1091
                        @rename($base_work_dir.$upload_path.'/'.$file, $base_work_dir.$upload_path.'/'.$safe_file);
1092
                        set_default_settings($upload_path, $safe_file, $filetype);
1093
                    }
1094
                }
1095
1096
                closedir($dir);
1097
            } else {
1098
                error_log('Could not create directory '.$base_work_dir.$upload_path.' to unzip files');
1099
            }
1100
            chdir($save_dir); // Back to previous dir position
1101
        }
1102
    }
1103
1104
    return true;
1105
}
1106
1107
/**
1108
 * Manages all the unzipping process of an uploaded document
1109
 * This uses the item_property table for properties of documents.
1110
 *
1111
 * @author Hugues Peeters <[email protected]>
1112
 * @author Bert Vanderkimpen
1113
 *
1114
 * @param array  $courseInfo
1115
 * @param array  $userInfo
1116
 * @param array  $uploaded_file    - follows the $_FILES Structure
1117
 * @param string $uploadPath       - destination of the upload.
1118
 *                                 This path is to append to $base_work_dir
1119
 * @param string $base_work_dir    - base working directory of the module
1120
 * @param int    $maxFilledSpace   - amount of bytes to not exceed in the base
1121
 *                                 working directory
1122
 * @param int    $sessionId
1123
 * @param int    $groupId          group.id
1124
 * @param bool   $output           Optional. If no output not wanted on success, set to false.
1125
 * @param bool   $onlyUploadFile
1126
 * @param string $whatIfFileExists (only works if $onlyUploadFile is false)
1127
 *
1128
 * @return bool true if it succeeds false otherwise
1129
 */
1130
function unzip_uploaded_document(
1131
    $courseInfo,
1132
    $userInfo,
1133
    $uploaded_file,
1134
    $uploadPath,
1135
    $base_work_dir,
1136
    $maxFilledSpace,
1137
    $sessionId = 0,
1138
    $groupId = 0,
1139
    $output = true,
1140
    $onlyUploadFile = false,
1141
    $whatIfFileExists = 'overwrite'
1142
) {
1143
    $zip = new PclZip($uploaded_file['tmp_name']);
1144
1145
    // Check the zip content (real size and file extension)
1146
    $zip_content_array = (array) $zip->listContent();
1147
    $realSize = 0;
1148
    foreach ($zip_content_array as &$this_content) {
1149
        $realSize += $this_content['size'];
1150
    }
1151
1152
    if (!DocumentManager::enough_space($realSize, $maxFilledSpace)) {
1153
        echo Display::return_message(get_lang('UplNotEnoughSpace'), 'error');
1154
1155
        return false;
1156
    }
1157
1158
    $folder = api_get_unique_id();
1159
    $destinationDir = api_get_path(SYS_ARCHIVE_PATH).$folder;
1160
    mkdir($destinationDir, api_get_permissions_for_new_directories(), true);
1161
1162
    // Uncompress zip file
1163
    // We extract using a callback function that "cleans" the path
1164
    $zip->extract(
1165
        PCLZIP_OPT_PATH,
1166
        $destinationDir,
1167
        PCLZIP_CB_PRE_EXTRACT,
1168
        'clean_up_files_in_zip',
1169
        PCLZIP_OPT_REPLACE_NEWER
1170
    );
1171
1172
    if ($onlyUploadFile === false) {
1173
        // Add all documents in the unzipped folder to the database
1174
        add_all_documents_in_folder_to_database(
1175
            $courseInfo,
1176
            $userInfo,
1177
            $base_work_dir,
1178
            $destinationDir,
1179
            $sessionId,
1180
            $groupId,
1181
            $output,
1182
            ['path' => $uploadPath],
1183
            $whatIfFileExists
1184
        );
1185
    } else {
1186
        // Copy result
1187
        $fs = new \Symfony\Component\Filesystem\Filesystem();
1188
        $fs->mirror($destinationDir, $base_work_dir.$uploadPath, null, ['overwrite']);
1189
    }
1190
1191
    if (is_dir($destinationDir)) {
1192
        rmdirr($destinationDir);
1193
    }
1194
1195
    return true;
1196
}
1197
1198
/**
1199
 * This function is a callback function that is used while extracting a zipfile
1200
 * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract.
1201
 *
1202
 * @param array $p_event
1203
 * @param array $p_header
1204
 *
1205
 * @return int (If the function returns 1, then the extraction is resumed, if 0 the path was skipped)
1206
 */
1207
function clean_up_files_in_zip($p_event, &$p_header)
1208
{
1209
    $originalStoredFileName = $p_header['stored_filename'];
1210
    $baseName = basename($originalStoredFileName);
1211
    // Skip files
1212
    $skipFiles = [
1213
        '__MACOSX',
1214
        '.Thumbs.db',
1215
        'Thumbs.db',
1216
    ];
1217
    if (in_array($baseName, $skipFiles)) {
1218
        return 0;
1219
    }
1220
    $modifiedStoredFileName = clean_up_path($originalStoredFileName);
1221
    $p_header['filename'] = str_replace($originalStoredFileName, $modifiedStoredFileName, $p_header['filename']);
1222
1223
    return 1;
1224
}
1225
1226
/**
1227
 * This function cleans up a given path
1228
 * by eliminating dangerous file names and cleaning them.
1229
 *
1230
 * @param string $path
1231
 *
1232
 * @return string
1233
 *
1234
 * @see disable_dangerous_file()
1235
 * @see api_replace_dangerous_char()
1236
 */
1237
function clean_up_path($path)
1238
{
1239
    // Split the path in folders and files
1240
    $path_array = explode('/', $path);
1241
    // Clean up every folder and filename in the path
1242
    foreach ($path_array as $key => &$val) {
1243
        // We don't want to lose the dots in ././folder/file (cfr. zipfile)
1244
        if ($val != '.') {
1245
            $val = disable_dangerous_file(api_replace_dangerous_char($val));
1246
        }
1247
    }
1248
    // Join the "cleaned" path (modified in-place as passed by reference)
1249
    $path = implode('/', $path_array);
1250
    filter_extension($path);
1251
1252
    return $path;
1253
}
1254
1255
/**
1256
 * Checks if the file is dangerous, based on extension and/or mimetype.
1257
 * The list of extensions accepted/rejected can be found from
1258
 * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include').
1259
 *
1260
 * @param string $filename passed by reference. The filename will be modified
1261
 *                         if filter rules say so! (you can include path but the filename should look like 'abc.html')
1262
 *
1263
 * @return int 0 to skip file, 1 to keep file
1264
 */
1265
function filter_extension(&$filename)
1266
{
1267
    if (substr($filename, -1) == '/') {
1268
        return 1; // Authorize directories
1269
    }
1270
    $blacklist = api_get_setting('upload_extensions_list_type');
1271
    if ($blacklist != 'whitelist') { // if = blacklist
1272
        $extensions = explode(';', strtolower(api_get_setting('upload_extensions_blacklist')));
1273
1274
        $skip = api_get_setting('upload_extensions_skip');
1275
        $ext = strrchr($filename, '.');
1276
        $ext = substr($ext, 1);
1277
        if (empty($ext)) {
1278
            return 1; // We're in blacklist mode, so accept empty extensions
1279
        }
1280
        if (in_array(strtolower($ext), $extensions)) {
1281
            if ($skip == 'true') {
1282
                return 0;
1283
            } else {
1284
                $new_ext = api_get_setting('upload_extensions_replace_by');
1285
                $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
1286
1287
                return 1;
1288
            }
1289
        } else {
1290
            return 1;
1291
        }
1292
    } else {
1293
        $extensions = explode(';', strtolower(api_get_setting('upload_extensions_whitelist')));
1294
        $skip = api_get_setting('upload_extensions_skip');
1295
        $ext = strrchr($filename, '.');
1296
        $ext = substr($ext, 1);
1297
        if (empty($ext)) {
1298
            return 1; // Accept empty extensions
1299
        }
1300
        if (!in_array(strtolower($ext), $extensions)) {
1301
            if ($skip == 'true') {
1302
                return 0;
1303
            } else {
1304
                $new_ext = api_get_setting('upload_extensions_replace_by');
1305
                $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
1306
1307
                return 1;
1308
            }
1309
        } else {
1310
            return 1;
1311
        }
1312
    }
1313
}
1314
1315
/**
1316
 * Adds a new document to the database.
1317
 *
1318
 * @param array  $courseInfo
1319
 * @param string $path
1320
 * @param string $fileType
1321
 * @param int    $fileSize
1322
 * @param string $title
1323
 * @param string $comment
1324
 * @param int    $readonly
1325
 * @param bool   $saveVisibility
1326
 * @param int    $group_id         group.id
1327
 * @param int    $sessionId        Session ID, if any
1328
 * @param int    $userId           creator user id
1329
 * @param bool   $sendNotification
1330
 * @param string $content
1331
 *
1332
 * @return int id if inserted document
1333
 */
1334
function add_document(
1335
    $courseInfo,
1336
    $path,
1337
    $fileType,
1338
    $fileSize,
1339
    $title,
1340
    $comment = null,
1341
    $readonly = 0,
1342
    $saveVisibility = true,
1343
    $group_id = 0,
1344
    $sessionId = 0,
1345
    $userId = 0,
1346
    $sendNotification = true,
1347
    $content = ''
1348
) {
1349
    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
1350
    $userId = empty($userId) ? api_get_user_id() : $userId;
1351
    $userEntity = api_get_user_entity($userId);
1352
    $courseEntity = api_get_course_entity(api_get_course_int_id());
1353
    $session = api_get_session_entity($sessionId);
1354
    $readonly = (int) $readonly;
1355
1356
    $em = Database::getManager();
1357
    $documentRepo = $em->getRepository('ChamiloCourseBundle:CDocument');
1358
1359
    $document = new CDocument();
1360
    $document
1361
        ->setCourse($courseEntity)
1362
        ->setPath($path)
1363
        ->setFiletype($fileType)
1364
        ->setSize($fileSize)
1365
        ->setTitle($title)
1366
        ->setComment($comment)
1367
        ->setReadonly($readonly)
1368
        ->setSession($session)
1369
    ;
1370
1371
    $em->persist($document);
1372
    $em->flush();
1373
1374
    $resourceNode = $documentRepo->addResourceNode($document, $userEntity);
1375
    $document->setResourceNode($resourceNode);
1376
1377
    $mediaManager = \Chamilo\CoreBundle\Framework\Container::$container->get('sonata.media.manager.media');
1378
    /** @var \Chamilo\MediaBundle\Entity\Media $media */
1379
    $media = $mediaManager->create();
1380
    $media->setName($title);
1381
1382
    $fileName = basename($path);
1383
    $extension = pathinfo($fileName, PATHINFO_EXTENSION);
1384
1385
    //$media->setSize($fileSize);
1386
    $media->setContext('default');
1387
1388
    $provider = 'sonata.media.provider.image';
1389
    if (!in_array($extension, ['jpeg', 'jpg', 'gif', 'png'])) {
1390
        $provider = 'sonata.media.provider.file';
1391
    }
1392
1393
    $media->setProviderName($provider);
1394
    $media->setEnabled(true);
1395
1396
    if ($content instanceof UploadedFile) {
1397
        $file = $content;
1398
    } else {
1399
        $handle = tmpfile();
1400
        fwrite($handle, $content);
1401
        $file = new \Sonata\MediaBundle\Extra\ApiMediaFile($handle);
1402
        $file->setMimetype($media->getContentType());
1403
    }
1404
1405
    $media->setBinaryContent($file);
1406
1407
    $mediaManager->save($media, true);
1408
1409
    $resourceFile = new \Chamilo\CoreBundle\Entity\Resource\ResourceFile();
1410
    $resourceFile->setMedia($media);
1411
    $resourceFile->setName($title);
1412
1413
    $em->persist($resourceFile);
1414
1415
    $resourceNode->setResourceFile($resourceFile);
1416
1417
    $em->persist($resourceNode);
1418
1419
1420
    $em->persist($document);
1421
    $em->flush();
1422
1423
    /*$resourceRight = new \Chamilo\CoreBundle\Entity\Resource\ResourceRights();
1424
    $resourceRight->setMask(\Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter::getEditorMask());
1425
    $resourceRight->setRole(\Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER);
1426
1427
    $documentRepo->addResourceToCourse($resourceNode, $courseEntity, $resourceRight);
1428
1429
    $resourceRight = new \Chamilo\CoreBundle\Entity\Resource\ResourceRights();
1430
    $resourceRight->setMask(\Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter::getReaderMask());
1431
    $resourceRight->setRole(\Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter::ROLE_CURRENT_COURSE_STUDENT);
1432
1433
    $documentRepo->addResourceToCourse($resourceNode, $courseEntity, $resourceRight);*/
1434
1435
    $documentId = $document->getIid();
1436
    if ($documentId) {
1437
        $table = Database::get_course_table(TABLE_DOCUMENT);
1438
        $sql = "UPDATE $table SET id = iid WHERE iid = $documentId";
1439
        Database::query($sql);
1440
1441
        if ($saveVisibility) {
1442
            api_set_default_visibility(
1443
                $documentId,
1444
                TOOL_DOCUMENT,
1445
                $group_id,
1446
                $courseInfo,
1447
                $sessionId,
1448
                $userId
1449
            );
1450
        }
1451
1452
        $allowNotification = api_get_configuration_value('send_notification_when_document_added');
1453
        if ($sendNotification && $allowNotification) {
1454
            $courseTitle = $courseInfo['title'];
1455
            if (!empty($sessionId)) {
1456
                $sessionInfo = api_get_session_info($sessionId);
1457
                $courseTitle .= ' ( '.$sessionInfo['name'].') ';
1458
            }
1459
1460
            $url = api_get_path(WEB_CODE_PATH).
1461
                'document/showinframes.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&id='.$documentId;
1462
            $link = Display::url(basename($title), $url, ['target' => '_blank']);
1463
            $userInfo = api_get_user_info($userId);
1464
1465
            $message = sprintf(
1466
                get_lang('DocumentXHasBeenAddedToDocumentInYourCourseXByUserX'),
1467
                $link,
1468
                $courseTitle,
1469
                $userInfo['complete_name']
1470
            );
1471
            $subject = sprintf(get_lang('NewDocumentAddedToCourseX'), $courseTitle);
1472
            MessageManager::sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId);
1473
        }
1474
1475
        return $documentId;
1476
    } else {
1477
        return false;
1478
    }
1479
}
1480
1481
/**
1482
 * Updates an existing document in the database
1483
 * as the file exists, we only need to change the size.
1484
 *
1485
 * @param array $_course
1486
 * @param int   $documentId
1487
 * @param int   $filesize
1488
 * @param int   $readonly
1489
 *
1490
 * @return bool true /false
1491
 */
1492
function update_existing_document($_course, $documentId, $filesize, $readonly = 0)
1493
{
1494
    $document_table = Database::get_course_table(TABLE_DOCUMENT);
1495
    $documentId = intval($documentId);
1496
    $filesize = intval($filesize);
1497
    $readonly = intval($readonly);
1498
    $course_id = $_course['real_id'];
1499
1500
    $sql = "UPDATE $document_table SET
1501
            size = '$filesize',
1502
            readonly = '$readonly'
1503
			WHERE c_id = $course_id AND id = $documentId";
1504
    if (Database::query($sql)) {
1505
        return true;
1506
    } else {
1507
        return false;
1508
    }
1509
}
1510
1511
/**
1512
 * This function updates the last_edit_date, last edit user id on all folders in a given path.
1513
 *
1514
 * @param array  $_course
1515
 * @param string $path
1516
 * @param int    $user_id
1517
 */
1518
function item_property_update_on_folder($_course, $path, $user_id)
1519
{
1520
    // If we are in the root, just return... no need to update anything
1521
    if ($path == '/') {
1522
        return;
1523
    }
1524
1525
    $user_id = intval($user_id);
1526
1527
    // If the given path ends with a / we remove it
1528
    $endchar = substr($path, strlen($path) - 1, 1);
1529
    if ($endchar == '/') {
1530
        $path = substr($path, 0, strlen($path) - 1);
1531
    }
1532
1533
    $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1534
1535
    // Get the time
1536
    $time = api_get_utc_datetime();
1537
1538
    // Det all paths in the given path
1539
    // /folder/subfolder/subsubfolder/file
1540
    // if file is updated, subsubfolder, subfolder and folder are updated
1541
    $exploded_path = explode('/', $path);
1542
    $course_id = api_get_course_int_id();
1543
    $newpath = '';
1544
    foreach ($exploded_path as $key => &$value) {
1545
        // We don't want a slash before our first slash
1546
        if ($key != 0) {
1547
            $newpath .= '/'.$value;
1548
            // Select ID of given folder
1549
            $folder_id = DocumentManager::get_document_id($_course, $newpath);
1550
1551
            if ($folder_id) {
1552
                $sql = "UPDATE $table SET
1553
				        lastedit_date = '$time',
1554
				        lastedit_type = 'DocumentInFolderUpdated', 
1555
				        lastedit_user_id='$user_id'
1556
						WHERE 
1557
						    c_id = $course_id AND 
1558
						    tool='".TOOL_DOCUMENT."' AND 
1559
						    ref = '$folder_id'";
1560
                Database::query($sql);
1561
            }
1562
        }
1563
    }
1564
}
1565
1566
/**
1567
 * Adds file to document table in database
1568
 * deprecated: use file_set_default_settings instead.
1569
 *
1570
 * @author	Olivier Cauberghe <[email protected]>
1571
 *
1572
 * @param	path,filename
1573
 * action:	Adds an entry to the document table with the default settings
1574
 */
1575
function set_default_settings($upload_path, $filename, $filetype = 'file')
1576
{
1577
    $dbTable = Database::get_course_table(TABLE_DOCUMENT);
1578
    global $default_visibility;
1579
1580
    if (!$default_visibility) {
1581
        $default_visibility = 'v';
1582
    }
1583
    $filetype = Database::escape_string($filetype);
1584
1585
    $upload_path = str_replace('\\', '/', $upload_path);
1586
    $upload_path = str_replace('//', '/', $upload_path);
1587
1588
    if ($upload_path == '/') {
1589
        $upload_path = '';
1590
    } elseif (!empty($upload_path) && $upload_path[0] != '/') {
1591
        $upload_path = "/$upload_path";
1592
    }
1593
1594
    $endchar = substr($filename, strlen($filename) - 1, 1);
1595
1596
    if ($endchar == '/') {
1597
        $filename = substr($filename, 0, -1);
1598
    }
1599
    $filename = Database::escape_string($filename);
1600
    $query = "SELECT count(*) as bestaat FROM $dbTable
1601
              WHERE path='$upload_path/$filename'";
1602
    $result = Database::query($query);
1603
    $row = Database::fetch_array($result);
1604
    if ($row['bestaat'] > 0) {
1605
        $query = "UPDATE $dbTable SET
1606
		            path='$upload_path/$filename',
1607
		            visibility='$default_visibility',
1608
		            filetype='$filetype'
1609
		          WHERE path='$upload_path/$filename'";
1610
    } else {
1611
        $query = "INSERT INTO $dbTable (path,visibility,filetype)
1612
		          VALUES('$upload_path/$filename','$default_visibility','$filetype')";
1613
    }
1614
    Database::query($query);
1615
}
1616
1617
/**
1618
 * Retrieves the image path list in a html file.
1619
 *
1620
 * @author Hugues Peeters <[email protected]>
1621
 *
1622
 * @param string $html_file
1623
 *
1624
 * @return array -  images path list
1625
 */
1626
function search_img_from_html($html_file)
1627
{
1628
    $img_path_list = [];
1629
1630
    if (!$fp = fopen($html_file, 'r')) {
1631
        return;
1632
    }
1633
1634
    // Aearch and store occurences of the <img> tag in an array
1635
    $size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
1636
    if (isset($fp) && $fp !== false) {
1637
        $buffer = fread($fp, $size_file);
1638
        if (strlen($buffer) >= 0 && $buffer !== false) {
1639
        } else {
1640
            die('<center>Can not read file.</center>');
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...
1641
        }
1642
    } else {
1643
        die('<center>Can not read file.</center>');
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...
1644
    }
1645
    $matches = [];
1646
    if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
1647
        $img_tag_list = $matches[0];
1648
    }
1649
1650
    fclose($fp);
1651
    unset($buffer);
1652
1653
    // Search the image file path from all the <IMG> tag detected
1654
1655
    if (sizeof($img_tag_list) > 0) {
1656
        foreach ($img_tag_list as &$this_img_tag) {
1657
            if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
1658
                $img_path_list[] = $matches[1];
1659
            }
1660
        }
1661
        $img_path_list = array_unique($img_path_list); // Remove duplicate entries
1662
    }
1663
1664
    return $img_path_list;
1665
}
1666
1667
/**
1668
 * Creates a new directory trying to find a directory name
1669
 * that doesn't already exist.
1670
 *
1671
 * @author  Hugues Peeters <[email protected]>
1672
 * @author  Bert Vanderkimpen
1673
 *
1674
 * @param array  $_course                 current course information
1675
 * @param int    $user_id                 current user id
1676
 * @param int    $session_id
1677
 * @param int    $to_group_id             group.id
1678
 * @param int    $to_user_id
1679
 * @param string $base_work_dir           /var/www/chamilo/courses/ABC/document
1680
 * @param string $desired_dir_name        complete path of the desired name
1681
 *                                        Example: /folder1/folder2
1682
 * @param string $title                   "folder2"
1683
 * @param int    $visibility              (0 for invisible, 1 for visible, 2 for deleted)
1684
 * @param bool   $generateNewNameIfExists
1685
 * @param bool   $sendNotification        depends in conf setting "send_notification_when_document_added"
1686
 *
1687
 * @return string actual directory name if it succeeds,
1688
 *                boolean false otherwise
1689
 */
1690
function create_unexisting_directory(
1691
    $_course,
1692
    $user_id,
1693
    $session_id,
1694
    $to_group_id,
1695
    $to_user_id,
1696
    $base_work_dir,
1697
    $desired_dir_name,
1698
    $title = '',
1699
    $visibility = '',
1700
    $generateNewNameIfExists = false,
1701
    $sendNotification = true
1702
) {
1703
    $course_id = $_course['real_id'];
1704
    $session_id = intval($session_id);
1705
1706
    $folderExists = DocumentManager::folderExists(
1707
        $desired_dir_name,
1708
        $_course,
1709
        $session_id,
1710
        $to_group_id
1711
    );
1712
1713
    if ($folderExists === true) {
1714
        if ($generateNewNameIfExists) {
1715
            $counter = 1;
1716
            while (1) {
1717
                $folderExists = DocumentManager::folderExists(
1718
                    $desired_dir_name.'_'.$counter,
1719
                    $_course,
1720
                    $session_id,
1721
                    $to_group_id
1722
                );
1723
1724
                if ($folderExists === false) {
1725
                    break;
1726
                }
1727
                $counter++;
1728
            }
1729
            $desired_dir_name = $desired_dir_name.'_'.$counter;
1730
        } else {
1731
            return false;
1732
        }
1733
    }
1734
1735
    $systemFolderName = $desired_dir_name;
1736
1737
    // Adding suffix
1738
    $suffix = DocumentManager::getDocumentSuffix(
1739
        $_course,
1740
        $session_id,
1741
        $to_group_id
1742
    );
1743
1744
    $systemFolderName .= $suffix;
1745
1746
    if ($title == null) {
1747
        $title = basename($desired_dir_name);
1748
    }
1749
1750
    if (!is_dir($base_work_dir.$systemFolderName)) {
1751
        $result = mkdir(
1752
            $base_work_dir.$systemFolderName,
1753
            api_get_permissions_for_new_directories(),
1754
            true
1755
        );
1756
1757
        if ($result) {
1758
            // Check if pathname already exists inside document table
1759
            $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
1760
            $sql = "SELECT id, path FROM $tbl_document
1761
                    WHERE
1762
                        c_id = $course_id AND
1763
                        (
1764
                            path = '".Database::escape_string($systemFolderName)."'
1765
                        )
1766
            ";
1767
1768
            $groupInfo = [];
1769
            if (!empty($to_group_id)) {
1770
                $groupInfo = GroupManager::get_group_properties($to_group_id);
1771
            }
1772
1773
            $rs = Database::query($sql);
1774
            if (Database::num_rows($rs) == 0) {
1775
                $document_id = add_document(
1776
                    $_course,
1777
                    $systemFolderName,
1778
                    'folder',
1779
                    0,
1780
                    $title,
1781
                    null,
1782
                    0,
1783
                    true,
1784
                    $to_group_id,
1785
                    $session_id,
1786
                    $user_id,
1787
                    $sendNotification
1788
                );
1789
1790
                if ($document_id) {
1791
                    // Update document item_property
1792
                    if (!empty($visibility)) {
1793
                        $visibilities = [
1794
                            0 => 'invisible',
1795
                            1 => 'visible',
1796
                            2 => 'delete',
1797
                        ];
1798
                        api_item_property_update(
1799
                            $_course,
1800
                            TOOL_DOCUMENT,
1801
                            $document_id,
1802
                            $visibilities[$visibility],
1803
                            $user_id,
1804
                            $groupInfo,
1805
                            $to_user_id,
1806
                            null,
1807
                            null,
1808
                            $session_id
1809
                        );
1810
                    } else {
1811
                        api_item_property_update(
1812
                            $_course,
1813
                            TOOL_DOCUMENT,
1814
                            $document_id,
1815
                            'FolderCreated',
1816
                            $user_id,
1817
                            $groupInfo,
1818
                            $to_user_id,
1819
                            null,
1820
                            null,
1821
                            $session_id
1822
                        );
1823
                    }
1824
1825
                    $documentData = DocumentManager::get_document_data_by_id(
1826
                        $document_id,
1827
                        $_course['code'],
1828
                        false,
1829
                        $session_id
1830
                    );
1831
1832
                    return $documentData;
1833
                }
1834
            } else {
1835
                $document = Database::fetch_array($rs);
1836
                $documentData = DocumentManager::get_document_data_by_id(
1837
                    $document['id'],
1838
                    $_course['code'],
1839
                    false,
1840
                    $session_id
1841
                );
1842
1843
                /* This means the folder NOT exist in the filesystem
1844
                 (now this was created) but there is a record in the Database*/
1845
1846
                return $documentData;
1847
            }
1848
        }
1849
    }
1850
1851
    return false;
1852
}
1853
1854
/**
1855
 * Handles uploaded missing images.
1856
 *
1857
 * @author Hugues Peeters <[email protected]>
1858
 * @author Bert Vanderkimpen
1859
 *
1860
 * @param array  $_course
1861
 * @param array  $uploaded_file_collection - follows the $_FILES Structure
1862
 * @param string $base_work_dir
1863
 * @param string $missing_files_dir
1864
 * @param int    $user_id
1865
 * @param int    $to_group_id              group.id
1866
 */
1867
function move_uploaded_file_collection_into_directory(
1868
    $_course,
1869
    $uploaded_file_collection,
1870
    $base_work_dir,
1871
    $missing_files_dir,
1872
    $user_id,
1873
    $to_group_id,
1874
    $to_user_id,
1875
    $max_filled_space
1876
) {
1877
    $number_of_uploaded_images = count($uploaded_file_collection['name']);
1878
    $new_file_list = [];
1879
    for ($i = 0; $i < $number_of_uploaded_images; $i++) {
1880
        $missing_file['name'] = $uploaded_file_collection['name'][$i];
1881
        $missing_file['type'] = $uploaded_file_collection['type'][$i];
1882
        $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
1883
        $missing_file['error'] = $uploaded_file_collection['error'][$i];
1884
        $missing_file['size'] = $uploaded_file_collection['size'][$i];
1885
1886
        $upload_ok = process_uploaded_file($missing_file);
1887
        if ($upload_ok) {
1888
            $new_file_list[] = handle_uploaded_document(
1889
                $_course,
1890
                $missing_file,
1891
                $base_work_dir,
1892
                $missing_files_dir,
1893
                $user_id,
1894
                $to_group_id,
1895
                $to_user_id,
1896
                $max_filled_space,
1897
                0,
1898
                'overwrite'
1899
            );
1900
        }
1901
        unset($missing_file);
1902
    }
1903
1904
    return $new_file_list;
1905
}
1906
1907
/**
1908
 * Opens the old html file and replace the src path into the img tag
1909
 * This also works for files in subdirectories.
1910
 *
1911
 * @param $original_img_path is an array
1912
 * @param $new_img_path is an array
1913
 */
1914
function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file)
1915
{
1916
    // Open the file
1917
    $fp = fopen($html_file, 'r');
1918
    $buffer = fread($fp, filesize($html_file));
1919
    $new_html_content = '';
1920
1921
    // Fix the image tags
1922
    for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb; $i++) {
1923
        $replace_what = $original_img_path[$i];
1924
        // We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
1925
        $exploded_file_path = explode('/', $new_img_path[$i]);
1926
        $replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count($exploded_file_path) - 1];
1927
        $buffer = str_replace($replace_what, $replace_by, $buffer);
1928
    }
1929
1930
    $new_html_content .= $buffer;
1931
1932
    @fclose($fp);
1933
1934
    // Write the resulted new file
1935
1936
    if (!$fp = fopen($html_file, 'w')) {
1937
        return;
1938
    }
1939
1940
    if (!fwrite($fp, $new_html_content)) {
1941
        return;
1942
    }
1943
}
1944
1945
/**
1946
 * Checks the extension of a file, if it's .htm or .html
1947
 * we use search_img_from_html to get all image paths in the file.
1948
 *
1949
 * @param string $file
1950
 *
1951
 * @return array paths
1952
 *
1953
 * @see check_for_missing_files() uses search_img_from_html()
1954
 */
1955
function check_for_missing_files($file)
1956
{
1957
    if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
1958
        $img_file_path = search_img_from_html($file);
1959
1960
        return $img_file_path;
1961
    }
1962
1963
    return false;
1964
}
1965
1966
/**
1967
 * This function builds a form that asks for the missing images in a html file
1968
 * maybe we should do this another way?
1969
 *
1970
 * @param array  $missing_files
1971
 * @param string $upload_path
1972
 * @param string $file_name
1973
 *
1974
 * @return string the form
1975
 */
1976
function build_missing_files_form($missing_files, $upload_path, $file_name)
1977
{
1978
    // Do we need a / or not?
1979
    $added_slash = ($upload_path == '/') ? '' : '/';
1980
    $folder_id = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
1981
    // Build the form
1982
    $form = "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
1983
        ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
1984
        // Related_file is the path to the file that has missing images
1985
        ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
1986
        ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
1987
        ."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
1988
        ."<table border=\"0\">";
1989
    foreach ($missing_files as &$this_img_file_path) {
1990
        $form .= "<tr>"
1991
            ."<td>".basename($this_img_file_path)." : </td>"
1992
            ."<td>"
1993
            ."<input type=\"file\" name=\"img_file[]\"/>"
1994
            ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
1995
            ."</td>"
1996
            ."</tr>";
1997
    }
1998
    $form .= "</table>"
1999
        ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
2000
        ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
2001
        ."</form>";
2002
2003
    return $form;
2004
}
2005
2006
/**
2007
 * This recursive function can be used during the upgrade process form older
2008
 * versions of Chamilo
2009
 * It crawls the given directory, checks if the file is in the DB and adds
2010
 * it if it's not.
2011
 *
2012
 * @param array  $courseInfo
2013
 * @param array  $userInfo
2014
 * @param string $base_work_dir    course document dir
2015
 * @param string $folderPath       folder to read
2016
 * @param int    $sessionId
2017
 * @param int    $groupId          group.id
2018
 * @param bool   $output
2019
 * @param array  $parent
2020
 * @param string $whatIfFileExists
2021
 *
2022
 * @return bool
2023
 */
2024
function add_all_documents_in_folder_to_database(
2025
    $courseInfo,
2026
    $userInfo,
2027
    $base_work_dir,
2028
    $folderPath,
2029
    $sessionId = 0,
2030
    $groupId = 0,
2031
    $output = false,
2032
    $parent = [],
2033
    $whatIfFileExists = 'overwrite'
2034
) {
2035
    if (empty($userInfo) || empty($courseInfo)) {
2036
        return false;
2037
    }
2038
2039
    $userId = $userInfo['user_id'];
2040
2041
    // Open dir
2042
    $handle = opendir($folderPath);
2043
2044
    if (is_dir($folderPath)) {
2045
        // Run trough
2046
        while ($file = readdir($handle)) {
2047
            if ($file == '.' || $file == '..') {
2048
                continue;
2049
            }
2050
2051
            $parentPath = '';
2052
            if (!empty($parent) && isset($parent['path'])) {
2053
                $parentPath = $parent['path'];
2054
                if ($parentPath == '/') {
2055
                    $parentPath = '';
2056
                }
2057
            }
2058
2059
            $completePath = $parentPath.'/'.$file;
2060
            $sysFolderPath = $folderPath.'/'.$file;
2061
2062
            // Is directory?
2063
            if (is_dir($sysFolderPath)) {
2064
                $folderExists = DocumentManager::folderExists(
2065
                    $completePath,
2066
                    $courseInfo,
2067
                    $sessionId,
2068
                    $groupId
2069
                );
2070
2071
                if ($folderExists === true) {
2072
                    switch ($whatIfFileExists) {
2073
                        case 'overwrite':
2074
                            $documentId = DocumentManager::get_document_id($courseInfo, $completePath, $sessionId);
2075
                            if ($documentId) {
2076
                                $newFolderData = DocumentManager::get_document_data_by_id(
2077
                                    $documentId,
2078
                                    $courseInfo['code'],
2079
                                    false,
2080
                                    $sessionId
2081
                                );
2082
                            }
2083
                            break;
2084
                        case 'rename':
2085
                            $newFolderData = create_unexisting_directory(
2086
                                $courseInfo,
2087
                                $userId,
2088
                                $sessionId,
2089
                                $groupId,
2090
                                null,
2091
                                $base_work_dir,
2092
                                $completePath,
2093
                                null,
2094
                                null,
2095
                                true
2096
                            );
2097
                            break;
2098
                        case 'nothing':
2099
                            if ($output) {
2100
                                $documentId = DocumentManager::get_document_id($courseInfo, $completePath, $sessionId);
2101
                                if ($documentId) {
2102
                                    $folderData = DocumentManager::get_document_data_by_id(
2103
                                        $documentId,
2104
                                        $courseInfo['code'],
2105
                                        false,
2106
                                        $sessionId
2107
                                    );
2108
                                    Display::addFlash(
2109
                                        Display::return_message(
2110
                                            $folderData['path'].' '.get_lang('UplAlreadyExists'),
2111
                                            'warning'
2112
                                        )
2113
                                    );
2114
                                }
2115
                            }
2116
                            continue 2;
2117
                            break;
2118
                    }
2119
                } else {
2120
                    $newFolderData = create_unexisting_directory(
2121
                        $courseInfo,
2122
                        $userId,
2123
                        $sessionId,
2124
                        $groupId,
2125
                        null,
2126
                        $base_work_dir,
2127
                        $completePath,
2128
                        null,
2129
                        null,
2130
                        false
2131
                    );
2132
                }
2133
2134
                // Recursive
2135
                add_all_documents_in_folder_to_database(
2136
                    $courseInfo,
2137
                    $userInfo,
2138
                    $base_work_dir,
2139
                    $sysFolderPath,
2140
                    $sessionId,
2141
                    $groupId,
2142
                    $output,
2143
                    $newFolderData,
2144
                    $whatIfFileExists
2145
                );
2146
            } else {
2147
                // Rename
2148
                $uploadedFile = [
2149
                    'name' => $file,
2150
                    'tmp_name' => $sysFolderPath,
2151
                    'size' => filesize($sysFolderPath),
2152
                    'type' => null,
2153
                    'from_file' => true,
2154
                    'move_file' => true,
2155
                ];
2156
2157
                handle_uploaded_document(
2158
                    $courseInfo,
2159
                    $uploadedFile,
2160
                    $base_work_dir,
2161
                    $parentPath,
2162
                    $userId,
2163
                    $groupId,
2164
                    null,
2165
                    0,
2166
                    $whatIfFileExists,
2167
                    $output,
2168
                    false,
2169
                    null,
2170
                    $sessionId
2171
                );
2172
            }
2173
        }
2174
    }
2175
}
2176