Issues (2037)

main/dropbox/dropbox_functions.inc.php (2 issues)

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, $action = 'add')
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
    $langFormHeader = ('send_other_users' == $action ? get_lang('SendFileToOtherUsers') : get_lang('UploadNewFile'));
539
    $form->addElement('header', $langFormHeader);
540
    $form->addElement('hidden', 'sec_token', $token);
541
    $form->addElement('hidden', 'origin', $origin);
542
    if ('add' == $action) {
543
        $maxFileSize = getIniMaxFileSizeInBytes();
544
        $form->addElement('hidden', 'MAX_FILE_SIZE', $maxFileSize);
545
        $form->addElement(
546
            'file',
547
            'file',
548
            get_lang('UploadFile'),
549
            ['onChange' => 'javascript: checkfile(this.value);']
550
        );
551
552
        $allowOverwrite = api_get_setting('dropbox_allow_overwrite');
553
        if ($allowOverwrite == 'true' && empty($idCondition)) {
554
            $form->addElement(
555
                'checkbox',
556
                'cb_overwrite',
557
                null,
558
                get_lang('OverwriteFile'),
559
                ['id' => 'cb_overwrite']
560
            );
561
        }
562
    }
563
564
    // List of all users in this course and all virtual courses combined with it
565
    if (api_get_session_id()) {
566
        $complete_user_list_for_dropbox = [];
567
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
568
            $complete_user_list_for_dropbox = CourseManager::get_user_list_from_course_code(
569
                $course_info['code'],
570
                api_get_session_id(),
571
                null,
572
                null,
573
                0,
574
                false,
575
                false,
576
                false,
577
                [],
578
                [],
579
                [],
580
                true
581
            );
582
        }
583
584
        $complete_user_list2 = CourseManager::get_coach_list_from_course_code(
585
            $course_info['code'],
586
            api_get_session_id()
587
        );
588
589
        $generalCoachList = [];
590
        $courseCoachList = [];
591
        foreach ($complete_user_list2 as $coach) {
592
            if ($coach['type'] == 'general_coach') {
593
                $generalCoachList[] = $coach;
594
            } else {
595
                $courseCoachList[] = $coach;
596
            }
597
        }
598
599
        $hideCourseCoach = api_get_setting('dropbox_hide_course_coach');
600
        if ($hideCourseCoach == 'false') {
601
            $complete_user_list_for_dropbox = array_merge(
602
                $complete_user_list_for_dropbox,
603
                $courseCoachList
604
            );
605
        }
606
        $hideGeneralCoach = api_get_setting('dropbox_hide_general_coach');
607
608
        if ($hideGeneralCoach == 'false') {
609
            $complete_user_list_for_dropbox = array_merge(
610
                $complete_user_list_for_dropbox,
611
                $generalCoachList
612
            );
613
        }
614
    } else {
615
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
616
            $complete_user_list_for_dropbox = CourseManager::get_user_list_from_course_code(
617
                $course_info['code'],
618
                api_get_session_id(),
619
                null,
620
                null,
621
                null,
622
                false,
623
                false,
624
                false,
625
                [],
626
                [],
627
                [],
628
                true
629
            );
630
        } else {
631
            $complete_user_list_for_dropbox = CourseManager::get_teacher_list_from_course_code(
632
                $course_info['code'],
633
                false
634
            );
635
        }
636
    }
637
638
    if (!empty($complete_user_list_for_dropbox)) {
639
        foreach ($complete_user_list_for_dropbox as $k => $e) {
640
            $complete_user_list_for_dropbox[$k] = $e + [
641
                'lastcommafirst' => api_get_person_name(
642
                    $e['firstname'],
643
                    $e['lastname']
644
                ),
645
            ];
646
        }
647
        $complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
648
    }
649
650
    /*
651
        Create the options inside the select box:
652
        List all selected users their user id as value and a name string as display
653
    */
654
    $current_user_id = '';
655
    $allowStudentToStudent = api_get_setting('dropbox_allow_student_to_student');
656
    $options = [];
657
    $userGroup = new UserGroup();
658
    foreach ($complete_user_list_for_dropbox as $current_user) {
659
        if ((
660
            $dropbox_person->isCourseTutor
661
                || $dropbox_person->isCourseAdmin
662
                || $allowStudentToStudent == 'true'
663
                || $current_user['status'] != 5                         // Always allow teachers.
664
                || $current_user['is_tutor'] == 1                       // Always allow tutors.
665
                ) && $current_user['user_id'] != $_user['user_id']) {   // Don't include yourself.
666
            if ($current_user['user_id'] == $current_user_id) {
667
                continue;
668
            }
669
            $userId = $current_user['user_id'];
670
            $userInfo = api_get_user_info($userId);
671
            if ($userInfo['status'] != INVITEE) {
672
                $groupNameListToString = '';
673
                if (!empty($groups)) {
674
                    $groupNameList = array_column($groups, 'name');
675
                    $groupNameListToString = ' - ['.implode(', ', $groupNameList).']';
676
                }
677
                $groups = $userGroup->getUserGroupListByUser($userId);
678
679
                $full_name = $userInfo['complete_name'].$groupNameListToString;
680
                $current_user_id = $current_user['user_id'];
681
                $options['user_'.$current_user_id] = $full_name;
682
            }
683
        }
684
    }
685
686
    /*
687
    * Show groups
688
    */
689
    $allowGroups = api_get_setting('dropbox_allow_group');
690
    if (($dropbox_person->isCourseTutor || $dropbox_person->isCourseAdmin)
691
        && $allowGroups == 'true' || $allowStudentToStudent == 'true'
692
    ) {
693
        $complete_group_list_for_dropbox = GroupManager::get_group_list(null, $course_info);
694
695
        if (count($complete_group_list_for_dropbox) > 0) {
696
            foreach ($complete_group_list_for_dropbox as $current_group) {
697
                if ($current_group['number_of_members'] > 0) {
698
                    $options['group_'.$current_group['id']] = 'G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users');
699
                }
700
            }
701
        }
702
    }
703
704
    if ('add' == $action) {
705
        $allowUpload = api_get_setting('dropbox_allow_just_upload');
706
        if ($allowUpload == 'true') {
707
            $options['user_'.$_user['user_id']] = get_lang('JustUploadInSelect');
708
        }
709
710
        if (empty($idCondition)) {
711
            $form->addSelect(
712
                'recipients',
713
                get_lang('SendTo'),
714
                $options,
715
                [
716
                    'multiple' => 'multiple',
717
                    'size' => '10',
718
                ]
719
            );
720
        }
721
        $form->addButtonUpload(get_lang('Upload'), 'submitWork');
722
        $headers = [
723
            get_lang('Upload'),
724
            get_lang('Upload').' ('.get_lang('Simple').')',
725
        ];
726
        $multipleForm = new FormValidator(
727
            'sent_multiple',
728
            'post',
729
            '#',
730
            null,
731
            ['enctype' => 'multipart/form-data', 'id' => 'fileupload']
732
        );
733
734
        if (empty($idCondition)) {
735
            $multipleForm->addSelect(
736
                'recipients',
737
                get_lang('SendTo'),
738
                $options,
739
                [
740
                    'multiple' => 'multiple',
741
                    'size' => '10',
742
                    'id' => 'recipient_form',
743
                ]
744
            );
745
        }
746
747
        $url = api_get_path(WEB_AJAX_PATH).'dropbox.ajax.php?'.api_get_cidreq().'&a=upload_file&'.$idCondition;
748
        if (empty($idCondition)) {
749
            $multipleForm->addHtml('<div id="multiple_form" style="display:none">');
750
        }
751
        $multipleForm->addMultipleUpload($url);
752
        if (empty($idCondition)) {
753
            $multipleForm->addHtml('</div>');
754
        }
755
756
        echo Display::tabs(
757
            $headers,
758
            [$multipleForm->returnForm(), $form->returnForm()],
759
            'tabs'
760
        );
761
    } else {
762
        $tblDropboxPerson = Database::get_course_table(TABLE_DROPBOX_PERSON);
763
        $tblDropboxFile = Database::get_course_table(TABLE_DROPBOX_FILE);
764
        $courseId = api_get_course_int_id();
765
        $optionsDpUsers = [];
766
        $current_user_id = api_get_user_id();
767
768
        $sql = "SELECT user_id
769
                FROM $tblDropboxPerson
770
                WHERE
771
                    c_id = $courseId AND
772
                    file_id = $id AND user_id != $current_user_id";
773
        $rs = Database::query($sql);
774
        if (Database::num_rows($rs) > 0) {
775
            while ($row = Database::fetch_array($rs)) {
776
                $dpUserId = $row['user_id'];
777
                $dpUser = api_get_user_info($dpUserId);
778
                $optionsDpUsers['user_'.$dpUserId] = $dpUser['complete_name'];
779
                if (isset($options['user_'.$dpUserId])) {
780
                    unset($options['user_'.$dpUserId]);
781
                }
782
            }
783
        }
784
785
        $form->addSelect(
786
            'recipients',
787
            get_lang('SendTo'),
788
            $options,
789
            [
790
                'multiple' => 'multiple',
791
                'size' => '10',
792
            ]
793
        );
794
795
        $formRemove = new FormValidator('sent_remove', 'post');
796
        $formRemove->addElement('header', get_lang('RemoveFileFromSelectedUsers'));
797
        $formRemove->addSelect(
798
            'recipients',
799
            get_lang('Remove'),
800
            $optionsDpUsers,
801
            [
802
                'multiple' => 'multiple',
803
                'size' => '10',
804
            ]
805
        );
806
807
        // Current file information.
808
        $sql = "SELECT title, filesize
809
                FROM $tblDropboxFile
810
                WHERE
811
                    c_id = $courseId AND
812
                    iid = $id";
813
        $rs = Database::query($sql);
814
        $dropboxFile = Database::fetch_array($rs);
815
        if (!empty($dropboxFile)) {
816
            $icon = DocumentManager::build_document_icon_tag('file', $dropboxFile['title']);
817
            $filesize = format_file_size($dropboxFile['filesize']);
818
            $labelFile = "$icon {$dropboxFile['title']} ($filesize)";
819
            $form->addLabel(get_lang('File'), $labelFile);
820
            $formRemove->addLabel(get_lang('File'), $labelFile);
821
        }
822
        $form->addElement('hidden', 'file_id', $id);
823
        $form->addElement('hidden', 'action', $action);
824
        $form->addElement('hidden', 'option', 'add_users');
825
        $form->addButtonUpload(get_lang('SendToUsers'), 'submitWork');
826
        $formRemove->addElement('hidden', 'sec_token', $token);
827
        $formRemove->addElement('hidden', 'origin', $origin);
828
        $formRemove->addElement('hidden', 'file_id', $id);
829
        $formRemove->addElement('hidden', 'action', $action);
830
        $formRemove->addElement('hidden', 'option', 'remove_users');
831
        $formRemove->addButtonUpload(get_lang('RemoveUsers'), 'submitWork');
832
833
        echo Display::tabs(
834
            [get_lang('AddUsers'), get_lang('RemoveUsers')],
835
            [$form->returnForm(), $formRemove->returnForm()],
836
            'tabs'
837
        );
838
    }
839
}
840
841
/**
842
 * Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
843
 * If there are, all entries concerning the file are deleted from the db + the file is deleted from the server.
844
 */
845
function removeUnusedFiles(int $courseId = 0, int $sessionId = 0)
846
{
847
    if (empty($courseId)) {
848
        $courseId = api_get_course_int_id();
849
    }
850
    $_course = api_get_course_info_by_id($courseId);
851
    if (empty($sessionId)) {
852
        $sessionId = api_get_session_id();
853
    }
854
    $condition_session = api_get_session_condition($sessionId, true, false, 'f.session_id');
855
856
    // select all files that aren't referenced anymore
857
    $sql = "SELECT DISTINCT f.iid, f.filename
858
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." f
859
            LEFT JOIN ".Database::get_course_table(TABLE_DROPBOX_PERSON)." p
860
            ON (f.iid = p.file_id)
861
            WHERE p.user_id IS NULL AND
862
                  f.c_id = $courseId
863
                  $condition_session
864
            ";
865
    $result = Database::query($sql);
866
    $condition_session = api_get_session_condition($sessionId);
867
    while ($res = Database::fetch_array($result)) {
868
        //delete the selected files from the post and file tables
869
        $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
870
                WHERE c_id = $courseId $condition_session AND file_id = ".$res['iid'];
871
        Database::query($sql);
872
        $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)."
873
                WHERE iid = ".$res['iid'];
874
        Database::query($sql);
875
        //delete file from server
876
        @unlink(api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$res['filename']);
877
    }
878
}
879
880
/**
881
 * Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
882
 * and is only visible to its uploader (user_id).
883
 *
884
 * Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
885
 * and are visible initially to recipient and pseudo_id.
886
 *
887
 * @author René Haentjens, Ghent University
888
 *
889
 * @todo check if this function is still necessary.
890
 */
891
function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
892
{
893
    $course_id = api_get_course_int_id();
894
895
    $mailingPseudoId = (int) $mailingPseudoId;
896
    $sql = "SELECT f.uploader_id
897
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." f
898
            LEFT JOIN ".Database::get_course_table(TABLE_DROPBOX_POST)." p
899
            ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
900
            WHERE
901
                p.dest_user_id = '".$mailingPseudoId."' AND
902
                p.c_id = $course_id
903
            ";
904
    $result = Database::query($sql);
905
906
    if (!($res = Database::fetch_array($result))) {
907
        exit(get_lang('GeneralError').' (code 901)');
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...
908
    }
909
    if ($owner == 0) {
910
        return $res['uploader_id'];
911
    }
912
    if ($res['uploader_id'] == $owner) {
913
        return true;
914
    }
915
    exit(get_lang('GeneralError').' (code '.$or_die.')');
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...
916
}
917
918
/**
919
 * @author René Haentjens, Ghent University
920
 *
921
 * @todo check if this function is still necessary.
922
 */
923
function removeMoreIfMailing(int $file_id, int $courseId = 0, int $sessionId = 0, int $uploaderId = 0)
924
{
925
    if (empty($courseId)) {
926
        $courseId = api_get_course_int_id();
927
    }
928
    if (empty($sessionId)) {
929
        $sessionId = api_get_session_id();
930
    }
931
    $condition_session = api_get_session_condition($sessionId);
932
    if (empty($uploaderId)) {
933
        $uploaderId = api_get_user_id();
934
    }
935
    // when deleting a mailing zip-file (posted to mailingPseudoId):
936
    // 1. the detail window is no longer reachable, so
937
    //    for all content files, delete mailingPseudoId from person-table
938
    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
939
    //    for all content files, replace mailingPseudoId by owner as uploader
940
    $sql = "SELECT p.dest_user_id
941
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)." p
942
            WHERE c_id = $courseId $condition_session AND p.file_id = $file_id";
943
    $result = Database::query($sql);
944
945
    if ($res = Database::fetch_array($result)) {
946
        $mailingPseudoId = $res['dest_user_id'];
947
        $mailId = get_mail_id_base();
948
        if ($mailingPseudoId > $mailId) {
949
            $sql = "DELETE FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
950
                    WHERE c_id = $courseId AND user_id = $mailingPseudoId";
951
            Database::query($sql);
952
953
            $sql = "UPDATE ".Database::get_course_table(TABLE_DROPBOX_FILE)."
954
                    SET uploader_id = $uploaderId
955
                    WHERE c_id = $courseId $condition_session AND uploader_id = $mailingPseudoId";
956
            Database::query($sql);
957
        }
958
    }
959
}
960
961
/**
962
 * @param array            $file
963
 * @param Dropbox_SentWork $work
964
 *
965
 * @return array|string|null
966
 */
967
function store_add_dropbox($file = [], $work = null)
968
{
969
    $_course = api_get_course_info();
970
    $_user = api_get_user_info();
971
972
    if (empty($file)) {
973
        $file = isset($_FILES['file']) ? $_FILES['file'] : null;
974
    }
975
976
    if (empty($work)) {
977
        // Validating the form data
978
        // there are no recipients selected
979
        if (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
980
            return get_lang('YouMustSelectAtLeastOneDestinee');
981
        } else {
982
            // Check if all the recipients are valid
983
            $thisIsAMailing = false;
984
            $thisIsJustUpload = false;
985
986
            foreach ($_POST['recipients'] as $rec) {
987
                if ($rec == 'mailing') {
988
                    $thisIsAMailing = true;
989
                } elseif ($rec == 'upload') {
990
                    $thisIsJustUpload = true;
991
                } elseif (strpos($rec, 'user_') === 0 &&
992
                    !CourseManager::is_user_subscribed_in_course(
993
                        substr($rec, strlen('user_')),
994
                        $_course['code'],
995
                        true
996
                    )
997
                ) {
998
                    Display::addFlash(
999
                        Display::return_message(
1000
                            get_lang('InvalideUserDetected'),
1001
                            'warning'
1002
                        )
1003
                    );
1004
1005
                    return false;
1006
                } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
1007
                    Display::addFlash(
1008
                        Display::return_message(
1009
                            get_lang('InvalideGroupDetected'),
1010
                            'warning'
1011
                        )
1012
                    );
1013
1014
                    return false;
1015
                }
1016
            }
1017
        }
1018
1019
        // we are doing a mailing but an additional recipient is selected
1020
        if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
1021
            Display::addFlash(
1022
                Display::return_message(
1023
                    get_lang('MailingSelectNoOther'),
1024
                    'warning'
1025
                )
1026
            );
1027
1028
            return false;
1029
        }
1030
1031
        // we are doing a just upload but an additional recipient is selected.
1032
        // note: why can't this be valid? It is like sending a document to
1033
        // yourself AND to a different person (I do this quite often with my e-mails)
1034
        if ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
1035
            Display::addFlash(
1036
                Display::return_message(
1037
                    get_lang('MailingJustUploadSelectNoOther'),
1038
                    'warning'
1039
                )
1040
            );
1041
1042
            return false;
1043
        }
1044
    }
1045
1046
    $fileId = 0;
1047
    $sendToOtherUsers = false;
1048
    if ((isset($_POST['action']) && 'send_other_users' == $_POST['action']) && isset($_POST['file_id'])) {
1049
        $fileId = (int) $_POST['file_id'];
1050
        $sendToOtherUsers = true;
1051
    }
1052
1053
    if (!$sendToOtherUsers) {
1054
        if (empty($file['name'])) {
1055
            Display::addFlash(Display::return_message(get_lang('NoFileSpecified'), 'warning'));
1056
1057
            return false;
1058
        }
1059
1060
        // are we overwriting a previous file or sending a new one
1061
        $dropbox_overwrite = false;
1062
        if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
1063
            $dropbox_overwrite = true;
1064
        }
1065
1066
        // doing the upload
1067
        $dropbox_filename = $file['name'];
1068
        $dropbox_filesize = $file['size'];
1069
        $dropbox_filetype = $file['type'];
1070
        $dropbox_filetmpname = $file['tmp_name'];
1071
1072
        // check if the filesize does not exceed the allowed size.
1073
        $maxFileSize = getIniMaxFileSizeInBytes();
1074
        if ($dropbox_filesize <= 0 || $dropbox_filesize > $maxFileSize) {
1075
            Display::addFlash(Display::return_message(get_lang('DropboxFileTooBig'), 'warning'));
1076
1077
            return false;
1078
        }
1079
1080
        // check if the file is actually uploaded
1081
        if (!isset($file['copy_file']) && !is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
1082
            Display::addFlash(Display::return_message(get_lang('TheFileIsNotUploaded'), 'warning'));
1083
1084
            return false;
1085
        }
1086
1087
        $upload_ok = process_uploaded_file($file, true);
1088
1089
        if (!$upload_ok) {
1090
            return null;
1091
        }
1092
1093
        // Try to add an extension to the file if it hasn't got one
1094
        $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
1095
        // Replace dangerous characters
1096
        $dropbox_filename = api_replace_dangerous_char($dropbox_filename);
1097
        // Transform any .php file in .phps fo security
1098
        $dropbox_filename = php2phps($dropbox_filename);
1099
1100
        //filter extension
1101
        if (!filter_extension($dropbox_filename)) {
1102
            Display::addFlash(
1103
                Display::return_message(
1104
                    get_lang('UplUnableToSaveFileFilteredExtension'),
1105
                    'warning'
1106
                )
1107
            );
1108
1109
            return false;
1110
        }
1111
1112
        // set title
1113
        $dropbox_title = $dropbox_filename;
1114
        // note: I think we could better migrate everything from here on to
1115
        // separate functions: store_new_dropbox, store_new_mailing, store_just_upload
1116
        if ($dropbox_overwrite && empty($work)) {
1117
            $dropbox_person = new Dropbox_Person(
1118
                $_user['user_id'],
1119
                api_is_course_admin(),
1120
                api_is_course_tutor()
1121
            );
1122
            $mailId = get_mail_id_base();
1123
            foreach ($dropbox_person->sentWork as $w) {
1124
                if ($w->title == $dropbox_filename) {
1125
                    if (($w->recipients[0]['id'] > $mailId) xor $thisIsAMailing) {
1126
                        Display::addFlash(Display::return_message(get_lang('MailingNonMailingError'), 'warning'));
1127
1128
                        return false;
1129
                    }
1130
                    if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
1131
                        Display::addFlash(Display::return_message(get_lang('MailingJustUploadSelectNoOther'), 'warning'));
1132
1133
                        return false;
1134
                    }
1135
                    $dropbox_filename = $w->filename;
1136
                    $found = true; // note: do we still need this?
1137
                    break;
1138
                }
1139
            }
1140
        } else {  // rename file to login_filename_uniqueId format
1141
            $dropbox_filename = $_user['username']."_".$dropbox_filename."_".uniqid('');
1142
        }
1143
1144
        if (isset($file['copy_file']) && $file['copy_file']) {
1145
            @copy($dropbox_filetmpname, api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$dropbox_filename);
1146
            @unlink($dropbox_filetmpname);
1147
        } else {
1148
            @move_uploaded_file(
1149
                $dropbox_filetmpname,
1150
                api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$dropbox_filename
1151
            );
1152
        }
1153
    }
1154
1155
    if (empty($work)) {
1156
        // creating the array that contains all the users who will receive the file
1157
        $new_work_recipients = [];
1158
        foreach ($_POST['recipients'] as $rec) {
1159
            if (strpos($rec, 'user_') === 0) {
1160
                $new_work_recipients[] = substr($rec, strlen('user_'));
1161
            } elseif (strpos($rec, 'group_') === 0) {
1162
                $groupInfo = GroupManager::get_group_properties(substr($rec, strlen('group_')));
1163
                $userList = GroupManager::get_subscribed_users($groupInfo);
1164
                foreach ($userList as $usr) {
1165
                    if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) {
1166
                        $new_work_recipients[] = $usr['user_id'];
1167
                    }
1168
                }
1169
            }
1170
        }
1171
1172
        $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox');
1173
        if ($b_send_mail) {
1174
            foreach ($new_work_recipients as $recipient_id) {
1175
                $recipent_temp = api_get_user_info($recipient_id);
1176
                $additionalParameters = [
1177
                    'smsType' => SmsPlugin::NEW_FILE_SHARED_COURSE_BY,
1178
                    'userId' => $recipient_id,
1179
                    'courseTitle' => $_course['title'],
1180
                    'userUsername' => $recipent_temp['username'],
1181
                ];
1182
1183
                $message = get_lang('NewDropboxFileUploadedContent').
1184
                    ' <a href="'.api_get_path(WEB_CODE_PATH).'dropbox/index.php?'.api_get_cidreq().'">'.get_lang('SeeFile').'</a>'.
1185
                    "\n\n".
1186
                    api_get_person_name(
1187
                        $_user['firstName'],
1188
                        $_user['lastName'],
1189
                        null,
1190
                        PERSON_NAME_EMAIL_ADDRESS
1191
                    )."\n".get_lang('Email')." : ".$_user['mail'];
1192
1193
                MessageManager::send_message_simple(
1194
                    $recipient_id,
1195
                    get_lang('NewDropboxFileUploaded'),
1196
                    $message,
1197
                    $_user['user_id'],
1198
                    false,
1199
                    false,
1200
                    $additionalParameters
1201
                );
1202
            }
1203
        }
1204
    }
1205
1206
    $successMessage = get_lang('FileUploadSucces');
1207
    if ($sendToOtherUsers) {
1208
        $result = true;
1209
        if ('remove_users' == $_POST['option']) {
1210
            foreach ($new_work_recipients as $userId) {
1211
                removeUserDropboxFile($fileId, $userId);
1212
            }
1213
            $successMessage = get_lang('FileRemovedFromSelectedUsers');
1214
        } else {
1215
            foreach ($new_work_recipients as $userId) {
1216
                addDropBoxFileToUser($fileId, $userId);
1217
            }
1218
        }
1219
    } else {
1220
        if (empty($work)) {
1221
            // Create new
1222
            $result = new Dropbox_SentWork(
1223
                $_user['user_id'],
1224
                $dropbox_title,
1225
                isset($_POST['description']) ? $_POST['description'] : '',
1226
                api_get_user_id(),
1227
                $dropbox_filename,
1228
                $dropbox_filesize,
1229
                $new_work_recipients
1230
            );
1231
        } else {
1232
            // Update
1233
            $work->title = $dropbox_title;
1234
            $work->filename = $dropbox_filename;
1235
            $work->filesize = $dropbox_filesize;
1236
            $work->upload_date = api_get_utc_datetime();
1237
            $work->last_upload_date = api_get_utc_datetime();
1238
            $work->description = isset($_POST['description']) ? $_POST['description'] : '';
1239
            $work->uploader_id = api_get_user_id();
1240
            $work->updateFile();
1241
            $result = $work;
1242
        }
1243
    }
1244
1245
    Security::clear_token();
1246
    Display::addFlash(Display::return_message($successMessage));
1247
1248
    return $result;
1249
}
1250
1251
/**
1252
 * It removes a dropbox file of a selected user.
1253
 *
1254
 * @param $fileId
1255
 * @param $userId
1256
 */
1257
function removeUserDropboxFile($fileId, $userId)
1258
{
1259
    $tblDropboxPerson = Database::get_course_table(TABLE_DROPBOX_PERSON);
1260
    $tblDropboxPost = Database::get_course_table(TABLE_DROPBOX_POST);
1261
    $courseId = api_get_course_int_id();
1262
    $sessionId = api_get_session_id();
1263
1264
    $params = [$courseId, $fileId, $userId];
1265
    $result = Database::delete(
1266
        $tblDropboxPerson,
1267
        ['c_id = ? AND file_id = ? AND user_id = ?' => $params]
1268
    );
1269
1270
    $params = [$courseId, $fileId, $userId, $sessionId];
1271
    $result = Database::delete(
1272
        $tblDropboxPost,
1273
        ['c_id = ? AND file_id = ? AND dest_user_id = ? AND session_id = ?' => $params]
1274
    );
1275
}
1276
1277
/**
1278
 * It sends a file to a selected user.
1279
 *
1280
 * @param $fileId
1281
 * @param $userId
1282
 */
1283
function addDropBoxFileToUser($fileId, $userId)
1284
{
1285
    $tblDropboxPerson = Database::get_course_table(TABLE_DROPBOX_PERSON);
1286
    $tblDropboxPost = Database::get_course_table(TABLE_DROPBOX_POST);
1287
    $courseId = api_get_course_int_id();
1288
    $sessionId = api_get_session_id();
1289
1290
    $sql = "SELECT count(file_id) as count
1291
                        FROM $tblDropboxPerson
1292
                        WHERE c_id = $courseId AND file_id = $fileId AND user_id = $userId";
1293
    $rs = Database::query($sql);
1294
    $row = Database::fetch_array($rs);
1295
    if (0 == $row['count']) {
1296
        $params = [
1297
            'c_id' => $courseId,
1298
            'file_id' => $fileId,
1299
            'user_id' => $userId,
1300
        ];
1301
        Database::insert($tblDropboxPerson, $params);
1302
    }
1303
1304
    $sql = "SELECT count(file_id) as count
1305
                        FROM $tblDropboxPost
1306
                        WHERE c_id = $courseId AND file_id = $fileId AND dest_user_id = $userId AND session_id = $sessionId";
1307
    $rs = Database::query($sql);
1308
    $row = Database::fetch_array($rs);
1309
    if (0 == $row['count']) {
1310
        $params = [
1311
            'c_id' => $courseId,
1312
            'file_id' => $fileId,
1313
            'dest_user_id' => $userId,
1314
            'session_id' => $sessionId,
1315
            'feedback_date' => api_get_utc_datetime(),
1316
            'cat_id' => 0,
1317
        ];
1318
        Database::insert($tblDropboxPost, $params);
1319
    }
1320
1321
    // Update item_property table for each recipient
1322
    api_item_property_update(
1323
        api_get_course_info(),
1324
        TOOL_DROPBOX,
1325
        $fileId,
1326
        'DropboxFileAdded',
1327
        api_get_user_id(),
1328
        null,
1329
        $userId
1330
    );
1331
}
1332
1333
/**
1334
 * Transforms the array containing all the feedback into something visually attractive.
1335
 *
1336
 * @param an array containing all the feedback about the given message
1337
 *
1338
 * @author Patrick Cool <[email protected]>, Ghent University
1339
 *
1340
 * @version march 2006
1341
 */
1342
function feedback($array, $url)
1343
{
1344
    $output = null;
1345
    foreach ($array as $value) {
1346
        $output .= format_feedback($value);
1347
    }
1348
    $output .= feedback_form($url);
1349
1350
    return $output;
1351
}
1352
1353
/**
1354
 * This function returns the html code to display the feedback messages on a given dropbox file.
1355
 *
1356
 * @param array $feedback an array that contains all the feedback messages about the given document
1357
 *
1358
 * @return string code
1359
 *
1360
 * @todo add the form for adding new comment (if the other party has not deleted it yet).
1361
 *
1362
 * @author Patrick Cool <[email protected]>, Ghent University
1363
 *
1364
 * @version march 2006
1365
 */
1366
function format_feedback($feedback)
1367
{
1368
    $userInfo = api_get_user_info($feedback['author_user_id']);
1369
    $output = UserManager::getUserProfileLink($userInfo);
1370
    $output .= '&nbsp;&nbsp;'.Display::dateToStringAgoAndLongDate($feedback['feedback_date']).'<br />';
1371
    $output .= '<div style="padding-top:6px">'.nl2br($feedback['feedback']).'</div><hr size="1" noshade/><br />';
1372
1373
    return $output;
1374
}
1375
1376
/**
1377
 * this function returns the code for the form for adding a new feedback message to a dropbox file.
1378
 *
1379
 * @param $url  url string
1380
 *
1381
 * @return string code
1382
 *
1383
 * @author Patrick Cool <[email protected]>, Ghent University
1384
 *
1385
 * @version march 2006
1386
 */
1387
function feedback_form($url)
1388
{
1389
    $return = '<div class="feeback-form">';
1390
    $number_users_who_see_file = check_if_file_exist($_GET['id']);
1391
    if ($number_users_who_see_file) {
1392
        $token = Security::get_token();
1393
        $return .= '<div class="form-group">';
1394
        $return .= '<input type="hidden" name="sec_token" value="'.$token.'"/>';
1395
        $return .= '<label class="col-sm-3 control-label">'.get_lang('AddNewFeedback');
1396
        $return .= '</label>';
1397
        $return .= '<div class="col-sm-6">';
1398
        $return .= '<textarea name="feedback" class="form-control" rows="4"></textarea>';
1399
        $return .= '</div>';
1400
        $return .= '<div class="col-sm-3">';
1401
        $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>';
1402
        $return .= '<button type="submit" class="btn btn-primary btn-sm" name="store_feedback" value="'.get_lang('Ok').'"
1403
                    onclick="javascript: document.form_dropbox.attributes.action.value = document.location;">'.get_lang('AddComment').'</button>';
1404
        $return .= '</div>';
1405
        $return .= '</div>';
1406
        $return .= '</div>';
1407
    } else {
1408
        $return .= get_lang('AllUsersHaveDeletedTheFileAndWillNotSeeFeedback');
1409
    }
1410
1411
    return $return;
1412
}
1413
1414
function user_can_download_file($id, $user_id)
1415
{
1416
    $course_id = api_get_course_int_id();
1417
    $id = (int) $id;
1418
    $user_id = (int) $user_id;
1419
1420
    $sql = "SELECT file_id
1421
            FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
1422
            WHERE c_id = $course_id AND user_id = $user_id AND file_id = ".$id;
1423
    $result = Database::query($sql);
1424
    $number_users_who_see_file = Database::num_rows($result);
1425
1426
    $sql = "SELECT file_id
1427
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
1428
            WHERE c_id = $course_id AND dest_user_id = $user_id AND file_id = ".$id;
1429
    $result = Database::query($sql);
1430
    $count = Database::num_rows($result);
1431
1432
    return $number_users_who_see_file > 0 || $count > 0;
1433
}
1434
1435
// we now check if the other users have not delete this document yet.
1436
// If this is the case then it is useless to see the
1437
// add feedback since the other users will never get to see the feedback.
1438
function check_if_file_exist($id)
1439
{
1440
    $id = (int) $id;
1441
    $course_id = api_get_course_int_id();
1442
    $sql = "SELECT file_id
1443
            FROM ".Database::get_course_table(TABLE_DROPBOX_PERSON)."
1444
            WHERE c_id = $course_id AND file_id = ".$id;
1445
    $result = Database::query($sql);
1446
    $number_users_who_see_file = Database::num_rows($result);
1447
1448
    $sql = "SELECT file_id
1449
            FROM ".Database::get_course_table(TABLE_DROPBOX_POST)."
1450
            WHERE c_id = $course_id AND file_id = ".$id;
1451
    $result = Database::query($sql);
1452
    $count = Database::num_rows($result);
1453
1454
    return $number_users_who_see_file > 0 || $count > 0;
1455
}
1456
1457
/**
1458
 * @return string language string (depending on the success or failure
1459
 *
1460
 * @author Patrick Cool <[email protected]>, Ghent University
1461
 *
1462
 * @version march 2006
1463
 */
1464
function store_feedback()
1465
{
1466
    if (!is_numeric($_GET['id'])) {
1467
        return get_lang('FeedbackError');
1468
    }
1469
    $course_id = api_get_course_int_id();
1470
    if (empty($_POST['feedback'])) {
1471
        return get_lang('PleaseTypeText');
1472
    } else {
1473
        $table = Database::get_course_table(TABLE_DROPBOX_FEEDBACK);
1474
        $params = [
1475
            'c_id' => $course_id,
1476
            'file_id' => $_GET['id'],
1477
            'author_user_id' => api_get_user_id(),
1478
            'feedback' => $_POST['feedback'],
1479
            'feedback_date' => api_get_utc_datetime(),
1480
            'feedback_id' => 0,
1481
        ];
1482
1483
        $id = Database::insert($table, $params);
1484
        if ($id) {
1485
            $sql = "UPDATE $table SET feedback_id = iid WHERE iid = $id";
1486
            Database::query($sql);
1487
        }
1488
1489
        return get_lang('DropboxFeedbackStored');
1490
    }
1491
}
1492
1493
/**
1494
 * This function downloads all the files of the input array into one zip.
1495
 *
1496
 * @param array $fileList containing all the ids of the files that have to be downloaded
1497
 *
1498
 * @author Patrick Cool <[email protected]>, Ghent University
1499
 *
1500
 * @todo consider removing the check if the user has received or sent this file (zip download of a folder already sufficiently checks for this).
1501
 * @todo integrate some cleanup function that removes zip files that are older than 2 days
1502
 *
1503
 * @author Patrick Cool <[email protected]>, Ghent University
1504
 * @author Julio Montoya  Addin c_id support
1505
 *
1506
 * @version march 2006
1507
 */
1508
function zip_download($fileList)
1509
{
1510
    $_course = api_get_course_info();
1511
    $course_id = api_get_course_int_id();
1512
    $fileList = array_map('intval', $fileList);
1513
1514
    // note: we also have to add the check if the user has received or sent this file.
1515
    $sql = "SELECT DISTINCT file.filename, file.title, file.author, file.description
1516
            FROM ".Database::get_course_table(TABLE_DROPBOX_FILE)." file
1517
            INNER JOIN ".Database::get_course_table(TABLE_DROPBOX_PERSON)." person
1518
            ON (person.file_id=file.id AND file.c_id = $course_id AND person.c_id = $course_id)
1519
            INNER JOIN ".Database::get_course_table(TABLE_DROPBOX_POST)." post
1520
            ON (post.file_id = file.id AND post.c_id = $course_id AND file.c_id = $course_id)
1521
            WHERE
1522
                file.id IN (".implode(', ', $fileList).") AND
1523
                file.id = person.file_id AND
1524
                (
1525
                    person.user_id = '".api_get_user_id()."' OR
1526
                    post.dest_user_id = '".api_get_user_id()."'
1527
                ) ";
1528
    $result = Database::query($sql);
1529
1530
    $files = [];
1531
    while ($row = Database::fetch_array($result)) {
1532
        $files[$row['filename']] = [
1533
            'filename' => $row['filename'],
1534
            'title' => $row['title'],
1535
            'author' => $row['author'],
1536
            'description' => $row['description'],
1537
        ];
1538
    }
1539
1540
    // Step 3: create the zip file and add all the files to it
1541
    $temp_zip_file = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
1542
    Session::write('dropbox_files_to_download', $files);
1543
    $zip = new PclZip($temp_zip_file);
1544
    foreach ($files as $value) {
1545
        $zip->add(
1546
            api_get_path(SYS_COURSE_PATH).$_course['path'].'/dropbox/'.$value['filename'],
1547
            PCLZIP_OPT_REMOVE_ALL_PATH,
1548
            PCLZIP_CB_PRE_ADD,
1549
            'my_pre_add_callback'
1550
        );
1551
    }
1552
    Session::erase('dropbox_files_to_download');
1553
    $name = 'dropbox-'.api_get_utc_datetime().'.zip';
1554
    $result = DocumentManager::file_send_for_download($temp_zip_file, true, $name);
1555
    if ($result === false) {
1556
        api_not_allowed(true);
1557
    }
1558
    @unlink($temp_zip_file);
1559
    exit;
1560
}
1561
1562
/**
1563
 * This is a callback function to decrypt the files in the zip file
1564
 * to their normal filename (as stored in the database).
1565
 *
1566
 * @param array $p_event  a variable of PCLZip
1567
 * @param array $p_header a variable of PCLZip
1568
 *
1569
 * @author Patrick Cool <[email protected]>, Ghent University
1570
 *
1571
 * @version march 2006
1572
 */
1573
function my_pre_add_callback($p_event, &$p_header)
1574
{
1575
    $files = Session::read('dropbox_files_to_download');
1576
    $p_header['stored_filename'] = $files[$p_header['stored_filename']]['title'];
1577
1578
    return 1;
1579
}
1580
1581
/**
1582
 * @desc Generates the contents of a html file that gives an overview of all the files in the zip file.
1583
 *       This is to know the information of the files that are inside the zip file (who send it, the comment, ...)
1584
 *
1585
 * @author Patrick Cool <[email protected]>, Ghent University, March 2006
1586
 * @author Ivan Tcholakov, 2010, code for html metadata has been added.
1587
 */
1588
function generate_html_overview($files, $dont_show_columns = [], $make_link = [])
1589
{
1590
    $return = '<!DOCTYPE html'."\n";
1591
    $return .= "\t".'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'."\n";
1592
    $return .= "\t".'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
1593
    $return .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.api_get_language_isocode().'" lang="'.api_get_language_isocode().'">'."\n";
1594
1595
    $return .= "<head>\n\t<title>".get_lang('OverviewOfFilesInThisZip')."</title>\n";
1596
    $return .= "\t".'<meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />'."\n";
1597
    $return .= "</head>\n\n";
1598
    $return .= '<body dir="'.api_get_text_direction().'">'."\n\n";
1599
    $return .= "<table border=\"1px\">\n";
1600
1601
    $counter = 0;
1602
    foreach ($files as $value) {
1603
        // Adding the header.
1604
        if ($counter == 0) {
1605
            $columns_array = array_keys($value);
1606
            $return .= "\n<tr>";
1607
            foreach ($columns_array as $columns_array_key => $columns_array_value) {
1608
                if (!in_array($columns_array_value, $dont_show_columns)) {
1609
                    $return .= "\n\t<th>".$columns_array_value."</th>";
1610
                }
1611
                $column[] = $columns_array_value;
1612
            }
1613
            $return .= "\n</tr>\n";
1614
        }
1615
        $counter++;
1616
1617
        // Adding the content.
1618
        $return .= "\n<tr>";
1619
        foreach ($column as $column_key => $column_value) {
1620
            if (!in_array($column_value, $dont_show_columns)) {
1621
                $return .= "\n\t<td>";
1622
                if (in_array($column_value, $make_link)) {
1623
                    $return .= '<a href="'.$value[$column_value].'">'.$value[$column_value].'</a>';
1624
                } else {
1625
                    $return .= $value[$column_value];
1626
                }
1627
                $return .= "</td>";
1628
            }
1629
        }
1630
        $return .= "\n</tr>\n";
1631
    }
1632
    $return .= "\n</table>\n\n</body>";
1633
    $return .= "\n</html>";
1634
1635
    return $return;
1636
}
1637
1638
/**
1639
 * @desc This function retrieves the number of feedback messages on every
1640
 * document. This function might become obsolete when
1641
 *       the feedback becomes user individual.
1642
 *
1643
 * @author Patrick Cool <[email protected]>, Ghent University
1644
 *
1645
 * @version march 2006
1646
 */
1647
function get_total_number_feedback()
1648
{
1649
    $course_id = api_get_course_int_id();
1650
    $sql = "SELECT COUNT(feedback_id) AS total, file_id
1651
            FROM ".Database::get_course_table(TABLE_DROPBOX_FEEDBACK)."
1652
            WHERE c_id = $course_id
1653
            GROUP BY file_id";
1654
    $result = Database::query($sql);
1655
    $return = [];
1656
    while ($row = Database::fetch_array($result)) {
1657
        $return[$row['file_id']] = $row['total'];
1658
    }
1659
1660
    return $return;
1661
}
1662
1663
/**
1664
 * @desc this function checks if the key exists. If this is the case
1665
 * it returns the value, if not it returns 0
1666
 *
1667
 * @author Patrick Cool <[email protected]>, Ghent University
1668
 *
1669
 * @version march 2006
1670
 */
1671
function check_number_feedback($key, $array)
1672
{
1673
    if (is_array($array)) {
1674
        if (array_key_exists($key, $array)) {
1675
            return $array[$key];
1676
        } else {
1677
            return 0;
1678
        }
1679
    } else {
1680
        return 0;
1681
    }
1682
}
1683
1684
/**
1685
 * Get the last access to a given tool of a given user.
1686
 *
1687
 * @param $tool string the tool constant
1688
 * @param $courseId the course_id
1689
 * @param $user_id the id of the user
1690
 *
1691
 * @return string last tool access date
1692
 *
1693
 * @author Patrick Cool <[email protected]>, Ghent University
1694
 *
1695
 * @version march 2006
1696
 *
1697
 * @todo consider moving this function to a more appropriate place.
1698
 */
1699
function get_last_tool_access($tool, $courseId = null, $user_id = null)
1700
{
1701
    // The default values of the parameters
1702
    if (empty($courseId)) {
1703
        $courseId = api_get_course_int_id();
1704
    }
1705
    if (empty($user_id)) {
1706
        $user_id = api_get_user_id();
1707
    }
1708
1709
    // the table where the last tool access is stored (=track_e_lastaccess)
1710
    $table_last_access = Database::get_main_table('track_e_lastaccess');
1711
1712
    $sql = "SELECT access_date FROM $table_last_access
1713
            WHERE
1714
                access_user_id = ".intval($user_id)." AND
1715
                c_id='".intval($courseId)."' AND
1716
                access_tool='".Database::escape_string($tool)."'
1717
                ORDER BY access_date DESC
1718
                LIMIT 1";
1719
    $result = Database::query($sql);
1720
    $row = Database::fetch_array($result);
1721
1722
    return $row['access_date'];
1723
}
1724
/**
1725
 * Previously $dropbox_cnf['mailingIdBase'], returns a mailing ID to generate a mail ID.
1726
 *
1727
 * @return int
1728
 */
1729
function get_mail_id_base()
1730
{
1731
    // false = no mailing functionality
1732
    //$dropbox_cnf['mailingIdBase'] = 10000000;  // bigger than any user_id,
1733
    // allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
1734
    // mailing pseudo_id = dropbox_cnf('mailingIdBase') + mailing id
1735
    return 10000000;
1736
}
1737