Passed
Push — 1.11.x ( 31fff3...86e7ae )
by Yannick
15:37 queued 10s
created

main/dropbox/dropbox_functions.inc.php (1 issue)

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