Passed
Push — master ( 4bdc2e...194c5a )
by Julito
08:53
created

removeUnusedFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
nc 2
nop 0
dl 0
loc 24
rs 9.7666
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * This file contains additional dropbox functions. Initially there were some
8
 * functions in the init files also but I have moved them over
9
 * to one file -- Patrick Cool <[email protected]>, Ghent University.
10
 *
11
 * @author Julio Montoya adding c_id support
12
 */
13
$this_section = SECTION_COURSES;
14
15
$htmlHeadXtra[] = '<script>
16
function setFocus(){
17
    $("#category_title").focus();
18
}
19
$(function() {
20
    setFocus();
21
});
22
</script>';
23
24
/**
25
 * This function is a wrapper function for the multiple actions feature.
26
 *
27
 * @return string|null If there is a problem, return a string message, otherwise nothing
28
 *
29
 * @author   Patrick Cool <[email protected]>, Ghent University
30
 *
31
 * @version  march 2006
32
 */
33
function handle_multiple_actions()
34
{
35
    $_user = api_get_user_info();
36
    $is_courseAdmin = api_is_course_admin();
37
    $is_courseTutor = api_is_course_tutor();
38
39
    // STEP 1: are we performing the actions on the received or on the sent files?
40
    if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'download_received') {
41
        $part = 'received';
42
    } elseif ($_POST['action'] == 'delete_sent' || $_POST['action'] == 'download_sent') {
43
        $part = 'sent';
44
    }
45
46
    // STEP 2: at least one file has to be selected. If not we return an error message
47
    $ids = isset($_GET['id']) ? $_GET['id'] : [];
48
    if (count($ids) > 0) {
49
        $checked_file_ids = $_POST['id'];
50
    } else {
51
        foreach ($_POST as $key => $value) {
52
            if (strstr($value, $part.'_') && $key != 'view_received_category' && $key != 'view_sent_category') {
53
                $checked_files = true;
54
                $checked_file_ids[] = intval(substr($value, strrpos($value, '_')));
55
            }
56
        }
57
    }
58
    $checked_file_ids = $_POST['id'];
59
60
    if (!is_array($checked_file_ids) || count($checked_file_ids) == 0) {
61
        return get_lang('CheckAtLeastOneFile');
62
    }
63
64
    // STEP 3A: deleting
65
    if ($_POST['action'] == 'delete_received' || $_POST['action'] == 'delete_sent') {
66
        $dropboxfile = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
67
        foreach ($checked_file_ids as $key => $value) {
68
            if ($_GET['view'] == 'received') {
69
                $dropboxfile->deleteReceivedWork($value);
70
                $message = get_lang('ReceivedFileDeleted');
71
            }
72
            if ($_GET['view'] == 'sent' || empty($_GET['view'])) {
73
                $dropboxfile->deleteSentWork($value);
74
                $message = get_lang('SentFileDeleted');
75
            }
76
        }
77
78
        return $message;
79
    }
80
81
    // STEP 3B: giving comment
82
    if (strstr($_POST['action'], 'move_')) {
83
        // check move_received_n or move_sent_n command
84
        if (strstr($_POST['action'], 'received')) {
85
            $part = 'received';
86
            $to_cat_id = str_replace('move_received_', '', $_POST['action']);
87
        } else {
88
            $part = 'sent';
89
            $to_cat_id = str_replace('move_sent_', '', $_POST['action']);
90
        }
91
92
        foreach ($checked_file_ids as $value) {
93
            store_move($value, $to_cat_id, $part);
94
        }
95
96
        return get_lang('FilesMoved');
97
    }
98
99
    // STEP 3D: downloading
100
    if ($_POST['action'] == 'download_sent' || $_POST['action'] == 'download_received') {
101
        zip_download($checked_file_ids);
102
    }
103
}
104
105
/**
106
 * Get conf settings.
107
 *
108
 * @return array
109
 */
110
function getDropboxConf()
111
{
112
    return Session::read('dropbox_conf');
113
}
114
115
/**
116
 * This function deletes a dropbox category.
117
 *
118
 * @todo give the user the possibility what needs to be done with the files
119
 * in this category: move them to the root, download them as a zip, delete them
120
 *
121
 * @author Patrick Cool <[email protected]>, Ghent University
122
 *
123
 * @version march 2006
124
 */
125
function delete_category($action, $id, $user_id = null)
126
{
127
    $course_id = api_get_course_int_id();
128
    $is_courseAdmin = api_is_course_admin();
129
    $is_courseTutor = api_is_course_tutor();
130
131
    if (empty($user_id)) {
132
        $user_id = api_get_user_id();
133
    }
134
135
    $cat = get_dropbox_category($id);
136
    if (count($cat) == 0) {
137
        return false;
138
    }
139
140
    if ($cat['user_id'] != $user_id && !api_is_platform_admin($user_id)) {
141
        return false;
142
    }
143
144
    // an additional check that might not be necessary
145
    if ($action == 'deletereceivedcategory') {
146
        $sentreceived = 'received';
147
        $entries_table = Database::get_course_table(TABLE_DROPBOX_POST);
148
        $id_field = 'file_id';
149
        $return_message = get_lang('ReceivedCatgoryDeleted');
150
    } elseif ($action == 'deletesentcategory') {
151
        $sentreceived = 'sent';
152
        $entries_table = Database::get_course_table(TABLE_DROPBOX_FILE);
153
        $id_field = 'id';
154
        $return_message = get_lang('SentCatgoryDeleted');
155
    } else {
156
        return get_lang('Error');
157
    }
158
159
    // step 1: delete the category
160
    $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
161
            WHERE c_id = $course_id AND cat_id='".intval($id)."' AND $sentreceived='1'";
162
    Database::query($sql);
163
164
    // step 2: delete all the documents in this category
165
    $sql = "SELECT * FROM ".$entries_table."
166
            WHERE c_id = $course_id AND cat_id='".intval($id)."'";
167
    $result = Database::query($sql);
168
169
    while ($row = Database::fetch_array($result)) {
170
        $dropboxfile = new Dropbox_Person($user_id, $is_courseAdmin, $is_courseTutor);
171
        if ($action == 'deletereceivedcategory') {
172
            $dropboxfile->deleteReceivedWork($row[$id_field]);
173
        }
174
        if ($action == 'deletesentcategory') {
175
            $dropboxfile->deleteSentWork($row[$id_field]);
176
        }
177
    }
178
179
    return $return_message;
180
}
181
182
/**
183
 * Displays the form to move one individual file to a category.
184
 *
185
 *@ return html code of the form that appears in a message box.
186
 *
187
 * @author Julio Montoya - function rewritten
188
 */
189
function display_move_form(
190
    $part,
191
    $id,
192
    $target = [],
193
    $extra_params = [],
194
    $viewReceivedCategory,
195
    $viewSentCategory,
196
    $view
197
) {
198
    $form = new FormValidator(
199
        'form1',
200
        'post',
201
        api_get_self().'?view_received_category='.$viewReceivedCategory.'&view_sent_category='.$viewSentCategory.'&view='.$view.'&'.$extra_params
202
    );
203
    $form->addElement('header', get_lang('MoveFileTo'));
204
    $form->addElement('hidden', 'id', intval($id));
205
    $form->addElement('hidden', 'part', Security::remove_XSS($part));
206
207
    $options = ['0' => get_lang('Root')];
208
    foreach ($target as $category) {
209
        $options[$category['cat_id']] = $category['cat_name'];
210
    }
211
    $form->addElement('select', 'move_target', get_lang('MoveFileTo'), $options);
212
    $form->addButtonMove(get_lang('MoveFile'), 'do_move');
213
    $form->display();
214
}
215
216
/**
217
 * This function moves a file to a different category.
218
 *
219
 * @param int    $id     the id of the file we are moving
220
 * @param int    $target the id of the folder we are moving to
221
 * @param string $part   are we moving a received file or a sent file?
222
 *
223
 * @return string string
224
 *
225
 * @author Patrick Cool <[email protected]>, Ghent University
226
 *
227
 * @version march 2006
228
 */
229
function store_move($id, $target, $part)
230
{
231
    $_user = api_get_user_info();
232
    $course_id = api_get_course_int_id();
233
234
    if ((isset($id) && $id != '') &&
235
        (isset($target) && $target != '') &&
236
        (isset($part) && $part != '')
237
    ) {
238
        if ($part == 'received') {
239
            $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_POST)."
240
                    SET cat_id = ".intval($target)."
241
                    WHERE c_id = $course_id AND dest_user_id = ".intval($_user['user_id'])."
242
                    AND file_id = ".intval($id)."";
243
            Database::query($sql);
244
            $return_message = get_lang('ReceivedFileMoved');
245
        }
246
        if ($part == 'sent') {
247
            $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_FILE)."
248
                    SET cat_id = ".intval($target)."
249
                    WHERE
250
                        c_id = $course_id AND
251
                        uploader_id = ".intval($_user['user_id'])." AND
252
                        id = ".intval($id);
253
            Database::query($sql);
254
            $return_message = get_lang('SentFileMoved');
255
        }
256
    } else {
257
        $return_message = get_lang('NotMovedError');
258
    }
259
260
    return $return_message;
261
}
262
263
/**
264
 * This function retrieves all dropbox categories and returns them as an array.
265
 *
266
 * @param $filter default '', when we need only the categories of the sent or the received part
267
 *
268
 * @return array
269
 *
270
 * @author Patrick Cool <[email protected]>, Ghent University
271
 *
272
 * @version march 2006
273
 */
274
function get_dropbox_categories($filter = '')
275
{
276
    $course_id = api_get_course_int_id();
277
    $_user = api_get_user_info();
278
    $return_array = [];
279
280
    $session_id = api_get_session_id();
281
    $condition_session = api_get_session_condition($session_id);
282
283
    $sql = "SELECT * FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
284
            WHERE c_id = $course_id AND user_id='".$_user['user_id']."' $condition_session";
285
286
    $result = Database::query($sql);
287
    while ($row = Database::fetch_array($result)) {
288
        if (($filter == 'sent' && $row['sent'] == 1) ||
289
            ($filter == 'received' && $row['received'] == 1) || $filter == ''
290
        ) {
291
            $return_array[$row['cat_id']] = $row;
292
        }
293
    }
294
295
    return $return_array;
296
}
297
298
/**
299
 * Get a dropbox category details.
300
 *
301
 * @param int The category ID
302
 *
303
 * @return array The details of this category
304
 */
305
function get_dropbox_category($id)
306
{
307
    $course_id = api_get_course_int_id();
308
    $id = (int) $id;
309
310
    if (empty($id)) {
311
        return [];
312
    }
313
314
    $sql = "SELECT * FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
315
            WHERE c_id = $course_id AND cat_id='".$id."'";
316
    $res = Database::query($sql);
317
    if ($res === false) {
318
        return [];
319
    }
320
    $row = Database::fetch_assoc($res);
321
322
    return $row;
323
}
324
325
/**
326
 * This functions stores a new dropboxcategory.
327
 *
328
 * @var it might not seem very elegant if you create a category in sent
329
 *         and in received with the same name that you get two entries in the
330
 *         dropbox_category table but it is the easiest solution. You get
331
 *         cat_name | received | sent | user_id
332
 *         test     |    1     |   0  |    237
333
 *         test     |    0     |   1  |    237
334
 *         more elegant would be
335
 *         test     |    1     |   1  |    237
336
 *
337
 * @author Patrick Cool <[email protected]>, Ghent University
338
 *
339
 * @version march 2006
340
 */
341
function store_addcategory()
342
{
343
    $course_id = api_get_course_int_id();
344
    $_user = api_get_user_info();
345
346
    // check if the target is valid
347
    if ($_POST['target'] == 'sent') {
348
        $sent = 1;
349
        $received = 0;
350
    } elseif ($_POST['target'] == 'received') {
351
        $sent = 0;
352
        $received = 1;
353
    } else {
354
        return get_lang('Error');
355
    }
356
357
    // check if the category name is valid
358
    if ($_POST['category_name'] == '') {
359
        return ['type' => 'error', 'message' => get_lang('ErrorPleaseGiveCategoryName')];
360
    }
361
362
    if (!isset($_POST['edit_id'])) {
363
        $session_id = api_get_session_id();
364
        // step 3a, we check if the category doesn't already exist
365
        $sql = "SELECT * FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
366
                WHERE
367
                    c_id = $course_id AND
368
                    user_id='".$_user['user_id']."' AND
369
                    cat_name='".Database::escape_string($_POST['category_name'])."' AND
370
                    received='".$received."' AND
371
                    sent='$sent' AND
372
                    session_id='$session_id'";
373
        $result = Database::query($sql);
374
375
        // step 3b, we add the category if it does not exist yet.
376
        if (Database::num_rows($result) == 0) {
377
            $params = [
378
                'cat_id' => 0,
379
                'c_id' => $course_id,
380
                'cat_name' => $_POST['category_name'],
381
                'received' => $received,
382
                'sent' => $sent,
383
                'user_id' => $_user['user_id'],
384
                'session_id' => $session_id,
385
            ];
386
            $id = Database::insert(Database::get_course_table(TABLE_DROPBOX_CATEGORY), $params);
387
            if ($id) {
388
                $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)." SET cat_id = iid 
389
                        WHERE iid = $id";
390
                Database::query($sql);
391
            }
392
393
            return ['type' => 'confirmation', 'message' => get_lang('CategoryStored')];
394
        } else {
395
            return ['type' => 'error', 'message' => get_lang('CategoryAlreadyExistsEditIt')];
396
        }
397
    } else {
398
        $params = [
399
            'cat_name' => $_POST['category_name'],
400
            'received' => $received,
401
            'sent' => $sent,
402
        ];
403
404
        Database::update(
405
            Database::get_course_table(TABLE_DROPBOX_CATEGORY),
406
            $params,
407
            [
408
                'c_id = ? AND user_id = ? AND cat_id = ?' => [
409
                    $course_id,
410
                    $_user['user_id'],
411
                    $_POST['edit_id'],
412
                ],
413
            ]
414
        );
415
416
        return ['type' => 'confirmation', 'message' => get_lang('CategoryModified')];
417
    }
418
}
419
420
/**
421
 * This function displays the form to add a new category.
422
 *
423
 * @param string $category_name this parameter is the name of the category (used when no section is selected)
424
 * @param int    $id            this is the id of the category we are editing
425
 *
426
 * @author Patrick Cool <[email protected]>, Ghent University
427
 *
428
 * @version march 2006
429
 */
430
function display_addcategory_form($category_name = '', $id = 0, $action = '')
431
{
432
    $course_id = api_get_course_int_id();
433
    $title = get_lang('AddNewCategory');
434
435
    $id = (int) $id;
436
437
    if (!empty($id)) {
438
        // retrieve the category we are editing
439
        $sql = "SELECT * FROM ".Database::get_course_table(TABLE_DROPBOX_CATEGORY)."
440
                WHERE c_id = $course_id AND cat_id = ".$id;
441
        $result = Database::query($sql);
442
        $row = Database::fetch_array($result);
443
444
        if (empty($category_name)) {
445
            // after an edit with an error we do not want to return to the
446
            // original name but the name we already modified.
447
            // (happens when createinrecievedfiles AND createinsentfiles are not checked)
448
            $category_name = $row['cat_name'];
449
        }
450
        if ($row['received'] == '1') {
451
            $target = 'received';
452
        }
453
        if ($row['sent'] == '1') {
454
            $target = 'sent';
455
        }
456
        $title = get_lang('EditCategory');
457
    }
458
459
    if ($action == 'addreceivedcategory') {
460
        $target = 'received';
461
    }
462
    if ($action == 'addsentcategory') {
463
        $target = 'sent';
464
    }
465
466
    if ($action == 'editcategory') {
467
        $text = get_lang('ModifyCategory');
468
    } elseif ($action == 'addreceivedcategory' || $action == 'addsentcategory') {
469
        $text = get_lang('CreateCategory');
470
    }
471
472
    $form = new FormValidator(
473
        'add_new_category',
474
        'post',
475
        api_get_self().'?'.api_get_cidreq().'&view='.Security::remove_XSS($_GET['view'])
476
    );
477
    $form->addElement('header', $title);
478
479
    if (!empty($id)) {
480
        $form->addElement('hidden', 'edit_id', $id);
481
    }
482
    $form->addElement('hidden', 'action', Security::remove_XSS($action));
483
    $form->addElement('hidden', 'target', Security::remove_XSS($target));
484
485
    $form->addElement('text', 'category_name', get_lang('CategoryName'));
486
    $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required');
487
    $form->addButtonSave($text, 'StoreCategory');
488
489
    $defaults = [];
490
    $defaults['category_name'] = Security::remove_XSS($category_name);
491
    $form->setDefaults($defaults);
492
    $form->display();
493
}
494
495
/**
496
 * this function displays the form to upload a new item to the dropbox.
497
 *
498
 * @param $viewReceivedCategory
499
 * @param $viewSentCategory
500
 * @param $view
501
 * @param int $id
502
 *
503
 * @author Patrick Cool <[email protected]>, Ghent University
504
 * @author Julio Montoya
505
 *
506
 * @version march 2006
507
 */
508
function display_add_form($viewReceivedCategory, $viewSentCategory, $view, $id = 0)
509
{
510
    $course_info = api_get_course_info();
511
    $_user = api_get_user_info();
512
    $is_courseAdmin = api_is_course_admin();
513
    $is_courseTutor = api_is_course_tutor();
514
    $origin = api_get_origin();
515
516
    $token = Security::get_token();
517
    $dropbox_person = new Dropbox_Person(
518
        api_get_user_id(),
519
        $is_courseAdmin,
520
        $is_courseTutor
521
    );
522
523
    $idCondition = !empty($id) ? '&id='.(int) $id : '';
524
525
    $url = api_get_self().'?view_received_category='.$viewReceivedCategory.'&view_sent_category='.$viewSentCategory.'&view='.$view.'&'.api_get_cidreq().$idCondition;
526
    $form = new FormValidator(
527
        'sent_form',
528
        'post',
529
        $url,
530
        null,
531
        [
532
            'enctype' => 'multipart/form-data',
533
            'onsubmit' => 'javascript: return checkForm(this);',
534
        ]
535
    );
536
537
    $form->addElement('header', get_lang('UploadNewFile'));
538
    $maxFileSize = api_get_setting('dropbox_max_filesize');
539
    $form->addElement('hidden', 'MAX_FILE_SIZE', $maxFileSize);
540
    $form->addElement('hidden', 'sec_token', $token);
541
    $form->addElement('hidden', 'origin', $origin);
542
    $form->addElement(
543
        'file',
544
        'file',
545
        get_lang('UploadFile'),
546
        ['onChange' => 'javascript: checkfile(this.value);']
547
    );
548
549
    $allowOverwrite = api_get_setting('dropbox_allow_overwrite');
550
    if ($allowOverwrite == 'true' && empty($idCondition)) {
551
        $form->addElement(
552
            'checkbox',
553
            'cb_overwrite',
554
            null,
555
            get_lang('OverwriteFile'),
556
            ['id' => 'cb_overwrite']
557
        );
558
    }
559
560
    // List of all users in this course and all virtual courses combined with it
561
    if (api_get_session_id()) {
562
        $complete_user_list_for_dropbox = [];
563
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
564
            $complete_user_list_for_dropbox = CourseManager:: get_user_list_from_course_code(
565
                $course_info['code'],
566
                api_get_session_id(),
567
                null,
568
                null,
569
                0,
570
                false,
571
                false,
572
                false,
573
                [],
574
                [],
575
                [],
576
                true
577
            );
578
        }
579
580
        $complete_user_list2 = CourseManager::get_coach_list_from_course_code(
581
            $course_info['code'],
582
            api_get_session_id()
583
        );
584
585
        $generalCoachList = [];
586
        $courseCoachList = [];
587
        foreach ($complete_user_list2 as $coach) {
588
            if ($coach['type'] == 'general_coach') {
589
                $generalCoachList[] = $coach;
590
            } else {
591
                $courseCoachList[] = $coach;
592
            }
593
        }
594
595
        $hideCourseCoach = api_get_setting('dropbox_hide_course_coach');
596
        if ($hideCourseCoach == 'false') {
597
            $complete_user_list_for_dropbox = array_merge(
598
                $complete_user_list_for_dropbox,
599
                $courseCoachList
600
            );
601
        }
602
        $hideGeneralCoach = api_get_setting('dropbox_hide_general_coach');
603
604
        if ($hideGeneralCoach == 'false') {
605
            $complete_user_list_for_dropbox = array_merge(
606
                $complete_user_list_for_dropbox,
607
                $generalCoachList
608
            );
609
        }
610
    } else {
611
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
612
            $complete_user_list_for_dropbox = CourseManager::get_user_list_from_course_code(
613
                $course_info['code'],
614
                api_get_session_id(),
615
                null,
616
                null,
617
                null,
618
                false,
619
                false,
620
                false,
621
                [],
622
                [],
623
                [],
624
                true
625
            );
626
        } else {
627
            $complete_user_list_for_dropbox = CourseManager::get_teacher_list_from_course_code(
628
                $course_info['code'],
629
                false
630
            );
631
        }
632
    }
633
634
    if (!empty($complete_user_list_for_dropbox)) {
635
        foreach ($complete_user_list_for_dropbox as $k => $e) {
636
            $complete_user_list_for_dropbox[$k] = $e + [
637
                'lastcommafirst' => api_get_person_name(
638
                    $e['firstname'],
639
                    $e['lastname']
640
                ),
641
            ];
642
        }
643
        $complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
644
    }
645
646
    /*
647
        Create the options inside the select box:
648
        List all selected users their user id as value and a name string as display
649
    */
650
    $current_user_id = '';
651
    $allowStudentToStudent = api_get_setting('dropbox_allow_student_to_student');
652
    $options = [];
653
    $userGroup = new UserGroup();
654
    foreach ($complete_user_list_for_dropbox as $current_user) {
655
        if ((
656
            $dropbox_person->isCourseTutor
657
                || $dropbox_person->isCourseAdmin
658
                || $allowStudentToStudent == 'true'
659
                || $current_user['status'] != 5                         // Always allow teachers.
660
                || $current_user['is_tutor'] == 1                       // Always allow tutors.
661
                ) && $current_user['user_id'] != $_user['user_id']) {   // Don't include yourself.
662
            if ($current_user['user_id'] == $current_user_id) {
663
                continue;
664
            }
665
            $userId = $current_user['user_id'];
666
            $userInfo = api_get_user_info($userId);
667
            if ($userInfo['status'] != INVITEE) {
668
                $groupNameListToString = '';
669
                if (!empty($groups)) {
670
                    $groupNameList = array_column($groups, 'name');
671
                    $groupNameListToString = ' - ['.implode(', ', $groupNameList).']';
672
                }
673
                $groups = $userGroup->getUserGroupListByUser($userId);
674
675
                $full_name = $userInfo['complete_name'].$groupNameListToString;
676
                $current_user_id = $current_user['user_id'];
677
                $options['user_'.$current_user_id] = $full_name;
678
            }
679
        }
680
    }
681
682
    /*
683
    * Show groups
684
    */
685
    $allowGroups = api_get_setting('dropbox_allow_group');
686
    if (($dropbox_person->isCourseTutor || $dropbox_person->isCourseAdmin)
687
        && $allowGroups == 'true' || $allowStudentToStudent == 'true'
688
    ) {
689
        $complete_group_list_for_dropbox = GroupManager::get_group_list(null, $course_info);
690
691
        if (count($complete_group_list_for_dropbox) > 0) {
692
            foreach ($complete_group_list_for_dropbox as $current_group) {
693
                if ($current_group['number_of_members'] > 0) {
694
                    $options['group_'.$current_group['id']] = 'G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users');
695
                }
696
            }
697
        }
698
    }
699
700
    $allowUpload = api_get_setting('dropbox_allow_just_upload');
701
    if ($allowUpload == 'true') {
702
        $options['user_'.$_user['user_id']] = get_lang('JustUploadInSelect');
703
    }
704
705
    if (empty($idCondition)) {
706
        $form->addSelect(
707
            'recipients',
708
            get_lang('SendTo'),
709
            $options,
710
            [
711
                'multiple' => 'multiple',
712
                'size' => '10',
713
            ]
714
        );
715
    }
716
    $form->addButtonUpload(get_lang('Upload'), 'submitWork');
717
718
    $headers = [
719
        get_lang('Upload'),
720
        get_lang('Upload').' ('.get_lang('Simple').')',
721
    ];
722
723
    $multipleForm = new FormValidator(
724
        'sent_multiple',
725
        'post',
726
        '#',
727
        null,
728
        ['enctype' => 'multipart/form-data', 'id' => 'fileupload']
729
    );
730
731
    if (empty($idCondition)) {
732
        $multipleForm->addSelect(
733
            'recipients',
734
            get_lang('SendTo'),
735
            $options,
736
            [
737
                'multiple' => 'multiple',
738
                'size' => '10',
739
                'id' => 'recipient_form',
740
            ]
741
        );
742
    }
743
744
    $url = api_get_path(WEB_AJAX_PATH).'dropbox.ajax.php?'.api_get_cidreq().'&a=upload_file&'.$idCondition;
745
    if (empty($idCondition)) {
746
        $multipleForm->addHtml('<div id="multiple_form" style="display:none">');
747
    }
748
    $multipleForm->addMultipleUpload($url);
749
    if (empty($idCondition)) {
750
        $multipleForm->addHtml('</div>');
751
    }
752
753
    echo Display::tabs(
754
        $headers,
755
        [$multipleForm->returnForm(), $form->returnForm()],
756
        'tabs'
757
    );
758
}
759
760
/**
761
 * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
762
 * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server.
763
 */
764
function removeUnusedFiles()
765
{
766
    $_course = api_get_course_info();
767
    $course_id = $_course['real_id'];
768
769
    // select all files that aren't referenced anymore
770
    $sql = "SELECT DISTINCT f.id, f.filename
771
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." f
772
            LEFT JOIN ".Database::get_course_table(TABLE_DROPBOX_PERSON)." p
773
            ON (f.id = p.file_id)
774
            WHERE p.user_id IS NULL AND
775
                  f.c_id = $course_id
776
            ";
777
    $result = Database::query($sql);
778
    while ($res = Database::fetch_array($result)) {
779
        //delete the selected files from the post and file tables
780
        $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
781
                WHERE c_id = $course_id AND file_id = '".$res['id']."'";
782
        Database::query($sql);
783
        $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)."
784
                WHERE c_id = $course_id AND id ='".$res['id']."'";
785
        Database::query($sql);
786
        //delete file from server
787
        @unlink(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$res['filename']);
788
    }
789
}
790
791
/**
792
 * Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
793
 * and is only visible to its uploader (user_id).
794
 *
795
 * Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
796
 * and are visible initially to recipient and pseudo_id.
797
 *
798
 * @author René Haentjens, Ghent University
799
 *
800
 * @todo check if this function is still necessary.
801
 */
802
function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
803
{
804
    $course_id = api_get_course_int_id();
805
806
    $mailingPseudoId = (int) $mailingPseudoId;
807
    $sql = "SELECT f.uploader_id
808
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." f
809
            LEFT JOIN ".Database::get_course_table(TABLE_DROPBOX_POST)." p
810
            ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
811
            WHERE
812
                p.dest_user_id = '".$mailingPseudoId."' AND
813
                p.c_id = $course_id
814
            ";
815
    $result = Database::query($sql);
816
817
    if (!($res = Database::fetch_array($result))) {
818
        die(get_lang('GeneralError').' (code 901)');
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...
819
    }
820
    if ($owner == 0) {
821
        return $res['uploader_id'];
822
    }
823
    if ($res['uploader_id'] == $owner) {
824
        return true;
825
    }
826
    die(get_lang('GeneralError').' (code '.$or_die.')');
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...
827
}
828
829
/**
830
 * @author René Haentjens, Ghent University
831
 *
832
 * @todo check if this function is still necessary.
833
 */
834
function removeMoreIfMailing($file_id)
835
{
836
    $course_id = api_get_course_int_id();
837
    // when deleting a mailing zip-file (posted to mailingPseudoId):
838
    // 1. the detail window is no longer reachable, so
839
    //    for all content files, delete mailingPseudoId from person-table
840
    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
841
    //    for all content files, replace mailingPseudoId by owner as uploader
842
    $file_id = (int) $file_id;
843
    $sql = "SELECT p.dest_user_id
844
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)." p
845
            WHERE c_id = $course_id AND p.file_id = '".$file_id."'";
846
    $result = Database::query($sql);
847
848
    if ($res = Database::fetch_array($result)) {
849
        $mailingPseudoId = $res['dest_user_id'];
850
        $mailId = get_mail_id_base();
851
        if ($mailingPseudoId > $mailId) {
852
            $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
853
                    WHERE c_id = $course_id AND user_id='".$mailingPseudoId."'";
854
            Database::query($sql);
855
856
            $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_FILE)."
857
                    SET uploader_id='".api_get_user_id()."'
858
                    WHERE c_id = $course_id AND uploader_id='".$mailingPseudoId."'";
859
            Database::query($sql);
860
        }
861
    }
862
}
863
864
/**
865
 * @param array            $file
866
 * @param Dropbox_SentWork $work
867
 *
868
 * @return array|string|null
869
 */
870
function store_add_dropbox($file = [], $work = null)
871
{
872
    $_course = api_get_course_info();
873
    $_user = api_get_user_info();
874
875
    if (empty($file)) {
876
        $file = isset($_FILES['file']) ? $_FILES['file'] : null;
877
    }
878
879
    if (empty($work)) {
880
        // Validating the form data
881
        // there are no recipients selected
882
        if (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
883
            return get_lang('YouMustSelectAtLeastOneDestinee');
884
        } else {
885
            // Check if all the recipients are valid
886
            $thisIsAMailing = false;
887
            $thisIsJustUpload = false;
888
889
            foreach ($_POST['recipients'] as $rec) {
890
                if ($rec == 'mailing') {
891
                    $thisIsAMailing = true;
892
                } elseif ($rec == 'upload') {
893
                    $thisIsJustUpload = true;
894
                } elseif (strpos($rec, 'user_') === 0 &&
895
                    !CourseManager::is_user_subscribed_in_course(
896
                        substr($rec, strlen('user_')),
897
                        $_course['code'],
898
                        true
899
                    )
900
                ) {
901
                    Display::addFlash(
902
                        Display::return_message(
903
                            get_lang('InvalideUserDetected'),
904
                            'warning'
905
                        )
906
                    );
907
908
                    return false;
909
                } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
910
                    Display::addFlash(
911
                        Display::return_message(
912
                            get_lang('InvalideGroupDetected'),
913
                            'warning'
914
                        )
915
                    );
916
917
                    return false;
918
                }
919
            }
920
        }
921
922
        // we are doing a mailing but an additional recipient is selected
923
        if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
924
            Display::addFlash(
925
                Display::return_message(
926
                    get_lang('MailingSelectNoOther'),
927
                    'warning'
928
                )
929
            );
930
931
            return false;
932
        }
933
934
        // we are doing a just upload but an additional recipient is selected.
935
        // note: why can't this be valid? It is like sending a document to
936
        // yourself AND to a different person (I do this quite often with my e-mails)
937
        if ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
938
            Display::addFlash(
939
                Display::return_message(
940
                    get_lang('MailingJustUploadSelectNoOther'),
941
                    'warning'
942
                )
943
            );
944
945
            return false;
946
        }
947
    }
948
949
    if (empty($file['name'])) {
950
        Display::addFlash(Display::return_message(get_lang('NoFileSpecified'), 'warning'));
951
952
        return false;
953
    }
954
955
    // are we overwriting a previous file or sending a new one
956
    $dropbox_overwrite = false;
957
    if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
958
        $dropbox_overwrite = true;
959
    }
960
961
    // doing the upload
962
    $dropbox_filename = $file['name'];
963
    $dropbox_filesize = $file['size'];
964
    $dropbox_filetype = $file['type'];
965
    $dropbox_filetmpname = $file['tmp_name'];
966
967
    // check if the filesize does not exceed the allowed size.
968
    $maxFileSize = api_get_setting('dropbox_max_filesize');
969
    if ($dropbox_filesize <= 0 || $dropbox_filesize > $maxFileSize) {
970
        Display::addFlash(Display::return_message(get_lang('DropboxFileTooBig'), 'warning'));
971
972
        return false;
973
    }
974
975
    // check if the file is actually uploaded
976
    if (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
977
        Display::addFlash(Display::return_message(get_lang('TheFileIsNotUploaded'), 'warning'));
978
979
        return false;
980
    }
981
982
    $upload_ok = process_uploaded_file($file, true);
983
984
    if (!$upload_ok) {
985
        return null;
986
    }
987
988
    // Try to add an extension to the file if it hasn't got one
989
    $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
990
    // Replace dangerous characters
991
    $dropbox_filename = api_replace_dangerous_char($dropbox_filename);
992
    // Transform any .php file in .phps fo security
993
    $dropbox_filename = php2phps($dropbox_filename);
994
995
    //filter extension
996
    if (!filter_extension($dropbox_filename)) {
997
        Display::addFlash(
998
            Display::return_message(
999
                get_lang('UplUnableToSaveFileFilteredExtension'),
1000
                'warning'
1001
            )
1002
        );
1003
1004
        return false;
1005
    }
1006
1007
    // set title
1008
    $dropbox_title = $dropbox_filename;
1009
    // note: I think we could better migrate everything from here on to
1010
    // separate functions: store_new_dropbox, store_new_mailing, store_just_upload
1011
    if ($dropbox_overwrite && empty($work)) {
1012
        $dropbox_person = new Dropbox_Person(
1013
            $_user['user_id'],
1014
            api_is_course_admin(),
1015
            api_is_course_tutor()
1016
        );
1017
        $mailId = get_mail_id_base();
1018
        foreach ($dropbox_person->sentWork as $w) {
1019
            if ($w->title == $dropbox_filename) {
1020
                if (($w->recipients[0]['id'] > $mailId) xor $thisIsAMailing) {
1021
                    Display::addFlash(Display::return_message(get_lang('MailingNonMailingError'), 'warning'));
1022
1023
                    return false;
1024
                }
1025
                if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
1026
                    Display::addFlash(Display::return_message(get_lang('MailingJustUploadSelectNoOther'), 'warning'));
1027
1028
                    return false;
1029
                }
1030
                $dropbox_filename = $w->filename;
1031
                $found = true; // note: do we still need this?
1032
                break;
1033
            }
1034
        }
1035
    } else {  // rename file to login_filename_uniqueId format
1036
        $dropbox_filename = $_user['username']."_".$dropbox_filename."_".uniqid('');
1037
    }
1038
1039
    if (empty($work)) {
1040
        // creating the array that contains all the users who will receive the file
1041
        $new_work_recipients = [];
1042
        foreach ($_POST['recipients'] as $rec) {
1043
            if (strpos($rec, 'user_') === 0) {
1044
                $new_work_recipients[] = substr($rec, strlen('user_'));
1045
            } elseif (strpos($rec, 'group_') === 0) {
1046
                $groupInfo = GroupManager::get_group_properties(substr($rec, strlen('group_')));
1047
                $userList = GroupManager::get_subscribed_users($groupInfo);
1048
                foreach ($userList as $usr) {
1049
                    if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) {
1050
                        $new_work_recipients[] = $usr['user_id'];
1051
                    }
1052
                }
1053
            }
1054
        }
1055
    }
1056
1057
    @move_uploaded_file(
1058
        $dropbox_filetmpname,
1059
        api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$dropbox_filename
1060
    );
1061
1062
    $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
1063
1064
    if ($b_send_mail && empty($work)) {
1065
        foreach ($new_work_recipients as $recipient_id) {
1066
            $recipent_temp = api_get_user_info($recipient_id);
1067
            $additionalParameters = [
1068
                'smsType' => SmsPlugin::NEW_FILE_SHARED_COURSE_BY,
1069
                'userId' => $recipient_id,
1070
                'courseTitle' => $_course['title'],
1071
                'userUsername' => $recipent_temp['username'],
1072
            ];
1073
            api_mail_html(
1074
                api_get_person_name(
1075
                    $recipent_temp['firstname'].' '.$recipent_temp['lastname'],
1076
                    null,
1077
                    PERSON_NAME_EMAIL_ADDRESS
1078
                ),
1079
                $recipent_temp['email'],
1080
                get_lang('NewDropboxFileUploaded'),
1081
                get_lang('NewDropboxFileUploadedContent').' <a href="'.api_get_path(WEB_CODE_PATH).'dropbox/index.php?'.api_get_cidreq().'">'.get_lang('SeeFile').'</a>'.
1082
                "\n\n".
1083
                api_get_person_name(
1084
                    $_user['firstName'],
1085
                    $_user['lastName'],
1086
                    null,
1087
                    PERSON_NAME_EMAIL_ADDRESS
1088
                )."\n".get_lang('Email')." : ".$_user['mail'],
1089
                api_get_person_name(
1090
                    $_user['firstName'],
1091
                    $_user['lastName'],
1092
                    null,
1093
                    PERSON_NAME_EMAIL_ADDRESS
1094
                ),
1095
                $_user['mail'],
1096
                null,
1097
                null,
1098
                null,
1099
                $additionalParameters
1100
            );
1101
        }
1102
    }
1103
1104
    if (empty($work)) {
1105
        // Create new
1106
        $result = new Dropbox_SentWork(
1107
            $_user['user_id'],
1108
            $dropbox_title,
1109
            isset($_POST['description']) ? $_POST['description'] : '',
1110
            api_get_user_id(),
1111
            $dropbox_filename,
1112
            $dropbox_filesize,
1113
            $new_work_recipients
1114
        );
1115
    } else {
1116
        // Update
1117
        $work->title = $dropbox_title;
1118
        $work->filename = $dropbox_filename;
1119
        $work->filesize = $dropbox_filesize;
1120
        $work->upload_date = api_get_utc_datetime();
1121
        $work->last_upload_date = api_get_utc_datetime();
1122
        $work->description = isset($_POST['description']) ? $_POST['description'] : '';
1123
        $work->uploader_id = api_get_user_id();
1124
        $work->updateFile();
1125
        $result = $work;
1126
    }
1127
1128
    Security::clear_token();
1129
    Display::addFlash(Display::return_message(get_lang('FileUploadSucces')));
1130
1131
    return $result;
1132
}
1133
1134
/**
1135
 * Transforms the array containing all the feedback into something visually attractive.
1136
 *
1137
 * @param an array containing all the feedback about the given message
1138
 *
1139
 * @author Patrick Cool <[email protected]>, Ghent University
1140
 *
1141
 * @version march 2006
1142
 */
1143
function feedback($array, $url)
1144
{
1145
    $output = null;
1146
    foreach ($array as $value) {
1147
        $output .= format_feedback($value);
1148
    }
1149
    $output .= feedback_form($url);
1150
1151
    return $output;
1152
}
1153
1154
/**
1155
 * This function returns the html code to display the feedback messages on a given dropbox file.
1156
 *
1157
 * @param $feedback_array an array that contains all the feedback messages about the given document
1158
 *
1159
 * @return string code
1160
 *
1161
 * @todo add the form for adding new comment (if the other party has not deleted it yet).
1162
 *
1163
 * @author Patrick Cool <[email protected]>, Ghent University
1164
 *
1165
 * @version march 2006
1166
 */
1167
function format_feedback($feedback)
1168
{
1169
    $userInfo = api_get_user_info($feedback['author_user_id']);
1170
    $output = UserManager::getUserProfileLink($userInfo);
1171
    $output .= '&nbsp;&nbsp;'.Display::dateToStringAgoAndLongDate($feedback['feedback_date']).'<br />';
1172
    $output .= '<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
1173
1174
    return $output;
1175
}
1176
1177
/**
1178
 * this function returns the code for the form for adding a new feedback message to a dropbox file.
1179
 *
1180
 * @param $url  url string
1181
 *
1182
 * @return string code
1183
 *
1184
 * @author Patrick Cool <[email protected]>, Ghent University
1185
 *
1186
 * @version march 2006
1187
 */
1188
function feedback_form($url)
1189
{
1190
    $return = '<div class="feeback-form">';
1191
    $number_users_who_see_file = check_if_file_exist($_GET['id']);
1192
    if ($number_users_who_see_file) {
1193
        $token = Security::get_token();
1194
        $return .= '<div class="form-group">';
1195
        $return .= '<input type="hidden" name="sec_token" value="'.$token.'"/>';
1196
        $return .= '<label class="col-sm-3 control-label">'.get_lang('AddNewFeedback');
1197
        $return .= '</label>';
1198
        $return .= '<div class="col-sm-6">';
1199
        $return .= '<textarea name="feedback" class="form-control" rows="4"></textarea>';
1200
        $return .= '</div>';
1201
        $return .= '<div class="col-sm-3">';
1202
        $return .= '<div class="float-right"><a class="btn btn-default btn-sm" href="'.$url.'"><i class="fa fa-times" aria-hidden="true"></i></a></div>';
1203
        $return .= '<button type="submit" class="btn btn-primary btn-sm" name="store_feedback" value="'.get_lang('Ok').'"
1204
                    onclick="javascript: document.form_dropbox.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
1205
        $return .= '</div>';
1206
        $return .= '</div>';
1207
        $return .= '</div>';
1208
    } else {
1209
        $return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
1210
    }
1211
1212
    return $return;
1213
}
1214
1215
function user_can_download_file($id, $user_id)
1216
{
1217
    $course_id = api_get_course_int_id();
1218
    $id = (int) $id;
1219
    $user_id = (int) $user_id;
1220
1221
    $sql = "SELECT file_id 
1222
            FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
1223
            WHERE c_id = $course_id AND user_id = $user_id AND file_id = ".$id;
1224
    $result = Database::query($sql);
1225
    $number_users_who_see_file = Database::num_rows($result);
1226
1227
    $sql = "SELECT file_id 
1228
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
1229
            WHERE c_id = $course_id AND dest_user_id = $user_id AND file_id = ".$id;
1230
    $result = Database::query($sql);
1231
    $count = Database::num_rows($result);
1232
1233
    return $number_users_who_see_file > 0 || $count > 0;
1234
}
1235
1236
// we now check if the other users have not delete this document yet.
1237
// If this is the case then it is useless to see the
1238
// add feedback since the other users will never get to see the feedback.
1239
function check_if_file_exist($id)
1240
{
1241
    $id = (int) $id;
1242
    $course_id = api_get_course_int_id();
1243
    $sql = "SELECT file_id 
1244
            FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
1245
            WHERE c_id = $course_id AND file_id = ".$id;
1246
    $result = Database::query($sql);
1247
    $number_users_who_see_file = Database::num_rows($result);
1248
1249
    $sql = "SELECT file_id 
1250
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
1251
            WHERE c_id = $course_id AND file_id = ".$id;
1252
    $result = Database::query($sql);
1253
    $count = Database::num_rows($result);
1254
1255
    return $number_users_who_see_file > 0 || $count > 0;
1256
}
1257
1258
/**
1259
 * @return string language string (depending on the success or failure
1260
 *
1261
 * @author Patrick Cool <[email protected]>, Ghent University
1262
 *
1263
 * @version march 2006
1264
 */
1265
function store_feedback()
1266
{
1267
    if (!is_numeric($_GET['id'])) {
1268
        return get_lang('FeedbackError');
1269
    }
1270
    $course_id = api_get_course_int_id();
1271
    if (empty($_POST['feedback'])) {
1272
        return get_lang('PleaseTypeText');
1273
    } else {
1274
        $params = [
1275
            'c_id' => $course_id,
1276
            'file_id' => $_GET['id'],
1277
            'author_user_id' => api_get_user_id(),
1278
            'feedback' => $_POST['feedback'],
1279
            'feedback_date' => api_get_utc_datetime(),
1280
        ];
1281
1282
        $id = Database::insert(Database::get_course_table(TABLE_DROPBOX_FEEDBACK), $params);
1283
        if ($id) {
1284
            $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_FEEDBACK)." 
1285
                    SET feedback_id = iid WHERE iid = $id";
1286
            Database::query($sql);
1287
        }
1288
1289
        return get_lang('DropboxFeedbackStored');
1290
    }
1291
}
1292
1293
/**
1294
 * This function downloads all the files of the input array into one zip.
1295
 *
1296
 * @param array $fileList containing all the ids of the files that have to be downloaded
1297
 *
1298
 * @author Patrick Cool <[email protected]>, Ghent University
1299
 *
1300
 * @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
1301
 * @todo integrate some cleanup function that removes zip files that are older than 2 days
1302
 *
1303
 * @author Patrick Cool <[email protected]>, Ghent University
1304
 * @author Julio Montoya  Addin c_id support
1305
 *
1306
 * @version march 2006
1307
 */
1308
function zip_download($fileList)
1309
{
1310
    $_course = api_get_course_info();
1311
    $course_id = api_get_course_int_id();
1312
    $fileList = array_map('intval', $fileList);
1313
1314
    // note: we also have to add the check if the user has received or sent this file.
1315
    $sql = "SELECT DISTINCT file.filename, file.title, file.author, file.description
1316
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." file
1317
            INNER JOIN ".Database::get_course_table(TABLE_DROPBOX_PERSON)." person
1318
            ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
1319
            INNER JOIN ".Database::get_course_table(TABLE_DROPBOX_POST)." post
1320
            ON (post.file_id = file.id AND post.c_id = $course_id AND file.c_id = $course_id)
1321
            WHERE
1322
                file.id IN (".implode(', ', $fileList).") AND
1323
                file.id = person.file_id AND
1324
                (
1325
                    person.user_id = '".api_get_user_id()."' OR
1326
                    post.dest_user_id = '".api_get_user_id()."'
1327
                ) ";
1328
    $result = Database::query($sql);
1329
1330
    $files = [];
1331
    while ($row = Database::fetch_array($result)) {
1332
        $files[$row['filename']] = [
1333
            'filename' => $row['filename'],
1334
            'title' => $row['title'],
1335
            'author' => $row['author'],
1336
            'description' => $row['description'],
1337
        ];
1338
    }
1339
1340
    // Step 3: create the zip file and add all the files to it
1341
    $temp_zip_file = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
1342
    Session::write('dropbox_files_to_download', $files);
1343
    $zip = new PclZip($temp_zip_file);
1344
    foreach ($files as $value) {
1345
        $zip->add(
1346
            api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'],
1347
            PCLZIP_OPT_REMOVE_ALL_PATH,
1348
            PCLZIP_CB_PRE_ADD,
1349
            'my_pre_add_callback'
1350
        );
1351
    }
1352
    Session::erase('dropbox_files_to_download');
1353
    $name = 'dropbox-'.api_get_utc_datetime().'.zip';
1354
    $result = DocumentManager::file_send_for_download($temp_zip_file, true, $name);
1355
    if ($result === false) {
1356
        api_not_allowed(true);
1357
    }
1358
    @unlink($temp_zip_file);
1359
    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...
1360
}
1361
1362
/**
1363
 * This is a callback function to decrypt the files in the zip file
1364
 * to their normal filename (as stored in the database).
1365
 *
1366
 * @param array $p_event  a variable of PCLZip
1367
 * @param array $p_header a variable of PCLZip
1368
 *
1369
 * @author Patrick Cool <[email protected]>, Ghent University
1370
 *
1371
 * @version march 2006
1372
 */
1373
function my_pre_add_callback($p_event, &$p_header)
1374
{
1375
    $files = Session::read('dropbox_files_to_download');
1376
    $p_header['stored_filename'] = $files[$p_header['stored_filename']]['title'];
1377
1378
    return 1;
1379
}
1380
1381
/**
1382
 * @desc Generates the contents of a html file that gives an overview of all the files in the zip file.
1383
 *       This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
1384
 *
1385
 * @author Patrick Cool <[email protected]>, Ghent University, March 2006
1386
 * @author Ivan Tcholakov, 2010, code for html metadata has been added.
1387
 */
1388
function generate_html_overview($files, $dont_show_columns = [], $make_link = [])
1389
{
1390
    $return = '<!DOCTYPE html'."\n";
1391
    $return .= "\t".'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'."\n";
1392
    $return .= "\t".'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
1393
    $return .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.api_get_language_isocode().'" lang="'.api_get_language_isocode().'">'."\n";
1394
1395
    $return .= "<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n";
1396
    $return .= "\t".'<meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />'."\n";
1397
    $return .= "</head>\n\n";
1398
    $return .= '<body dir="'.api_get_text_direction().'">'."\n\n";
1399
    $return .= "<table border=\"1px\">\n";
1400
1401
    $counter = 0;
1402
    foreach ($files as $value) {
1403
        // Adding the header.
1404
        if ($counter == 0) {
1405
            $columns_array = array_keys($value);
1406
            $return .= "\n<tr>";
1407
            foreach ($columns_array as $columns_array_key => $columns_array_value) {
1408
                if (!in_array($columns_array_value, $dont_show_columns)) {
1409
                    $return .= "\n\t<th>".$columns_array_value."</th>";
1410
                }
1411
                $column[] = $columns_array_value;
1412
            }
1413
            $return .= "\n</tr>\n";
1414
        }
1415
        $counter++;
1416
1417
        // Adding the content.
1418
        $return .= "\n<tr>";
1419
        foreach ($column as $column_key => $column_value) {
1420
            if (!in_array($column_value, $dont_show_columns)) {
1421
                $return .= "\n\t<td>";
1422
                if (in_array($column_value, $make_link)) {
1423
                    $return .= '<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
1424
                } else {
1425
                    $return .= $value[$column_value];
1426
                }
1427
                $return .= "</td>";
1428
            }
1429
        }
1430
        $return .= "\n</tr>\n";
1431
    }
1432
    $return .= "\n</table>\n\n</body>";
1433
    $return .= "\n</html>";
1434
1435
    return $return;
1436
}
1437
1438
/**
1439
 * @desc This function retrieves the number of feedback messages on every
1440
 * document. This function might become obsolete when
1441
 *       the feedback becomes user individual.
1442
 *
1443
 * @author Patrick Cool <[email protected]>, Ghent University
1444
 *
1445
 * @version march 2006
1446
 */
1447
function get_total_number_feedback()
1448
{
1449
    $course_id = api_get_course_int_id();
1450
    $sql = "SELECT COUNT(feedback_id) AS total, file_id
1451
            FROM ".Database::get_course_table(TABLE_DROPBOX_FEEDBACK)."
1452
            WHERE c_id = $course_id 
1453
            GROUP BY file_id";
1454
    $result = Database::query($sql);
1455
    $return = [];
1456
    while ($row = Database::fetch_array($result)) {
1457
        $return[$row['file_id']] = $row['total'];
1458
    }
1459
1460
    return $return;
1461
}
1462
1463
/**
1464
 * @desc this function checks if the key exists. If this is the case
1465
 * it returns the value, if not it returns 0
1466
 *
1467
 * @author Patrick Cool <[email protected]>, Ghent University
1468
 *
1469
 * @version march 2006
1470
 */
1471
function check_number_feedback($key, $array)
1472
{
1473
    if (is_array($array)) {
1474
        if (array_key_exists($key, $array)) {
1475
            return $array[$key];
1476
        } else {
1477
            return 0;
1478
        }
1479
    } else {
1480
        return 0;
1481
    }
1482
}
1483
1484
/**
1485
 * Get the last access to a given tool of a given user.
1486
 *
1487
 * @param $tool string the tool constant
1488
 * @param $courseId the course_id
1489
 * @param $user_id the id of the user
1490
 *
1491
 * @return string last tool access date
1492
 *
1493
 * @author Patrick Cool <[email protected]>, Ghent University
1494
 *
1495
 * @version march 2006
1496
 *
1497
 * @todo consider moving this function to a more appropriate place.
1498
 */
1499
function get_last_tool_access($tool, $courseId = null, $user_id = null)
1500
{
1501
    // The default values of the parameters
1502
    if (empty($courseId)) {
1503
        $courseId = api_get_course_int_id();
1504
    }
1505
    if (empty($user_id)) {
1506
        $user_id = api_get_user_id();
1507
    }
1508
1509
    // the table where the last tool access is stored (=track_e_lastaccess)
1510
    $table_last_access = Database::get_main_table('track_e_lastaccess');
1511
1512
    $sql = "SELECT access_date FROM $table_last_access
1513
            WHERE
1514
                access_user_id = ".intval($user_id)." AND
1515
                c_id='".intval($courseId)."' AND
1516
                access_tool='".Database::escape_string($tool)."'
1517
                ORDER BY access_date DESC
1518
                LIMIT 1";
1519
    $result = Database::query($sql);
1520
    $row = Database::fetch_array($result);
1521
1522
    return $row['access_date'];
1523
}
1524
/**
1525
 * Previously $dropbox_cnf['mailingIdBase'], returns a mailing ID to generate a mail ID.
1526
 *
1527
 * @return int
1528
 */
1529
function get_mail_id_base()
1530
{
1531
    // false = no mailing functionality
1532
    //$dropbox_cnf['mailingIdBase'] = 10000000;  // bigger than any user_id,
1533
    // allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
1534
    // mailing pseudo_id = dropbox_cnf('mailingIdBase') + mailing id
1535
    return 10000000;
1536
}
1537