Passed
Push — 1.11.x ( 88d8b8...039984 )
by Julito
13:18
created

build_work_directory_selector()   B

Complexity

Conditions 8
Paths 3

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 18
nc 3
nop 3
dl 0
loc 28
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CStudentPublication;
6
use ChamiloSession as Session;
7
8
/**
9
 *  @author Thomas, Hugues, Christophe - original version
10
 *  @author Patrick Cool <[email protected]>, Ghent University -
11
 * ability for course admins to specify wether uploaded documents are visible or invisible by default.
12
 *  @author Roan Embrechts, code refactoring and virtual course support
13
 *  @author Frederic Vauthier, directories management
14
 *  @author Julio Montoya <[email protected]> BeezNest 2011 LOTS of bug fixes
15
 *
16
 *  @todo   this lib should be convert in a static class and moved to main/inc/lib
17
 */
18
19
/**
20
 * Displays action links (for admins, authorized groups members and authorized students).
21
 *
22
 * @param   int Whether to show tool options
23
 * @param   int Whether to show upload form option
24
 * @param bool $isTutor
25
 */
26
function displayWorkActionLinks($id, $action, $isTutor)
27
{
28
    $id = $my_back_id = (int) $id;
29
    if ('list' == $action) {
30
        $my_back_id = 0;
31
    }
32
33
    $output = '';
34
    $origin = api_get_origin();
35
36
    if (!empty($id)) {
37
        $output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&id='.$my_back_id.'">'.
38
            Display::return_icon('back.png', get_lang('BackToWorksList'), '', ICON_SIZE_MEDIUM).
39
            '</a>';
40
    }
41
42
    if (($isTutor || api_is_allowed_to_edit(null, true)) &&
43
        'learnpath' != $origin
44
    ) {
45
        // Create dir
46
        if (empty($id)) {
47
            $output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=create_dir">';
48
            $output .= Display::return_icon(
49
                'new_work.png',
50
                get_lang('CreateAssignment'),
51
                '',
52
                ICON_SIZE_MEDIUM
53
            );
54
            $output .= '</a>';
55
        }
56
    }
57
58
    if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath' && $action == 'list') {
59
        $output .= '<a id="open-view-list" href="#">'.
60
            Display::return_icon(
61
                'listwork.png',
62
                get_lang('ViewStudents'),
63
                '',
64
                ICON_SIZE_MEDIUM
65
            ).
66
            '</a>';
67
    }
68
69
    if ('' != $output) {
70
        echo '<div class="actions">';
71
        echo $output;
72
        echo '</div>';
73
    }
74
}
75
76
/**
77
 * @param string $path
78
 * @param int    $courseId
79
 *
80
 * @return array
81
 */
82
function get_work_data_by_path($path, $courseId = 0)
83
{
84
    $path = Database::escape_string($path);
85
    $courseId = (int) $courseId;
86
    if (empty($courseId)) {
87
        $courseId = api_get_course_int_id();
88
    }
89
90
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
91
    $sql = "SELECT *  FROM $table
92
            WHERE url = '$path' AND c_id = $courseId ";
93
    $result = Database::query($sql);
94
    $return = [];
95
    if (Database::num_rows($result)) {
96
        $return = Database::fetch_array($result, 'ASSOC');
97
    }
98
99
    return $return;
100
}
101
102
/**
103
 * @param int $id
104
 * @param int $courseId
105
 * @param int $sessionId
106
 *
107
 * @return array
108
 */
109
function get_work_data_by_id($id, $courseId = 0, $sessionId = 0)
110
{
111
    $id = (int) $id;
112
    $courseId = ((int) $courseId) ?: api_get_course_int_id();
113
    $course = api_get_course_entity($courseId);
114
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
115
116
    $sessionCondition = '';
117
    if (!empty($sessionId)) {
118
        $sessionCondition = api_get_session_condition($sessionId, true);
119
    }
120
121
    $webCodePath = api_get_path(WEB_CODE_PATH);
122
123
    $sql = "SELECT * FROM $table
124
            WHERE
125
                id = $id AND c_id = $courseId
126
                $sessionCondition";
127
    $result = Database::query($sql);
128
    $work = [];
129
    if (Database::num_rows($result)) {
130
        $work = Database::fetch_array($result, 'ASSOC');
131
        if (empty($work['title'])) {
132
            $work['title'] = basename($work['url']);
133
        }
134
        $work['download_url'] = $webCodePath.'work/download.php?id='.$work['id'].'&'.api_get_cidreq();
135
        $work['view_url'] = $webCodePath.'work/view.php?id='.$work['id'].'&'.api_get_cidreq();
136
        $work['show_url'] = $webCodePath.'work/show_file.php?id='.$work['id'].'&'.api_get_cidreq();
137
        $work['show_content'] = '';
138
        if ($work['contains_file']) {
139
            $fileType = '';
140
            $file = api_get_path(SYS_COURSE_PATH).$course->getDirectory().'/'.$work['url'];
141
            if (file_exists($file)) {
142
                $fileType = mime_content_type($file);
143
            }
144
145
            if (in_array($fileType, ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
146
                $work['show_content'] = Display::img($work['show_url'], $work['title'], null, false);
147
            } elseif (false !== strpos($fileType, 'video/')) {
148
                $work['show_content'] = Display::tag(
149
                    'video',
150
                    get_lang('FileFormatNotSupported'),
151
                    ['src' => $work['show_url']]
152
                );
153
            }
154
        }
155
156
        $fieldValue = new ExtraFieldValue('work');
157
        $work['extra'] = $fieldValue->getAllValuesForAnItem($id, true);
158
    }
159
160
    return $work;
161
}
162
163
/**
164
 * @param int $user_id
165
 * @param int $work_id
166
 *
167
 * @return int
168
 */
169
function get_work_count_by_student($user_id, $work_id)
170
{
171
    $user_id = (int) $user_id;
172
    $work_id = (int) $work_id;
173
    $course_id = api_get_course_int_id();
174
    $session_id = api_get_session_id();
175
    $sessionCondition = api_get_session_condition($session_id);
176
177
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
178
    $sql = "SELECT COUNT(*) as count
179
            FROM  $table
180
            WHERE
181
                c_id = $course_id AND
182
                parent_id = $work_id AND
183
                user_id = $user_id AND
184
                active IN (0, 1)
185
                $sessionCondition";
186
    $result = Database::query($sql);
187
    $return = 0;
188
    if (Database::num_rows($result)) {
189
        $return = Database::fetch_row($result, 'ASSOC');
190
        $return = (int) ($return[0]);
191
    }
192
193
    return $return;
194
}
195
196
/**
197
 * @param int $id
198
 * @param int $courseId
199
 *
200
 * @return array
201
 */
202
function get_work_assignment_by_id($id, $courseId = 0)
203
{
204
    $courseId = (int) $courseId;
205
    if (empty($courseId)) {
206
        $courseId = api_get_course_int_id();
207
    }
208
    $id = (int) $id;
209
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
210
    $sql = "SELECT * FROM $table
211
            WHERE c_id = $courseId AND publication_id = $id";
212
    $result = Database::query($sql);
213
    $return = [];
214
    if (Database::num_rows($result)) {
215
        $return = Database::fetch_array($result, 'ASSOC');
216
    }
217
218
    return $return;
219
}
220
221
/**
222
 * @param int    $id
223
 * @param array  $my_folder_data
224
 * @param string $add_in_where_query
225
 * @param int    $course_id
226
 * @param int    $session_id
227
 *
228
 * @return array
229
 */
230
function getWorkList($id, $my_folder_data, $add_in_where_query = null, $course_id = 0, $session_id = 0)
231
{
232
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
233
234
    $course_id = $course_id ? $course_id : api_get_course_int_id();
235
    $session_id = $session_id ? $session_id : api_get_session_id();
236
    $condition_session = api_get_session_condition($session_id);
237
    $group_id = api_get_group_id();
238
239
    $groupIid = 0;
240
    if ($group_id) {
241
        $groupInfo = GroupManager::get_group_properties($group_id);
242
        if ($groupInfo) {
243
            $groupIid = $groupInfo['iid'];
244
        }
245
    }
246
247
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
248
    $linkInfo = GradebookUtils::isResourceInCourseGradebook(
249
        api_get_course_id(),
250
        3,
251
        $id,
252
        api_get_session_id()
253
    );
254
255
    if ($linkInfo) {
256
        $workInGradeBookLinkId = $linkInfo['id'];
257
        if ($workInGradeBookLinkId) {
258
            if ($is_allowed_to_edit) {
259
                if (intval($my_folder_data['qualification']) == 0) {
260
                    echo Display::return_message(
261
                        get_lang('MaxWeightNeedToBeProvided'),
262
                        'warning'
263
                    );
264
                }
265
            }
266
        }
267
    }
268
269
    $contains_file_query = '';
270
    // Get list from database
271
    if ($is_allowed_to_edit) {
272
        $active_condition = ' active IN (0, 1)';
273
        $sql = "SELECT * FROM $work_table
274
                WHERE
275
                    c_id = $course_id
276
                    $add_in_where_query
277
                    $condition_session AND
278
                    $active_condition AND
279
                    (parent_id = 0)
280
                    $contains_file_query AND
281
                    post_group_id = $groupIid
282
                ORDER BY sent_date DESC";
283
    } else {
284
        if (!empty($group_id)) {
285
            // set to select only messages posted by the user's group
286
            $group_query = " WHERE c_id = $course_id AND post_group_id = $groupIid";
287
            $subdirs_query = ' AND parent_id = 0';
288
        } else {
289
            $group_query = " WHERE c_id = $course_id AND (post_group_id = '0' OR post_group_id is NULL) ";
290
            $subdirs_query = ' AND parent_id = 0';
291
        }
292
        //@todo how we can active or not an assignment?
293
        $active_condition = ' AND active IN (1, 0)';
294
        $sql = "SELECT * FROM  $work_table
295
                $group_query
296
                $subdirs_query
297
                $add_in_where_query
298
                $active_condition
299
                $condition_session
300
                ORDER BY title";
301
    }
302
303
    $work_parents = [];
304
305
    $sql_result = Database::query($sql);
306
    if (Database::num_rows($sql_result)) {
307
        while ($work = Database::fetch_object($sql_result)) {
308
            if (0 == $work->parent_id) {
309
                $work_parents[] = $work;
310
            }
311
        }
312
    }
313
314
    return $work_parents;
315
}
316
317
/**
318
 * @param int $userId
319
 * @param int $courseId
320
 * @param int $sessionId
321
 *
322
 * @return array
323
 */
324
function getWorkPerUser($userId, $courseId = 0, $sessionId = 0)
325
{
326
    $works = getWorkList(null, null, null, $courseId, $sessionId);
327
    $result = [];
328
    if (!empty($works)) {
329
        foreach ($works as $workData) {
330
            $workId = $workData->id;
331
            $result[$workId]['work'] = $workData;
332
            $result[$workId]['work']->user_results = get_work_user_list(
333
                0,
334
                100,
335
                null,
336
                null,
337
                $workId,
338
                null,
339
                $userId,
340
                false,
341
                $courseId,
342
                $sessionId
343
            );
344
        }
345
    }
346
347
    return $result;
348
}
349
350
/**
351
 * @param int $workId
352
 * @param int $groupId
353
 * @param int $course_id
354
 * @param int $sessionId
355
 */
356
function getUniqueStudentAttemptsTotal($workId, $groupId, $course_id, $sessionId)
357
{
358
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
359
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
360
    $course_id = (int) $course_id;
361
    $workId = (int) $workId;
362
    $sessionId = (int) $sessionId;
363
    $groupId = (int) $groupId;
364
    $sessionCondition = api_get_session_condition(
365
        $sessionId,
366
        true,
367
        false,
368
        'w.session_id'
369
    );
370
371
    $groupIid = 0;
372
    if ($groupId) {
373
        $groupInfo = GroupManager::get_group_properties($groupId);
374
        $groupIid = $groupInfo['iid'];
375
    }
376
377
    $sql = "SELECT count(DISTINCT u.user_id)
378
            FROM $work_table w
379
            INNER JOIN $user_table u
380
            ON w.user_id = u.user_id
381
            WHERE
382
                w.c_id = $course_id
383
                $sessionCondition AND
384
                w.parent_id = $workId AND
385
                w.post_group_id = $groupIid AND
386
                w.active IN (0, 1)
387
            ";
388
389
    $res_document = Database::query($sql);
390
    $rowCount = Database::fetch_row($res_document);
391
392
    return $rowCount[0];
393
}
394
395
/**
396
 * @param mixed $workId
397
 * @param int   $groupId
398
 * @param int   $course_id
399
 * @param int   $sessionId
400
 * @param int   $userId       user id to filter
401
 * @param array $onlyUserList only parse this user list
402
 *
403
 * @return mixed
404
 */
405
function getUniqueStudentAttempts(
406
    $workId,
407
    $groupId,
408
    $course_id,
409
    $sessionId,
410
    $userId = null,
411
    $onlyUserList = []
412
) {
413
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
414
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
415
416
    $course_id = (int) $course_id;
417
    $workCondition = null;
418
    if (is_array($workId)) {
419
        $workId = array_map('intval', $workId);
420
        $workId = implode("','", $workId);
421
        $workCondition = " w.parent_id IN ('".$workId."') AND";
422
    } else {
423
        $workId = (int) $workId;
424
        $workCondition = ' w.parent_id = '.$workId.' AND';
425
    }
426
427
    $sessionId = (int) $sessionId;
428
    $groupId = (int) $groupId;
429
    $studentCondition = null;
430
431
    if (!empty($onlyUserList)) {
432
        $onlyUserList = array_map('intval', $onlyUserList);
433
        $studentCondition = "AND u.user_id IN ('".implode("', '", $onlyUserList)."') ";
434
    } else {
435
        if (empty($userId)) {
436
            return 0;
437
        }
438
    }
439
440
    $groupIid = 0;
441
    if ($groupId) {
442
        $groupInfo = GroupManager::get_group_properties($groupId);
443
        $groupIid = $groupInfo['iid'];
444
    }
445
446
    $sessionCondition = api_get_session_condition(
447
        $sessionId,
448
        true,
449
        false,
450
        'w.session_id'
451
    );
452
453
    $sql = "SELECT count(*) FROM (
454
                SELECT count(*), w.parent_id
455
                FROM $work_table w
456
                INNER JOIN $user_table u
457
                ON w.user_id = u.user_id
458
                WHERE
459
                    w.filetype = 'file' AND
460
                    w.c_id = $course_id
461
                    $sessionCondition AND
462
                    $workCondition
463
                    w.post_group_id = $groupIid AND
464
                    w.active IN (0, 1) $studentCondition
465
                ";
466
    if (!empty($userId)) {
467
        $userId = (int) $userId;
468
        $sql .= ' AND u.user_id = '.$userId;
469
    }
470
    $sql .= ' GROUP BY u.user_id, w.parent_id) as t';
471
    $result = Database::query($sql);
472
    $row = Database::fetch_row($result);
473
474
    return $row[0];
475
}
476
477
/**
478
 * Shows the work list (student view).
479
 *
480
 * @return string
481
 */
482
function showStudentWorkGrid()
483
{
484
    $courseInfo = api_get_course_info();
485
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student&'.api_get_cidreq();
486
487
    $columns = [
488
        get_lang('Type'),
489
        get_lang('Title'),
490
        get_lang('HandOutDateLimit'),
491
        get_lang('Feedback'),
492
        get_lang('LastUpload'),
493
    ];
494
495
    $columnModel = [
496
        ['name' => 'type', 'index' => 'type', 'width' => '30', 'align' => 'center', 'sortable' => 'false'],
497
        ['name' => 'title', 'index' => 'title', 'width' => '250', 'align' => 'left'],
498
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '80', 'align' => 'center', 'sortable' => 'false'],
499
        ['name' => 'feedback', 'index' => 'feedback', 'width' => '80', 'align' => 'center', 'sortable' => 'false'],
500
        ['name' => 'last_upload', 'index' => 'feedback', 'width' => '125', 'align' => 'center', 'sortable' => 'false'],
501
    ];
502
503
    if ($courseInfo['show_score'] == 0) {
504
        $columnModel[] = [
505
            'name' => 'others',
506
            'index' => 'others',
507
            'width' => '80',
508
            'align' => 'left',
509
            'sortable' => 'false',
510
        ];
511
        $columns[] = get_lang('Others');
512
    }
513
514
    $params = [
515
        'autowidth' => 'true',
516
        'height' => 'auto',
517
    ];
518
519
    $html = '<script>
520
        $(function() {
521
            '.Display::grid_js('workList', $url, $columns, $columnModel, $params, [], null, true).'
522
        });
523
    </script>';
524
525
    $html .= Display::grid_html('workList');
526
527
    return $html;
528
}
529
530
/**
531
 * Shows the work list (student view).
532
 *
533
 * @return string
534
 */
535
function showStudentAllWorkGrid($withResults = 1)
536
{
537
    $withResults = (int) $withResults;
538
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_all_work_student&with_results='.$withResults;
539
540
    $columns = [
541
        get_lang('Type'),
542
        get_lang('Title'),
543
        get_lang('HandOutDateLimit'),
544
    ];
545
546
    $id = 'workList';
547
    if ($withResults) {
548
        $id = 'workListWithResults';
549
        $columns[] = get_lang('Feedback');
550
        $columns[] = get_lang('LastUpload');
551
    }
552
553
    $columnModel = [
554
        ['name' => 'type', 'index' => 'type', 'width' => '50', 'align' => 'center', 'sortable' => 'false'],
555
        ['name' => 'title', 'index' => 'title', 'width' => '600', 'align' => 'left'],
556
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '125', 'align' => 'center', 'sortable' => 'false'],
557
    ];
558
559
    if ($withResults) {
560
        $columnModel[] = [
561
            'name' => 'feedback',
562
            'index' => 'feedback',
563
            'width' => '150',
564
            'align' => 'center',
565
            'sortable' => 'false',
566
        ];
567
        $columnModel[] = [
568
            'name' => 'last_upload',
569
            'index' => 'last_upload',
570
            'width' => '150',
571
            'align' => 'center',
572
            'sortable' => 'false',
573
        ];
574
    }
575
576
    $params = [
577
        'autowidth' => 'true',
578
        'height' => 'auto',
579
    ];
580
581
    $html = '<script>
582
        $(function() {
583
            '.Display::grid_js($id, $url, $columns, $columnModel, $params, [], null, true).'
584
        });
585
    </script>';
586
587
    $html .= Display::grid_html($id);
588
589
    return $html;
590
}
591
592
/**
593
 * Shows the work list (teacher view).
594
 *
595
 * @return string
596
 */
597
function showTeacherWorkGrid()
598
{
599
    $columnModel = [
600
        ['name' => 'type', 'index' => 'type', 'width' => '35', 'align' => 'center', 'sortable' => 'false'],
601
        ['name' => 'title', 'index' => 'title', 'width' => '300', 'align' => 'left', 'wrap_cell' => "true"],
602
        ['name' => 'sent_date', 'index' => 'sent_date', 'width' => '125', 'align' => 'center'],
603
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '125', 'align' => 'center'],
604
        ['name' => 'amount', 'index' => 'amount', 'width' => '110', 'align' => 'center', 'sortable' => 'false'],
605
        ['name' => 'actions', 'index' => 'actions', 'width' => '110', 'align' => 'left', 'sortable' => 'false'],
606
    ];
607
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_teacher&'.api_get_cidreq();
608
    $deleteUrl = api_get_path(WEB_AJAX_PATH).'work.ajax.php?a=delete_work&'.api_get_cidreq();
609
610
    $columns = [
611
        get_lang('Type'),
612
        get_lang('Title'),
613
        get_lang('SentDate'),
614
        get_lang('HandOutDateLimit'),
615
        get_lang('AmountSubmitted'),
616
        get_lang('Actions'),
617
    ];
618
619
    $params = [
620
        'multiselect' => true,
621
        'autowidth' => 'true',
622
        'height' => 'auto',
623
    ];
624
625
    $html = '<script>
626
    $(function() {
627
        '.Display::grid_js('workList', $url, $columns, $columnModel, $params, [], null, true).'
628
        $("#workList").jqGrid(
629
            "navGrid",
630
            "#workList_pager",
631
            { edit: false, add: false, del: true },
632
            { height:280, reloadAfterSubmit:false }, // edit options
633
            { height:280, reloadAfterSubmit:false }, // add options
634
            { reloadAfterSubmit:false, url: "'.$deleteUrl.'" }, // del options
635
            { width:500 } // search options
636
        );
637
    });
638
    </script>';
639
    $html .= Display::grid_html('workList');
640
641
    return $html;
642
}
643
644
/**
645
 * Builds the form that enables the user to
646
 * move a document from one directory to another
647
 * This function has been copied from the document/document.inc.php library.
648
 *
649
 * @param array  $folders
650
 * @param string $curdirpath
651
 * @param string $move_file
652
 * @param string $group_dir
653
 *
654
 * @return string html form
655
 */
656
function build_work_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
657
{
658
    $course_id = api_get_course_int_id();
659
    $move_file = (int) $move_file;
660
    $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
661
    $sql = "SELECT title, url FROM $tbl_work
662
            WHERE c_id = $course_id AND id ='".$move_file."'";
663
    $result = Database::query($sql);
664
    $row = Database::fetch_array($result, 'ASSOC');
665
    $title = empty($row['title']) ? basename($row['url']) : $row['title'];
666
667
    $form = new FormValidator(
668
        'move_to_form',
669
        'post',
670
        api_get_self().'?'.api_get_cidreq().'&curdirpath='.Security::remove_XSS($curdirpath)
671
    );
672
673
    $form->addHeader(get_lang('MoveFile').' - '.Security::remove_XSS($title));
674
    $form->addHidden('item_id', $move_file);
675
    $form->addHidden('action', 'move_to');
676
677
    // Group documents cannot be uploaded in the root
678
    if ($group_dir == '') {
679
        if (is_array($folders)) {
680
            foreach ($folders as $fid => $folder) {
681
                //you cannot move a file to:
682
                //1. current directory
683
                //2. inside the folder you want to move
684
                //3. inside a subfolder of the folder you want to move
685
                if (($curdirpath != $folder) &&
686
                    ($folder != $move_file) &&
687
                    (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
688
                ) {
689
                    $options[$fid] = $folder;
690
                }
691
            }
692
        }
693
    } else {
694
        if ($curdirpath != '/') {
695
            $form .= '<option value="0">/ ('.get_lang('Root').')</option>';
696
        }
697
        foreach ($folders as $fid => $folder) {
698
            if (($curdirpath != $folder) && ($folder != $move_file) &&
699
                (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
700
            ) {
701
                //cannot copy dir into his own subdir
702
                $display_folder = substr($folder, strlen($group_dir));
703
                $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
704
                //$form .= '<option value="'.$fid.'">'.$display_folder.'</option>'."\n";
705
                $options[$fid] = $display_folder;
706
            }
707
        }
708
    }
709
710
    $form->addSelect('move_to_id', get_lang('Select'), $options);
711
    $form->addButtonSend(get_lang('MoveFile'), 'move_file_submit');
712
713
    return $form->returnForm();
714
}
715
716
/**
717
 * creates a new directory trying to find a directory name
718
 * that doesn't already exist.
719
 *
720
 * @author Hugues Peeters <[email protected]>
721
 * @author Bert Vanderkimpen
722
 * @author Yannick Warnier <[email protected]> Adaptation for work tool
723
 *
724
 * @param string $workDir        Base work dir (.../work)
725
 * @param string $desiredDirName complete path of the desired name
726
 *
727
 * @return string actual directory name if it succeeds, boolean false otherwise
728
 */
729
function create_unexisting_work_directory($workDir, $desiredDirName)
730
{
731
    $counter = 0;
732
    $workDir = (substr($workDir, -1, 1) == '/' ? $workDir : $workDir.'/');
733
    $checkDirName = $desiredDirName;
734
    while (file_exists($workDir.$checkDirName)) {
735
        $counter++;
736
        $checkDirName = $desiredDirName.$counter;
737
    }
738
739
    if (@mkdir($workDir.$checkDirName, api_get_permissions_for_new_directories())) {
740
        return $checkDirName;
741
    } else {
742
        return false;
743
    }
744
}
745
746
/**
747
 * Delete a work-tool directory.
748
 *
749
 * @param int $id work directory id to delete
750
 *
751
 * @return int -1 on error
752
 */
753
function deleteDirWork($id)
754
{
755
    $locked = api_resource_is_locked_by_gradebook($id, LINK_STUDENTPUBLICATION);
756
757
    if ($locked == true) {
758
        echo Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
759
760
        return false;
761
    }
762
763
    $_course = api_get_course_info();
764
    $id = intval($id);
765
    $work_data = get_work_data_by_id($id);
766
767
    if (empty($work_data)) {
768
        return false;
769
    }
770
771
    $base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work';
772
    $work_data_url = $base_work_dir.$work_data['url'];
773
    $check = Security::check_abs_path($work_data_url.'/', $base_work_dir.'/');
774
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
775
    $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
776
    $t_agenda = Database::get_course_table(TABLE_AGENDA);
777
    $course_id = api_get_course_int_id();
778
    $sessionId = api_get_session_id();
779
780
    if (!empty($work_data['url'])) {
781
        if ($check) {
782
            $consideredWorkingTime = api_get_configuration_value('considered_working_time');
783
            if (!empty($consideredWorkingTime)) {
784
                $fieldValue = new ExtraFieldValue('work');
785
                $resultExtra = $fieldValue->getAllValuesForAnItem(
786
                    $work_data['id'],
787
                    true
788
                );
789
790
                $workingTime = null;
791
                foreach ($resultExtra as $field) {
792
                    $field = $field['value'];
793
                    if ($consideredWorkingTime == $field->getField()->getVariable()) {
794
                        $workingTime = $field->getValue();
795
796
                        break;
797
                    }
798
                }
799
800
                $courseUsers = CourseManager::get_user_list_from_course_code($_course['code'], $sessionId);
801
                if (!empty($workingTime)) {
802
                    foreach ($courseUsers as $user) {
803
                        $userWorks = get_work_user_list(
804
                            0,
805
                            100,
806
                            null,
807
                            null,
808
                            $work_data['id'],
809
                            null,
810
                            $user['user_id'],
811
                            false,
812
                            $course_id,
813
                            $sessionId
814
                        );
815
816
                        if (count($userWorks) != 1) {
817
                            continue;
818
                        }
819
                        Event::eventRemoveVirtualCourseTime($course_id, $user['user_id'], $sessionId, $workingTime);
820
                    }
821
                }
822
            }
823
824
            // Deleting all contents inside the folder
825
            $sql = "UPDATE $table SET active = 2
826
                    WHERE c_id = $course_id AND filetype = 'folder' AND id = $id";
827
            Database::query($sql);
828
829
            $sql = "UPDATE $table SET active = 2
830
                    WHERE c_id = $course_id AND parent_id = $id";
831
            Database::query($sql);
832
833
            $new_dir = $work_data_url.'_DELETED_'.$id;
834
835
            if (api_get_setting('permanently_remove_deleted_files') == 'true') {
836
                my_delete($work_data_url);
837
            } else {
838
                if (file_exists($work_data_url)) {
839
                    rename($work_data_url, $new_dir);
840
                }
841
            }
842
843
            // Gets calendar_id from student_publication_assigment
844
            $sql = "SELECT add_to_calendar FROM $TSTDPUBASG
845
                    WHERE c_id = $course_id AND publication_id = $id";
846
            $res = Database::query($sql);
847
            $calendar_id = Database::fetch_row($res);
848
849
            // delete from agenda if it exists
850
            if (!empty($calendar_id[0])) {
851
                $sql = "DELETE FROM $t_agenda
852
                        WHERE c_id = $course_id AND id = '".$calendar_id[0]."'";
853
                Database::query($sql);
854
            }
855
            $sql = "DELETE FROM $TSTDPUBASG
856
                    WHERE c_id = $course_id AND publication_id = $id";
857
            Database::query($sql);
858
859
            Skill::deleteSkillsFromItem($id, ITEM_TYPE_STUDENT_PUBLICATION);
860
861
            Event::addEvent(
862
                LOG_WORK_DIR_DELETE,
863
                LOG_WORK_DATA,
864
                [
865
                    'id' => $work_data['id'],
866
                    'url' => $work_data['url'],
867
                    'title' => $work_data['title'],
868
                ],
869
                null,
870
                api_get_user_id(),
871
                api_get_course_int_id(),
872
                $sessionId
873
            );
874
875
            $linkInfo = GradebookUtils::isResourceInCourseGradebook(
876
                api_get_course_id(),
877
                3,
878
                $id,
879
                api_get_session_id()
880
            );
881
            $link_id = $linkInfo['id'];
882
            if ($linkInfo !== false) {
883
                GradebookUtils::remove_resource_from_course_gradebook($link_id);
884
            }
885
886
            return true;
887
        }
888
    }
889
}
890
891
/**
892
 * Get the path of a document in the student_publication table (path relative to the course directory).
893
 *
894
 * @param int $id
895
 *
896
 * @return string Path (or -1 on error)
897
 */
898
function get_work_path($id)
899
{
900
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
901
    $course_id = api_get_course_int_id();
902
    $sql = 'SELECT url FROM '.$table.'
903
            WHERE c_id = '.$course_id.' AND id='.(int) $id;
904
    $res = Database::query($sql);
905
    if (Database::num_rows($res)) {
906
        $row = Database::fetch_array($res);
907
908
        return $row['url'];
909
    }
910
911
    return -1;
912
}
913
914
/**
915
 * Update the url of a work in the student_publication table.
916
 *
917
 * @param int    $id        of the work to update
918
 * @param string $new_path  Destination directory where the work has been moved (must end with a '/')
919
 * @param int    $parent_id
920
 *
921
 * @return mixed Int -1 on error, sql query result on success
922
 */
923
function updateWorkUrl($id, $new_path, $parent_id)
924
{
925
    if (empty($id)) {
926
        return -1;
927
    }
928
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
929
    $course_id = api_get_course_int_id();
930
    $id = (int) $id;
931
    $parent_id = (int) $parent_id;
932
933
    $sql = "SELECT * FROM $table
934
            WHERE c_id = $course_id AND id = $id";
935
    $res = Database::query($sql);
936
    if (Database::num_rows($res) != 1) {
937
        return -1;
938
    } else {
939
        $row = Database::fetch_array($res);
940
        $filename = basename($row['url']);
941
        $new_url = $new_path.$filename;
942
        $new_url = Database::escape_string($new_url);
943
944
        $sql = "UPDATE $table SET
945
                   url = '$new_url',
946
                   parent_id = '$parent_id'
947
                WHERE c_id = $course_id AND id = $id";
948
949
        return Database::query($sql);
950
    }
951
}
952
953
/**
954
 * Update the url of a dir in the student_publication table.
955
 *
956
 * @param array  $work_data work original data
957
 * @param string $newPath   Example: "folder1"
958
 *
959
 * @return bool
960
 */
961
function updateDirName($work_data, $newPath)
962
{
963
    $course_id = $work_data['c_id'];
964
    $work_id = (int) ($work_data['iid']);
965
    $oldPath = $work_data['url'];
966
    $originalNewPath = Database::escape_string($newPath);
967
    $newPath = Database::escape_string($newPath);
968
    $newPath = api_replace_dangerous_char($newPath);
969
    $newPath = disable_dangerous_file($newPath);
970
971
    if ($oldPath == '/'.$newPath) {
972
        return true;
973
    }
974
975
    if (!empty($newPath)) {
976
        $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
977
        $sql = "UPDATE $table SET
978
                    title = '".$originalNewPath."'
979
                WHERE
980
                    c_id = $course_id AND
981
                    iid = $work_id";
982
        Database::query($sql);
983
    }
984
}
985
986
/**
987
 * returns all the javascript that is required for easily
988
 * validation when you create a work
989
 * this goes into the $htmlHeadXtra[] array.
990
 */
991
function to_javascript_work()
992
{
993
    return '<script>
994
        function updateDocumentTitle(value) {
995
            var temp = value.indexOf("/");
996
            //linux path
997
            if(temp != -1){
998
                temp=value.split("/");
999
            } else {
1000
                temp=value.split("\\\");
1001
            }
1002
1003
            var fullFilename = temp[temp.length - 1];
1004
            var baseFilename = fullFilename;
1005
1006
            // get file extension
1007
            var fileExtension = "";
1008
            if (fullFilename.match(/\..+/)) {
1009
                fileInfo = fullFilename.match(/(.*)\.([^.]+)$/);
1010
                if (fileInfo.length > 1) {
1011
                    fileExtension = "."+fileInfo[fileInfo.length - 1];
1012
                    baseFilename = fileInfo[fileInfo.length - 2];
1013
                }
1014
            }
1015
1016
            document.getElementById("file_upload").value = baseFilename;
1017
            document.getElementById("file_extension").value = fileExtension;
1018
            $("#contains_file_id").attr("value", 1);
1019
        }
1020
        function setFocus() {
1021
            $("#work_title").focus();
1022
        }
1023
1024
        $(function() {
1025
            setFocus();
1026
            var checked = $("#expiry_date").attr("checked");
1027
            if (checked) {
1028
                $("#option2").show();
1029
            } else {
1030
                $("#option2").hide();
1031
            }
1032
1033
            var checkedEndDate = $("#end_date").attr("checked");
1034
            if (checkedEndDate) {
1035
                $("#option3").show();
1036
                $("#ends_on").attr("checked", true);
1037
            } else {
1038
                $("#option3").hide();
1039
                $("#ends_on").attr("checked", false);
1040
            }
1041
1042
            $("#expiry_date").click(function() {
1043
                $("#option2").toggle();
1044
            });
1045
1046
            $("#end_date").click(function() {
1047
                $("#option3").toggle();
1048
            });
1049
        });
1050
    </script>';
1051
}
1052
1053
/**
1054
 * Gets the id of a student publication with a given path.
1055
 *
1056
 * @param string $path
1057
 *
1058
 * @return true if is found / false if not found
1059
 */
1060
// TODO: The name of this function does not fit with the kind of information it returns.
1061
// Maybe check_work_id() or is_work_id()?
1062
function get_work_id($path)
1063
{
1064
    $TBL_STUDENT_PUBLICATION = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1065
    $TBL_PROP_TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
1066
    $course_id = api_get_course_int_id();
1067
    $path = Database::escape_string($path);
1068
1069
    if (api_is_allowed_to_edit()) {
1070
        $sql = "SELECT work.id
1071
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1072
                WHERE
1073
                    props.c_id = $course_id AND
1074
                    work.c_id = $course_id AND
1075
                    props.tool='work' AND
1076
                    work.id=props.ref AND
1077
                    work.url LIKE 'work/".$path."%' AND
1078
                    work.filetype='file' AND
1079
                    props.visibility<>'2'";
1080
    } else {
1081
        $sql = "SELECT work.id
1082
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1083
                WHERE
1084
                    props.c_id = $course_id AND
1085
                    work.c_id = $course_id AND
1086
                    props.tool='work' AND
1087
                    work.id=props.ref AND
1088
                    work.url LIKE 'work/".$path."%' AND
1089
                    work.filetype='file' AND
1090
                    props.visibility<>'2' AND
1091
                    props.lastedit_user_id = '".api_get_user_id()."'";
1092
    }
1093
    $result = Database::query($sql);
1094
    $num_rows = Database::num_rows($result);
1095
1096
    if ($result && $num_rows > 0) {
1097
        return true;
1098
    } else {
1099
        return false;
1100
    }
1101
}
1102
1103
/**
1104
 * @param int $work_id
1105
 * @param int $onlyMeUserId show only my works
1106
 * @param int $notMeUserId  show works from everyone except me
1107
 *
1108
 * @return int
1109
 */
1110
function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null)
1111
{
1112
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1113
    $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1114
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
1115
1116
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true) || api_is_coach();
1117
    $session_id = api_get_session_id();
1118
    $condition_session = api_get_session_condition(
1119
        $session_id,
1120
        true,
1121
        false,
1122
        'work.session_id'
1123
    );
1124
1125
    $group_id = api_get_group_id();
1126
    $course_info = api_get_course_info();
1127
    $course_id = $course_info['real_id'];
1128
    $work_id = (int) $work_id;
1129
1130
    $groupIid = 0;
1131
    if ($group_id) {
1132
        $groupInfo = GroupManager::get_group_properties($group_id);
1133
        if ($groupInfo && isset($groupInfo['iid'])) {
1134
            $groupIid = (int) $groupInfo['iid'];
1135
        }
1136
    }
1137
1138
    if (!empty($group_id)) {
1139
        // set to select only messages posted by the user's group
1140
        $extra_conditions = " work.post_group_id = '".$groupIid."' ";
1141
    } else {
1142
        $extra_conditions = " (work.post_group_id = '0' or work.post_group_id IS NULL) ";
1143
    }
1144
1145
    if ($is_allowed_to_edit) {
1146
        $extra_conditions .= ' AND work.active IN (0, 1) ';
1147
    } else {
1148
        $extra_conditions .= ' AND work.active IN (0, 1) AND accepted = 1';
1149
        if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
1150
            $extra_conditions .= " AND work.user_id = ".api_get_user_id()." ";
1151
        } else {
1152
            $extra_conditions .= '';
1153
        }
1154
    }
1155
1156
    $extra_conditions .= " AND parent_id  = ".$work_id."  ";
1157
    $where_condition = null;
1158
    if (!empty($notMeUserId)) {
1159
        $where_condition .= " AND u.user_id <> ".intval($notMeUserId);
1160
    }
1161
1162
    if (!empty($onlyMeUserId)) {
1163
        $where_condition .= " AND u.user_id =  ".intval($onlyMeUserId);
1164
    }
1165
1166
    $sql = "SELECT count(*) as count
1167
            FROM $iprop_table prop
1168
            INNER JOIN $work_table work
1169
            ON (
1170
                prop.ref = work.id AND
1171
                prop.c_id = $course_id AND
1172
                prop.tool='work' AND
1173
                prop.visibility <> 2 AND
1174
                work.c_id = $course_id
1175
            )
1176
            INNER JOIN $user_table u
1177
            ON (work.user_id = u.user_id)
1178
            WHERE $extra_conditions $where_condition $condition_session";
1179
1180
    $result = Database::query($sql);
1181
1182
    $users_with_work = 0;
1183
    if (Database::num_rows($result)) {
1184
        $result = Database::fetch_array($result);
1185
        $users_with_work = $result['count'];
1186
    }
1187
1188
    return $users_with_work;
1189
}
1190
1191
/**
1192
 * @param int    $start
1193
 * @param int    $limit
1194
 * @param string $column
1195
 * @param string $direction
1196
 * @param string $where_condition
1197
 * @param bool   $getCount
1198
 *
1199
 * @return array
1200
 */
1201
function getWorkListStudent(
1202
    $start,
1203
    $limit,
1204
    $column,
1205
    $direction,
1206
    $where_condition,
1207
    $getCount = false
1208
) {
1209
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1210
    $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1211
    $courseInfo = api_get_course_info();
1212
    $course_id = $courseInfo['real_id'];
1213
    $session_id = api_get_session_id();
1214
    $condition_session = api_get_session_condition($session_id);
1215
    $group_id = api_get_group_id();
1216
    $userId = api_get_user_id();
1217
1218
    $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
1219
        $userId,
1220
        $courseInfo
1221
    );
1222
1223
    if (!in_array($direction, ['asc', 'desc'])) {
1224
        $direction = 'desc';
1225
    }
1226
    if (!empty($where_condition)) {
1227
        $where_condition = ' AND '.$where_condition;
1228
    }
1229
1230
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1231
    $start = (int) $start;
1232
    $limit = (int) $limit;
1233
1234
    $groupIid = 0;
1235
    if ($group_id) {
1236
        $groupInfo = GroupManager::get_group_properties($group_id);
1237
        if ($groupInfo) {
1238
            $groupIid = (int) $groupInfo['iid'];
1239
        }
1240
    }
1241
1242
    if (!empty($groupIid)) {
1243
        $group_query = " WHERE w.c_id = $course_id AND post_group_id = $groupIid";
1244
        $subdirs_query = 'AND parent_id = 0';
1245
    } else {
1246
        $group_query = " WHERE w.c_id = $course_id AND (post_group_id = '0' or post_group_id is NULL)  ";
1247
        $subdirs_query = 'AND parent_id = 0';
1248
    }
1249
1250
    $active_condition = ' AND active IN (1, 0)';
1251
1252
    if ($getCount) {
1253
        $select = 'SELECT count(w.id) as count ';
1254
    } else {
1255
        $select = 'SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ';
1256
    }
1257
1258
    $sql = "$select
1259
            FROM $workTable w
1260
            LEFT JOIN $workTableAssignment a
1261
            ON (a.publication_id = w.id AND a.c_id = w.c_id)
1262
                $group_query
1263
                $subdirs_query
1264
                $active_condition
1265
                $condition_session
1266
                $where_condition
1267
            ";
1268
1269
    $sql .= " ORDER BY $column $direction ";
1270
1271
    if (!empty($start) && !empty($limit)) {
1272
        $sql .= " LIMIT $start, $limit";
1273
    }
1274
1275
    $result = Database::query($sql);
1276
1277
    if ($getCount) {
1278
        $row = Database::fetch_array($result);
1279
1280
        return $row['count'];
1281
    }
1282
1283
    $works = [];
1284
    $url = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq();
1285
    if ($isDrhOfCourse) {
1286
        $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
1287
    }
1288
1289
    $urlOthers = api_get_path(WEB_CODE_PATH).'work/work_list_others.php?'.api_get_cidreq().'&id=';
1290
    while ($work = Database::fetch_array($result, 'ASSOC')) {
1291
        $isSubscribed = userIsSubscribedToWork($userId, $work['id'], $course_id);
1292
        if ($isSubscribed == false) {
1293
            continue;
1294
        }
1295
1296
        $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $session_id);
1297
1298
        if ($visibility != 1) {
1299
            continue;
1300
        }
1301
1302
        $work['type'] = Display::return_icon('work.png');
1303
        $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
1304
1305
        if (empty($work['title'])) {
1306
            $work['title'] = basename($work['url']);
1307
        }
1308
1309
        $whereCondition = " AND u.user_id = $userId ";
1310
1311
        $workList = get_work_user_list(
1312
            0,
1313
            1000,
1314
            null,
1315
            null,
1316
            $work['id'],
1317
            $whereCondition
1318
        );
1319
1320
        $count = getTotalWorkComment($workList, $courseInfo);
1321
        $lastWork = getLastWorkStudentFromParentByUser($userId, $work, $courseInfo);
1322
1323
        if (!is_null($count) && !empty($count)) {
1324
            $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$lastWork['id'].'&'.api_get_cidreq();
1325
1326
            $feedback = '&nbsp;'.Display::url(
1327
                Display::returnFontAwesomeIcon('comments-o'),
1328
                $urlView,
1329
                ['title' => get_lang('View')]
1330
            );
1331
1332
            $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info').$feedback;
1333
        }
1334
1335
        if (!empty($lastWork)) {
1336
            $work['last_upload'] = (!empty($lastWork['qualification'])) ? $lastWork['qualification_rounded'].' - ' : '';
1337
            $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
1338
        }
1339
1340
        $work['title'] = Display::url($work['title'], $url.'&id='.$work['id']);
1341
        $work['others'] = Display::url(
1342
            Display::return_icon('group.png', get_lang('Others')),
1343
            $urlOthers.$work['id']
1344
        );
1345
        $works[] = $work;
1346
    }
1347
1348
    return $works;
1349
}
1350
1351
/**
1352
 * @param int    $start
1353
 * @param int    $limit
1354
 * @param string $column
1355
 * @param string $direction
1356
 * @param string $where_condition
1357
 * @param bool   $getCount
1358
 * @param int    $withResults
1359
 *
1360
 * @return array
1361
 */
1362
function getAllWorkListStudent(
1363
    $start,
1364
    $limit,
1365
    $column,
1366
    $direction,
1367
    $where_condition,
1368
    $getCount = false,
1369
    $withResults = 1
1370
) {
1371
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1372
    $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1373
    $userId = api_get_user_id();
1374
1375
    if (empty($userId)) {
1376
        return [];
1377
    }
1378
1379
    $courses = CourseManager::get_courses_list_by_user_id($userId, true);
1380
1381
    if (!empty($where_condition)) {
1382
        $where_condition = ' AND '.$where_condition;
1383
    }
1384
1385
    if (!in_array($direction, ['asc', 'desc'])) {
1386
        $direction = 'desc';
1387
    }
1388
1389
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1390
    $start = (int) $start;
1391
    $limit = (int) $limit;
1392
    $courseQuery = [];
1393
    $courseList = [];
1394
    foreach ($courses as $course) {
1395
        $course_id = $course['real_id'];
1396
        $courseInfo = api_get_course_info_by_id($course_id);
1397
        $session_id = isset($course['session_id']) ? $course['session_id'] : 0;
1398
        $conditionSession = api_get_session_condition($session_id, true, false, 'w.session_id');
1399
        $parentCondition = '';
1400
        if ($withResults) {
1401
            $parentCondition = 'AND ww.parent_id is NOT NULL';
1402
        }
1403
        $courseQuery[] = " (w.c_id = $course_id $conditionSession $parentCondition )";
1404
        $courseList[$course_id] = $courseInfo;
1405
    }
1406
1407
    $courseQueryToString = implode(' OR ', $courseQuery);
1408
1409
    if ($getCount) {
1410
        if (empty($courseQuery)) {
1411
            return 0;
1412
        }
1413
        $select = 'SELECT count(DISTINCT(w.id)) as count ';
1414
    } else {
1415
        if (empty($courseQuery)) {
1416
            return [];
1417
        }
1418
        $select = 'SELECT DISTINCT
1419
                        w.url,
1420
                        w.id,
1421
                        w.c_id,
1422
                        w.session_id,
1423
                        a.expires_on,
1424
                        a.ends_on,
1425
                        a.enable_qualification,
1426
                        w.qualification,
1427
                        a.publication_id';
1428
    }
1429
1430
    $checkSentWork = " LEFT JOIN $workTable ww
1431
                       ON (ww.c_id = w.c_id AND ww.parent_id = w.id AND ww.user_id = $userId ) ";
1432
    $where = ' AND ww.url IS NULL ';
1433
    $expirationCondition = " AND (a.expires_on IS NULL OR a.expires_on > '".api_get_utc_datetime()."') ";
1434
    if ($withResults) {
1435
        $where = '';
1436
        $checkSentWork = " LEFT JOIN $workTable ww
1437
                           ON (
1438
                            ww.c_id = w.c_id AND
1439
                            ww.parent_id = w.id AND
1440
                            ww.user_id = $userId AND
1441
                            a.expires_on IS NULL AND
1442
                            ww.parent_id is NOT NULL
1443
                        ) ";
1444
        $expirationCondition = " OR (
1445
                ww.parent_id is NULL AND
1446
                a.expires_on IS NOT NULL AND
1447
                a.expires_on < '".api_get_utc_datetime()."'
1448
            ) ";
1449
    }
1450
1451
    $sql = "$select
1452
            FROM $workTable w
1453
            LEFT JOIN $workTableAssignment a
1454
            ON (a.publication_id = w.id AND a.c_id = w.c_id)
1455
            $checkSentWork
1456
            WHERE
1457
                w.parent_id = 0 AND
1458
                w.active IN (1, 0) AND
1459
                ($courseQueryToString)
1460
                $where_condition
1461
                $expirationCondition
1462
                $where
1463
            ";
1464
1465
    $sql .= " ORDER BY $column $direction ";
1466
1467
    if (!empty($start) && !empty($limit)) {
1468
        $sql .= " LIMIT $start, $limit";
1469
    }
1470
1471
    $result = Database::query($sql);
1472
1473
    if ($getCount) {
1474
        $row = Database::fetch_array($result);
1475
1476
        if ($row) {
1477
            return (int) $row['count'];
1478
        }
1479
1480
        return 0;
1481
    }
1482
1483
    $works = [];
1484
    while ($work = Database::fetch_array($result, 'ASSOC')) {
1485
        $courseId = $work['c_id'];
1486
        $courseInfo = $courseList[$work['c_id']];
1487
        $courseCode = $courseInfo['code'];
1488
        $sessionId = $work['session_id'];
1489
1490
        $cidReq = api_get_cidreq_params($courseCode, $sessionId);
1491
        $url = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.$cidReq;
1492
        $isSubscribed = userIsSubscribedToWork($userId, $work['id'], $courseId);
1493
        if ($isSubscribed == false) {
1494
            continue;
1495
        }
1496
1497
        $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $sessionId);
1498
1499
        if ($visibility != 1) {
1500
            continue;
1501
        }
1502
1503
        $work['type'] = Display::return_icon('work.png');
1504
        $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
1505
1506
        if (empty($work['title'])) {
1507
            $work['title'] = basename($work['url']);
1508
        }
1509
1510
        if ($withResults) {
1511
            $whereCondition = " AND u.user_id = $userId ";
1512
            $workList = get_work_user_list(
1513
                0,
1514
                1000,
1515
                null,
1516
                null,
1517
                $work['id'],
1518
                $whereCondition,
1519
                null,
1520
                false,
1521
                $courseId,
1522
                $sessionId
1523
            );
1524
1525
            $count = getTotalWorkComment($workList, $courseInfo);
1526
            $lastWork = getLastWorkStudentFromParentByUser($userId, $work, $courseInfo);
1527
1528
            if (!is_null($count) && !empty($count)) {
1529
                $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$lastWork['id'].'&'.$cidReq;
1530
1531
                $feedback = '&nbsp;'.Display::url(
1532
                        Display::returnFontAwesomeIcon('comments-o'),
1533
                        $urlView,
1534
                        ['title' => get_lang('View')]
1535
                    );
1536
1537
                $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info').$feedback;
1538
            }
1539
1540
            if (!empty($lastWork)) {
1541
                $work['last_upload'] = (!empty($lastWork['qualification'])) ? $lastWork['qualification_rounded'].' - ' : '';
1542
                $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
1543
            }
1544
        }
1545
1546
        $work['title'] = Display::url($work['title'], $url.'&id='.$work['id']);
1547
        $works[] = $work;
1548
    }
1549
1550
    return $works;
1551
}
1552
1553
/**
1554
 * @param int    $start
1555
 * @param int    $limit
1556
 * @param string $column
1557
 * @param string $direction
1558
 * @param string $where_condition
1559
 * @param bool   $getCount
1560
 *
1561
 * @return array
1562
 */
1563
function getWorkListTeacher(
1564
    $start,
1565
    $limit,
1566
    $column,
1567
    $direction,
1568
    $where_condition,
1569
    $getCount = false
1570
) {
1571
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1572
    $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1573
1574
    $courseInfo = api_get_course_info();
1575
    $course_id = api_get_course_int_id();
1576
    $session_id = api_get_session_id();
1577
    $condition_session = api_get_session_condition($session_id);
1578
    $group_id = api_get_group_id();
1579
    $groupIid = 0;
1580
    if ($group_id) {
1581
        $groupInfo = GroupManager::get_group_properties($group_id);
1582
        $groupIid = $groupInfo['iid'];
1583
    }
1584
    $groupIid = (int) $groupIid;
1585
1586
    $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
1587
    if (!in_array($direction, ['asc', 'desc'])) {
1588
        $direction = 'desc';
1589
    }
1590
    if (!empty($where_condition)) {
1591
        $where_condition = ' AND '.$where_condition;
1592
    }
1593
1594
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1595
    $start = (int) $start;
1596
    $limit = (int) $limit;
1597
    $works = [];
1598
1599
    // Get list from database
1600
    if ($is_allowed_to_edit) {
1601
        $active_condition = ' active IN (0, 1)';
1602
        if ($getCount) {
1603
            $select = " SELECT count(w.id) as count";
1604
        } else {
1605
            $select = " SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
1606
        }
1607
        $sql = " $select
1608
                FROM $workTable w
1609
                LEFT JOIN $workTableAssignment a
1610
                ON (a.publication_id = w.id AND a.c_id = w.c_id)
1611
                WHERE
1612
                    w.c_id = $course_id
1613
                    $condition_session AND
1614
                    $active_condition AND
1615
                    parent_id = 0 AND
1616
                    post_group_id = $groupIid
1617
                    $where_condition
1618
                ORDER BY $column $direction
1619
                LIMIT $start, $limit";
1620
1621
        $result = Database::query($sql);
1622
1623
        if ($getCount) {
1624
            $row = Database::fetch_array($result);
1625
1626
            return (int) $row['count'];
1627
        }
1628
1629
        $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
1630
        $blockEdition = api_get_configuration_value('block_student_publication_edition');
1631
        while ($work = Database::fetch_array($result, 'ASSOC')) {
1632
            $workId = $work['id'];
1633
            $work['type'] = Display::return_icon('work.png');
1634
            $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
1635
1636
            $countUniqueAttempts = getUniqueStudentAttemptsTotal(
1637
                $workId,
1638
                $group_id,
1639
                $course_id,
1640
                $session_id
1641
            );
1642
1643
            $totalUsers = getStudentSubscribedToWork(
1644
                $workId,
1645
                $course_id,
1646
                $group_id,
1647
                $session_id,
1648
                true
1649
            );
1650
1651
            $work['amount'] = Display::label(
1652
                $countUniqueAttempts.'/'.
1653
                $totalUsers,
1654
                'success'
1655
            );
1656
1657
            $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $session_id);
1658
1659
            if ($visibility == 1) {
1660
                $icon = 'visible.png';
1661
                $text = get_lang('Visible');
1662
                $action = 'invisible';
1663
                $class = '';
1664
            } else {
1665
                $icon = 'invisible.png';
1666
                $text = get_lang('Invisible');
1667
                $action = 'visible';
1668
                $class = 'muted';
1669
            }
1670
1671
            $visibilityLink = Display::url(
1672
                Display::return_icon($icon, $text, [], ICON_SIZE_SMALL),
1673
                api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action='.$action.'&'.api_get_cidreq()
1674
            );
1675
1676
            if (empty($work['title'])) {
1677
                $work['title'] = basename($work['url']);
1678
            }
1679
            $work['title'] = Display::url($work['title'], $url.'&id='.$workId, ['class' => $class]);
1680
            $work['title'] .= ' '.Display::label(get_count_work($work['id']), 'success');
1681
            $work['sent_date'] = api_get_local_time($work['sent_date']);
1682
1683
            if ($blockEdition && !api_is_platform_admin()) {
1684
                $editLink = '';
1685
            } else {
1686
                $editLink = Display::url(
1687
                    Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL),
1688
                    api_get_path(WEB_CODE_PATH).'work/edit_work.php?id='.$workId.'&'.api_get_cidreq()
1689
                );
1690
            }
1691
1692
            $correctionLink = '&nbsp;'.Display::url(
1693
                Display::return_icon('upload_package.png', get_lang('UploadCorrections'), '', ICON_SIZE_SMALL),
1694
                api_get_path(WEB_CODE_PATH).'work/upload_corrections.php?'.api_get_cidreq().'&id='.$workId
1695
            ).'&nbsp;';
1696
1697
            if ($countUniqueAttempts > 0) {
1698
                $downloadLink = Display::url(
1699
                    Display::return_icon(
1700
                        'save_pack.png',
1701
                        get_lang('Save'),
1702
                        [],
1703
                        ICON_SIZE_SMALL
1704
                    ),
1705
                    api_get_path(WEB_CODE_PATH).'work/downloadfolder.inc.php?id='.$workId.'&'.api_get_cidreq()
1706
                );
1707
            } else {
1708
                $downloadLink = Display::url(
1709
                    Display::return_icon(
1710
                        'save_pack_na.png',
1711
                        get_lang('Save'),
1712
                        [],
1713
                        ICON_SIZE_SMALL
1714
                    ),
1715
                    '#'
1716
                );
1717
            }
1718
            // Remove Delete Work Button from action List
1719
            // Because removeXSS "removes" the onClick JS Event to do the action (See model.ajax.php - Line 1639)
1720
            // But still can use the another jqgrid button to remove works (trash icon)
1721
            //
1722
            // $deleteUrl = api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action=delete_dir&'.api_get_cidreq();
1723
            // $deleteLink = '<a href="#" onclick="showConfirmationPopup(this, \'' . $deleteUrl . '\' ) " >' .
1724
            //     Display::return_icon(
1725
            //         'delete.png',
1726
            //         get_lang('Delete'),
1727
            //         [],
1728
            //         ICON_SIZE_SMALL
1729
            //     ) . '</a>';
1730
1731
            if (!api_is_allowed_to_edit()) {
1732
                // $deleteLink = null;
1733
                $editLink = null;
1734
            }
1735
            $work['actions'] = $visibilityLink.$correctionLink.$downloadLink.$editLink;
1736
            $works[] = $work;
1737
        }
1738
    }
1739
1740
    return $works;
1741
}
1742
1743
/**
1744
 * @param int    $start
1745
 * @param int    $limit
1746
 * @param string $column
1747
 * @param string $direction
1748
 * @param int    $workId
1749
 * @param int    $studentId
1750
 * @param string $whereCondition
1751
 * @param bool   $getCount
1752
 *
1753
 * @return array
1754
 */
1755
function get_work_user_list_from_documents(
1756
    $start,
1757
    $limit,
1758
    $column,
1759
    $direction,
1760
    $workId,
1761
    $studentId = null,
1762
    $whereCondition = '',
1763
    $getCount = false
1764
) {
1765
    if ($getCount) {
1766
        $select1 = ' SELECT count(u.user_id) as count ';
1767
        $select2 = ' SELECT count(u.user_id) as count ';
1768
    } else {
1769
        $select1 = ' SELECT DISTINCT
1770
                        u.firstname,
1771
                        u.lastname,
1772
                        u.user_id,
1773
                        w.title,
1774
                        w.parent_id,
1775
                        w.document_id document_id,
1776
                        w.id, qualification,
1777
                        qualificator_id,
1778
                        w.sent_date,
1779
                        w.contains_file,
1780
                        w.url
1781
                    ';
1782
        $select2 = ' SELECT DISTINCT
1783
                        u.firstname, u.lastname,
1784
                        u.user_id,
1785
                        d.title,
1786
                        w.parent_id,
1787
                        d.id document_id,
1788
                        0,
1789
                        0,
1790
                        0,
1791
                        w.sent_date,
1792
                        w.contains_file,
1793
                        w.url
1794
                    ';
1795
    }
1796
1797
    $documentTable = Database::get_course_table(TABLE_DOCUMENT);
1798
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1799
    $workRelDocument = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
1800
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
1801
1802
    $courseId = api_get_course_int_id();
1803
    $sessionId = api_get_session_id();
1804
1805
    if (empty($studentId)) {
1806
        $studentId = api_get_user_id();
1807
    }
1808
1809
    $studentId = (int) $studentId;
1810
    $workId = (int) $workId;
1811
1812
    $userCondition = " AND u.user_id = $studentId ";
1813
    $sessionCondition = api_get_session_condition($sessionId, true, false, 'w.session_id');
1814
    $workCondition = " AND w_rel.work_id = $workId";
1815
    $workParentCondition = " AND w.parent_id = $workId";
1816
1817
    $sql = "(
1818
                $select1 FROM $userTable u
1819
                INNER JOIN $workTable w
1820
                ON (u.user_id = w.user_id AND w.active IN (0, 1) AND w.filetype = 'file')
1821
                WHERE
1822
                    w.c_id = $courseId
1823
                    $userCondition
1824
                    $sessionCondition
1825
                    $whereCondition
1826
                    $workParentCondition
1827
            ) UNION (
1828
                $select2 FROM $workTable w
1829
                INNER JOIN $workRelDocument w_rel
1830
                ON (w_rel.work_id = w.id AND w.active IN (0, 1) AND w_rel.c_id = w.c_id)
1831
                INNER JOIN $documentTable d
1832
                ON (w_rel.document_id = d.id AND d.c_id = w.c_id)
1833
                INNER JOIN $userTable u ON (u.user_id = $studentId)
1834
                WHERE
1835
                    w.c_id = $courseId
1836
                    $workCondition
1837
                    $sessionCondition AND
1838
                    d.id NOT IN (
1839
                        SELECT w.document_id id
1840
                        FROM $workTable w
1841
                        WHERE
1842
                            user_id = $studentId AND
1843
                            c_id = $courseId AND
1844
                            filetype = 'file' AND
1845
                            active IN (0, 1)
1846
                            $sessionCondition
1847
                            $workParentCondition
1848
                    )
1849
            )";
1850
1851
    $start = (int) $start;
1852
    $limit = (int) $limit;
1853
1854
    $direction = in_array(strtolower($direction), ['desc', 'asc']) ? $direction : 'desc';
1855
    $column = Database::escape_string($column);
1856
1857
    if ($getCount) {
1858
        $result = Database::query($sql);
1859
        $result = Database::fetch_array($result);
1860
1861
        return $result['count'];
1862
    }
1863
1864
    $sql .= " ORDER BY $column $direction";
1865
    $sql .= " LIMIT $start, $limit";
1866
1867
    $result = Database::query($sql);
1868
1869
    $currentUserId = api_get_user_id();
1870
    $work_data = get_work_data_by_id($workId);
1871
    $qualificationExists = false;
1872
1873
    if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0) {
1874
        $qualificationExists = true;
1875
    }
1876
1877
    $urlAdd = api_get_path(WEB_CODE_PATH).'work/upload_from_template.php?'.api_get_cidreq();
1878
    $urlEdit = api_get_path(WEB_CODE_PATH).'work/edit.php?'.api_get_cidreq();
1879
    $urlDelete = api_get_path(WEB_CODE_PATH).'work/work_list.php?action=delete&'.api_get_cidreq();
1880
    $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq();
1881
    $urlDownload = api_get_path(WEB_CODE_PATH).'work/download.php?'.api_get_cidreq();
1882
1883
    $editIcon = Display::return_icon('edit.png', get_lang('Edit'));
1884
    $addIcon = Display::return_icon('add.png', get_lang('Add'));
1885
    $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'));
1886
    $viewIcon = Display::return_icon('default.png', get_lang('View'));
1887
    $saveIcon = Display::return_icon(
1888
        'save.png',
1889
        get_lang('Save'),
1890
        [],
1891
        ICON_SIZE_SMALL
1892
    );
1893
    $allowEdition = api_get_course_setting('student_delete_own_publication') == 1;
1894
1895
    $workList = [];
1896
    while ($row = Database::fetch_array($result, 'ASSOC')) {
1897
        $userId = $row['user_id'];
1898
        $documentId = $row['document_id'];
1899
        $itemId = $row['id'];
1900
        $addLinkShowed = false;
1901
1902
        if (empty($documentId)) {
1903
            $url = $urlEdit.'&item_id='.$row['id'].'&id='.$workId;
1904
            $editLink = Display::url($editIcon, $url);
1905
            if (1 != $allowEdition) {
1906
                $editLink = null;
1907
            }
1908
        } else {
1909
            $documentToWork = getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId);
1910
1911
            if (empty($documentToWork)) {
1912
                $url = $urlAdd.'&document_id='.$documentId.'&id='.$workId;
1913
                $editLink = Display::url($addIcon, $url);
1914
                $addLinkShowed = true;
1915
            } else {
1916
                $row['title'] = $documentToWork['title'];
1917
                $row['sent_date'] = $documentToWork['sent_date'];
1918
                $newWorkId = $documentToWork['id'];
1919
                $url = $urlEdit.'&item_id='.$newWorkId.'&id='.$workId;
1920
                $editLink = Display::url($editIcon, $url);
1921
1922
                if (1 != $allowEdition) {
1923
                    $editLink = '';
1924
                }
1925
            }
1926
        }
1927
1928
        $downloadLink = '';
1929
        // If URL is present then there's a file to download keep BC.
1930
        if ($row['contains_file'] || !empty($row['url'])) {
1931
            $downloadLink = Display::url($saveIcon, $urlDownload.'&id='.$row['id']).'&nbsp;';
1932
        }
1933
1934
        $viewLink = '';
1935
        if (!empty($itemId)) {
1936
            $viewLink = Display::url($viewIcon, $urlView.'&id='.$itemId);
1937
        }
1938
1939
        $deleteLink = '';
1940
        if ($allowEdition == 1 && !empty($itemId)) {
1941
            $deleteLink = Display::url($deleteIcon, $urlDelete.'&item_id='.$itemId.'&id='.$workId);
1942
        }
1943
1944
        $row['type'] = null;
1945
1946
        if ($qualificationExists) {
1947
            if (empty($row['qualificator_id'])) {
1948
                $status = Display::label(get_lang('NotRevised'), 'warning');
1949
            } else {
1950
                $status = Display::label(get_lang('Revised'), 'success');
1951
            }
1952
            $row['qualificator_id'] = $status;
1953
        }
1954
1955
        if (!empty($row['qualification'])) {
1956
            $row['qualification'] = Display::label($row['qualification'], 'info');
1957
        }
1958
1959
        if (!empty($row['sent_date'])) {
1960
            $row['sent_date'] = Display::dateToStringAgoAndLongDate($row['sent_date']);
1961
        }
1962
1963
        if ($userId == $currentUserId) {
1964
            $row['actions'] = $downloadLink.$viewLink.$editLink.$deleteLink;
1965
        }
1966
1967
        if ($addLinkShowed) {
1968
            $row['qualification'] = '';
1969
            $row['qualificator_id'] = '';
1970
        }
1971
1972
        $workList[] = $row;
1973
    }
1974
1975
    return $workList;
1976
}
1977
1978
/**
1979
 * @param int    $start
1980
 * @param int    $limit
1981
 * @param int    $column
1982
 * @param string $direction
1983
 * @param int    $work_id
1984
 * @param string $whereCondition
1985
 * @param int    $studentId
1986
 * @param bool   $getCount
1987
 * @param int    $courseId
1988
 * @param int    $sessionId
1989
 *
1990
 * @return array
1991
 */
1992
function get_work_user_list(
1993
    $start,
1994
    $limit,
1995
    $column,
1996
    $direction,
1997
    $work_id,
1998
    $whereCondition = '',
1999
    $studentId = null,
2000
    $getCount = false,
2001
    $courseId = 0,
2002
    $sessionId = 0
2003
) {
2004
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2005
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
2006
2007
    $session_id = $sessionId ? $sessionId : api_get_session_id();
2008
    $group_id = api_get_group_id();
2009
    $course_info = api_get_course_info();
2010
    $course_info = empty($course_info) ? api_get_course_info_by_id($courseId) : $course_info;
2011
    $course_id = isset($course_info['real_id']) ? $course_info['real_id'] : $courseId;
2012
2013
    $work_id = (int) $work_id;
2014
    $start = (int) $start;
2015
    $limit = (int) $limit;
2016
2017
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
2018
2019
    $compilatio_web_folder = api_get_path(WEB_CODE_PATH).'plagiarism/compilatio/';
2020
    $compilation = null;
2021
    if (api_get_configuration_value('allow_compilatio_tool')) {
2022
        $compilation = new Compilatio();
2023
    }
2024
2025
    if (!in_array($direction, ['asc', 'desc'])) {
2026
        $direction = 'desc';
2027
    }
2028
2029
    $work_data = get_work_data_by_id($work_id, $courseId, $sessionId);
2030
    $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
2031
    $condition_session = api_get_session_condition(
2032
        $session_id,
2033
        true,
2034
        false,
2035
        'work.session_id'
2036
    );
2037
2038
    $locked = api_resource_is_locked_by_gradebook(
2039
        $work_id,
2040
        LINK_STUDENTPUBLICATION,
2041
        $course_info['code']
2042
    );
2043
2044
    $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
2045
        api_get_user_id(),
2046
        $course_info
2047
    );
2048
2049
    $isDrhOfSession = !empty(SessionManager::getSessionFollowedByDrh(api_get_user_id(), $session_id));
2050
2051
    $groupIid = 0;
2052
    if ($group_id) {
2053
        $groupInfo = GroupManager::get_group_properties($group_id);
2054
        if ($groupInfo) {
2055
            $groupIid = $groupInfo['iid'];
2056
        }
2057
    }
2058
2059
    if (!empty($work_data)) {
2060
        if (!empty($group_id)) {
2061
            // set to select only messages posted by the user's group
2062
            $extra_conditions = " work.post_group_id = '".$groupIid."' ";
2063
        } else {
2064
            $extra_conditions = " (work.post_group_id = '0' OR work.post_group_id is NULL) ";
2065
        }
2066
2067
        if ($is_allowed_to_edit || $isDrhOfCourse || $isDrhOfSession) {
2068
            $extra_conditions .= ' AND work.active IN (0, 1) ';
2069
        } else {
2070
            if (isset($course_info['show_score']) &&
2071
                1 == $course_info['show_score']
2072
            ) {
2073
                $extra_conditions .= ' AND (u.user_id = '.api_get_user_id().' AND work.active IN (0, 1)) ';
2074
            } else {
2075
                $extra_conditions .= ' AND work.active IN (0, 1) ';
2076
            }
2077
        }
2078
2079
        $extra_conditions .= " AND parent_id  = $work_id ";
2080
2081
        $select = 'SELECT DISTINCT
2082
                        u.user_id,
2083
                        work.id as id,
2084
                        title as title,
2085
                        description,
2086
                        url,
2087
                        sent_date,
2088
                        contains_file,
2089
                        has_properties,
2090
                        view_properties,
2091
                        qualification,
2092
                        weight,
2093
                        allow_text_assignment,
2094
                        u.firstname,
2095
                        u.lastname,
2096
                        u.username,
2097
                        parent_id,
2098
                        accepted,
2099
                        qualificator_id,
2100
                        url_correction,
2101
                        title_correction
2102
                        ';
2103
        if ($getCount) {
2104
            $select = 'SELECT DISTINCT count(u.user_id) as count ';
2105
        }
2106
2107
        $work_assignment = get_work_assignment_by_id($work_id, $courseId);
2108
2109
        if (!empty($studentId)) {
2110
            $studentId = (int) $studentId;
2111
            $whereCondition .= " AND u.user_id = $studentId ";
2112
        }
2113
2114
        $sql = " $select
2115
                FROM $work_table work
2116
                INNER JOIN $user_table u
2117
                ON (work.user_id = u.user_id)
2118
                WHERE
2119
                    work.c_id = $course_id AND
2120
                    $extra_conditions
2121
                    $whereCondition
2122
                    $condition_session
2123
                    AND u.status != ".INVITEE."
2124
                ORDER BY $column $direction";
2125
2126
        if (!empty($start) && !empty($limit)) {
2127
            $sql .= " LIMIT $start, $limit";
2128
        }
2129
        $result = Database::query($sql);
2130
        $works = [];
2131
2132
        if ($getCount) {
2133
            $work = Database::fetch_array($result, 'ASSOC');
2134
2135
            return $work['count'];
2136
        }
2137
2138
        $url = api_get_path(WEB_CODE_PATH).'work/';
2139
        $unoconv = api_get_configuration_value('unoconv.binaries');
2140
        $loadingText = addslashes(get_lang('Loading'));
2141
        $uploadedText = addslashes(get_lang('Uploaded'));
2142
        $failsUploadText = addslashes(get_lang('UplNoFileUploaded'));
2143
        $failsUploadIcon = Display::return_icon(
2144
            'closed-circle.png',
2145
            '',
2146
            [],
2147
            ICON_SIZE_TINY
2148
        );
2149
        $saveIcon = Display::return_icon(
2150
            'save.png',
2151
            get_lang('Save'),
2152
            [],
2153
            ICON_SIZE_SMALL
2154
        );
2155
2156
        $correctionIcon = Display::return_icon(
2157
            'check-circle.png',
2158
            get_lang('Correction'),
2159
            null,
2160
            ICON_SIZE_SMALL
2161
        );
2162
2163
        $correctionIconSmall = Display::return_icon(
2164
            'check-circle.png',
2165
            get_lang('Correction'),
2166
            null,
2167
            ICON_SIZE_TINY
2168
        );
2169
2170
        $rateIcon = Display::return_icon(
2171
            'rate_work.png',
2172
            get_lang('CorrectAndRate'),
2173
            [],
2174
            ICON_SIZE_SMALL
2175
        );
2176
2177
        $blockEdition = api_get_configuration_value('block_student_publication_edition');
2178
        $blockScoreEdition = api_get_configuration_value('block_student_publication_score_edition');
2179
        $loading = Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin');
2180
        while ($work = Database::fetch_array($result, 'ASSOC')) {
2181
            $item_id = $work['id'];
2182
            $dbTitle = $work['title'];
2183
            // Get the author ID for that document from the item_property table
2184
            $is_author = false;
2185
            $can_read = false;
2186
            $owner_id = $work['user_id'];
2187
2188
            /* Because a bug found when saving items using the api_item_property_update()
2189
               the field $item_property_data['insert_user_id'] is not reliable. */
2190
            if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
2191
                $is_author = true;
2192
            }
2193
2194
            if ($course_info['show_score'] == 0) {
2195
                $can_read = true;
2196
            }
2197
2198
            $qualification_exists = false;
2199
            if (!empty($work_data['qualification']) &&
2200
                intval($work_data['qualification']) > 0
2201
            ) {
2202
                $qualification_exists = true;
2203
            }
2204
2205
            $qualification_string = '';
2206
            if ($qualification_exists) {
2207
                if ($work['qualification'] == '') {
2208
                    $qualification_string = Display::label('-');
2209
                } else {
2210
                    $qualification_string = formatWorkScore($work['qualification'], $work_data['qualification']);
2211
                }
2212
            }
2213
2214
            $work['qualification_score'] = $work['qualification'];
2215
            $add_string = '';
2216
            $time_expires = '';
2217
            if (!empty($work_assignment['expires_on'])) {
2218
                $time_expires = api_strtotime(
2219
                    $work_assignment['expires_on'],
2220
                    'UTC'
2221
                );
2222
            }
2223
2224
            if (!empty($work_assignment['expires_on']) &&
2225
                !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
2226
                $add_string = Display::label(get_lang('Expired'), 'important').' - ';
2227
            }
2228
2229
            if (($can_read && $work['accepted'] == '1') ||
2230
                ($is_author && in_array($work['accepted'], ['1', '0'])) ||
2231
                ($is_allowed_to_edit || api_is_drh())
2232
            ) {
2233
                // Firstname, lastname, username
2234
                $work['fullname'] = Display::div(
2235
                    api_get_person_name($work['firstname'], $work['lastname']),
2236
                    ['class' => 'work-name']
2237
                );
2238
                // Title
2239
                $work['title_clean'] = $work['title'];
2240
                $work['title'] = Security::remove_XSS($work['title']);
2241
                if (strlen($work['title']) > 30) {
2242
                    $short_title = substr($work['title'], 0, 27).'...';
2243
                    $work['title'] = Display::span($short_title, ['class' => 'work-title', 'title' => $work['title']]);
2244
                } else {
2245
                    $work['title'] = Display::div($work['title'], ['class' => 'work-title']);
2246
                }
2247
2248
                // Type.
2249
                $work['type'] = DocumentManager::build_document_icon_tag('file', $work['url']);
2250
2251
                // File name.
2252
                $linkToDownload = '';
2253
                // If URL is present then there's a file to download keep BC.
2254
                if ($work['contains_file'] || !empty($work['url'])) {
2255
                    $linkToDownload = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'.$saveIcon.'</a> ';
2256
                }
2257
2258
                $feedback = '';
2259
                $count = getWorkCommentCount($item_id, $course_info);
2260
                if (!is_null($count) && !empty($count)) {
2261
                    if ($qualification_exists) {
2262
                        $feedback .= ' ';
2263
                    }
2264
                    $feedback .= Display::url(
2265
                        $count.' '.Display::returnFontAwesomeIcon('comments-o'),
2266
                        $url.'view.php?'.api_get_cidreq().'&id='.$item_id
2267
                    );
2268
                }
2269
2270
                $correction = '';
2271
                $hasCorrection = '';
2272
                if (!empty($work['url_correction'])) {
2273
                    $hasCorrection = Display::url(
2274
                        $correctionIcon,
2275
                        api_get_path(WEB_CODE_PATH).'work/download.php?id='.$item_id.'&'.api_get_cidreq().'&correction=1'
2276
                    );
2277
                }
2278
2279
                if ($qualification_exists) {
2280
                    $work['qualification'] = $qualification_string.$feedback;
2281
                } else {
2282
                    $work['qualification'] = $qualification_string.$feedback.$hasCorrection;
2283
                }
2284
2285
                $work['qualification_only'] = $qualification_string;
2286
2287
                // Date.
2288
                $work_date = api_get_local_time($work['sent_date']);
2289
                $date = date_to_str_ago($work['sent_date']).' '.$work_date;
2290
                $work['formatted_date'] = $work_date.' '.$add_string;
2291
                $work['expiry_note'] = $add_string;
2292
                $work['sent_date_from_db'] = $work['sent_date'];
2293
                $work['sent_date'] = '<div class="work-date" title="'.$date.'">'.
2294
                    $add_string.' '.Display::dateToStringAgoAndLongDate($work['sent_date']).'</div>';
2295
                $work['status'] = $hasCorrection;
2296
                $work['has_correction'] = $hasCorrection;
2297
2298
                // Actions.
2299
                $action = '';
2300
                if (api_is_allowed_to_edit()) {
2301
                    if ($blockScoreEdition && !api_is_platform_admin() && !empty($work['qualification_score'])) {
2302
                        $rateLink = '';
2303
                    } else {
2304
                        $rateLink = '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2305
                            $rateIcon.'</a> ';
2306
                    }
2307
                    $action .= $rateLink;
2308
2309
                    if ($unoconv && empty($work['contains_file'])) {
2310
                        $action .= '<a
2311
                            href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=export_to_doc&item_id='.$item_id.'"
2312
                            title="'.get_lang('ExportToDoc').'" >'.
2313
                            Display::return_icon('export_doc.png', get_lang('ExportToDoc'), [], ICON_SIZE_SMALL).'</a> ';
2314
                    }
2315
2316
                    $alreadyUploaded = '';
2317
                    if (!empty($work['url_correction'])) {
2318
                        $alreadyUploaded = '<br />'.$work['title_correction'].' '.$correctionIconSmall;
2319
                    }
2320
2321
                    $correction = '
2322
                        <form
2323
                        id="file_upload_'.$item_id.'"
2324
                        class="work_correction_file_upload file_upload_small fileinput-button"
2325
                        action="'.api_get_path(WEB_AJAX_PATH).'work.ajax.php?'.api_get_cidreq().'&a=upload_correction_file&item_id='.$item_id.'"
2326
                        method="POST"
2327
                        enctype="multipart/form-data"
2328
                        >
2329
                        <div id="progress_'.$item_id.'" class="text-center button-load">
2330
                            '.addslashes(get_lang('ClickOrDropOneFileHere')).'
2331
                            '.Display::return_icon('upload_file.png', get_lang('Correction'), [], ICON_SIZE_TINY).'
2332
                            '.$alreadyUploaded.'
2333
                        </div>
2334
                        <input id="file_'.$item_id.'" type="file" name="file" class="" multiple>
2335
                        </form>
2336
                    ';
2337
2338
                    $correction .= "<script>
2339
                    $(function() {
2340
                        $('.work_correction_file_upload').each(function () {
2341
                            $(this).fileupload({
2342
                                dropZone: $(this)
2343
                            });
2344
                        });
2345
2346
                        /*$('.getSingleCompilatio').on('click', function () {
2347
                            var parts = $(this).parent().attr('id').split('id_avancement');
2348
                            getSingleCompilatio(parts[1]);
2349
                        });*/
2350
2351
                        $('#file_upload_".$item_id."').fileupload({
2352
                            add: function (e, data) {
2353
                                $('#progress_$item_id').html();
2354
                                //$('#file_$item_id').remove();
2355
                                data.context = $('#progress_$item_id').html('$loadingText <br /> <em class=\"fa fa-spinner fa-pulse fa-fw\"></em>');
2356
                                data.submit();
2357
                                $(this).removeClass('hover');
2358
                            },
2359
                            dragover: function (e, data) {
2360
                                $(this).addClass('hover');
2361
                            },
2362
                            done: function (e, data) {
2363
                                if (data._response.result.name) {
2364
                                    $('#progress_$item_id').html('$uploadedText '+data._response.result.result+'<br />'+data._response.result.name);
2365
                                } else {
2366
                                    $('#progress_$item_id').html('$failsUploadText $failsUploadIcon');
2367
                                }
2368
                                $(this).removeClass('hover');
2369
                            }
2370
                        });
2371
                        $('#file_upload_".$item_id."').on('dragleave', function (e) {
2372
                            // dragleave callback implementation
2373
                            $(this).removeClass('hover');
2374
                        });
2375
                    });
2376
                    </script>";
2377
2378
                    if ($locked) {
2379
                        if ($qualification_exists) {
2380
                            $action .= Display::return_icon(
2381
                                'edit_na.png',
2382
                                get_lang('CorrectAndRate'),
2383
                                [],
2384
                                ICON_SIZE_SMALL
2385
                            );
2386
                        } else {
2387
                            $action .= Display::return_icon('edit_na.png', get_lang('Comment'), [], ICON_SIZE_SMALL);
2388
                        }
2389
                    } else {
2390
                        if ($blockEdition && !api_is_platform_admin()) {
2391
                            $editLink = '';
2392
                        } else {
2393
                            if ($qualification_exists) {
2394
                                $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
2395
                                    ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
2396
                                        'Edit'
2397
                                    ).'"  >'.
2398
                                    Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
2399
                            } else {
2400
                                $editLink = '<a href="'.$url.'edit.php?'.api_get_cidreq(
2401
                                    ).'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang(
2402
                                        'Modify'
2403
                                    ).'">'.
2404
                                    Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>';
2405
                            }
2406
                        }
2407
                        $action .= $editLink;
2408
                    }
2409
2410
                    if ($work['contains_file']) {
2411
                        if ($locked) {
2412
                            $action .= Display::return_icon(
2413
                                'move_na.png',
2414
                                get_lang('Move'),
2415
                                [],
2416
                                ICON_SIZE_SMALL
2417
                            );
2418
                        } else {
2419
                            $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Move').'">'.
2420
                                Display::return_icon('move.png', get_lang('Move'), [], ICON_SIZE_SMALL).'</a>';
2421
                        }
2422
                    }
2423
2424
                    if ($work['accepted'] == '1') {
2425
                        $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_invisible&item_id='.$item_id.'" title="'.get_lang('Invisible').'" >'.
2426
                            Display::return_icon('visible.png', get_lang('Invisible'), [], ICON_SIZE_SMALL).'</a>';
2427
                    } else {
2428
                        $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_visible&item_id='.$item_id.'" title="'.get_lang('Visible').'" >'.
2429
                            Display::return_icon('invisible.png', get_lang('Visible'), [], ICON_SIZE_SMALL).'</a> ';
2430
                    }
2431
2432
                    if ($locked) {
2433
                        $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2434
                    } else {
2435
                        $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=delete&item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
2436
                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
2437
                    }
2438
                } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
2439
                    $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2440
                        Display::return_icon('default.png', get_lang('View'), [], ICON_SIZE_SMALL).'</a>';
2441
2442
                    if (api_get_course_setting('student_delete_own_publication') == 1) {
2443
                        if (api_is_allowed_to_session_edit(false, true)) {
2444
                            $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
2445
                                Display::return_icon('edit.png', get_lang('Comment'), [], ICON_SIZE_SMALL).'</a>';
2446
                        }
2447
                        $action .= ' <a href="'.$url.'work_list.php?'.api_get_cidreq().'&action=delete&item_id='.$item_id.'&id='.$work['parent_id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'"  >'.
2448
                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
2449
                    }
2450
                } else {
2451
                    $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2452
                        Display::return_icon('default.png', get_lang('View'), [], ICON_SIZE_SMALL).'</a>';
2453
                }
2454
2455
                // Status.
2456
                if (empty($work['qualificator_id'])) {
2457
                    $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
2458
                } else {
2459
                    $qualificator_id = Display::label(get_lang('Revised'), 'success');
2460
                }
2461
                $work['qualificator_id'] = $qualificator_id.' '.$hasCorrection;
2462
                $work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>';
2463
                $work['correction'] = $correction;
2464
2465
                if (!empty($compilation)) {
2466
                    $compilationId = $compilation->getCompilatioId($item_id, $course_id);
2467
                    if ($compilationId) {
2468
                        $actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'>
2469
                            ".$loading.'&nbsp;'.get_lang('CompilatioConnectionWithServer').'</div>';
2470
                    } else {
2471
                        $workDirectory = api_get_path(SYS_COURSE_PATH).$course_info['directory'];
2472
                        if (!Compilatio::verifiFileType($dbTitle)) {
2473
                            $actionCompilatio = get_lang('FileFormatNotSupported');
2474
                        } elseif (filesize($workDirectory.'/'.$work['url']) > $compilation->getMaxFileSize()) {
2475
                            $sizeFile = round(filesize($workDirectory.'/'.$work['url']) / 1000000);
2476
                            $actionCompilatio = get_lang('UplFileTooBig').': '.format_file_size($sizeFile).'<br />';
2477
                        } else {
2478
                            $actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'>";
2479
                            $actionCompilatio .= Display::url(
2480
                                get_lang('CompilatioAnalysis'),
2481
                                'javascript:void(0)',
2482
                                [
2483
                                    'class' => 'getSingleCompilatio btn btn-primary btn-xs',
2484
                                    'onclick' => "getSingleCompilatio($item_id);",
2485
                                ]
2486
                            );
2487
                            $actionCompilatio .= get_lang('CompilatioWithCompilatio');
2488
                        }
2489
                    }
2490
                    $work['compilatio'] = $actionCompilatio;
2491
                }
2492
                $works[] = $work;
2493
            }
2494
        }
2495
2496
        return $works;
2497
    }
2498
}
2499
2500
/**
2501
 * Send reminder to users who have not given the task.
2502
 *
2503
 * @param int
2504
 *
2505
 * @return array
2506
 *
2507
 * @author cvargas [email protected] cfasanando, [email protected]
2508
 */
2509
function send_reminder_users_without_publication($task_data)
2510
{
2511
    $_course = api_get_course_info();
2512
    $task_id = $task_data['id'];
2513
    $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
2514
    $subject = '['.api_get_setting('siteName').'] ';
2515
2516
    // The body can be as long as you wish, and any combination of text and variables
2517
    $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
2518
    $content .= get_lang('WorkName').' : '.$task_title."\n";
2519
    $list_users = get_list_users_without_publication($task_id);
2520
    $mails_sent_to = [];
2521
    foreach ($list_users as $user) {
2522
        $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
2523
        $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]).", \n\n";
2524
        $body = $dear_line.$content;
2525
        MessageManager::send_message($user[3], $subject, $body);
2526
        $mails_sent_to[] = $name_user;
2527
    }
2528
2529
    return $mails_sent_to;
2530
}
2531
2532
/**
2533
 * @param int $workId    The work ID
2534
 * @param int $courseId  The course ID
2535
 * @param int $sessionId Optional. The session ID
2536
 */
2537
function sendEmailToDrhOnHomeworkCreation($workId, $courseId, $sessionId = 0)
2538
{
2539
    $courseInfo = api_get_course_info_by_id($courseId);
2540
    $assignment = get_work_assignment_by_id($workId, $courseId);
2541
    $work = get_work_data_by_id($workId, $courseId, $sessionId);
2542
    $workInfo = array_merge($assignment, $work);
2543
2544
    if (empty($sessionId)) {
2545
        $students = CourseManager::get_student_list_from_course_code($courseInfo['code']);
2546
    } else {
2547
        $students = CourseManager::get_student_list_from_course_code($courseInfo['code'], true, $sessionId);
2548
    }
2549
2550
    $bodyView = new Template(null, false, false, false, false, false);
2551
2552
    foreach ($students as $student) {
2553
        $studentInfo = api_get_user_info($student['user_id']);
2554
        if (empty($studentInfo)) {
2555
            continue;
2556
        }
2557
2558
        $hrms = UserManager::getDrhListFromUser($student['id']);
2559
        foreach ($hrms as $hrm) {
2560
            $hrmName = api_get_person_name($hrm['firstname'], $hrm['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
2561
2562
            $bodyView->assign('hrm_name', $hrmName);
2563
            $bodyView->assign('student', $studentInfo);
2564
            $bodyView->assign('course', $courseInfo);
2565
            $bodyView->assign('course_link', api_get_course_url($courseInfo['code'], $sessionId));
2566
            $bodyView->assign('work', $workInfo);
2567
2568
            $bodyTemplate = $bodyView->get_template('mail/new_work_alert_hrm.tpl');
2569
2570
            MessageManager::send_message(
2571
                $hrm['id'],
2572
                sprintf(
2573
                    get_lang('StudentXHasBeenAssignedNewWorkInCourseY'),
2574
                    $student['firstname'],
2575
                    $courseInfo['title']
2576
                ),
2577
                $bodyView->fetch($bodyTemplate)
2578
            );
2579
        }
2580
    }
2581
}
2582
2583
/**
2584
 * Sends an email to the students of a course when a homework is created.
2585
 *
2586
 * @param int $workId
2587
 * @param int $courseId
2588
 * @param int $sessionId
2589
 *
2590
 * @author Guillaume Viguier <[email protected]>
2591
 * @author Julio Montoya <[email protected]> Adding session support - 2011
2592
 */
2593
function sendEmailToStudentsOnHomeworkCreation($workId, $courseId, $sessionId = 0)
2594
{
2595
    $courseInfo = api_get_course_info_by_id($courseId);
2596
    $courseCode = $courseInfo['code'];
2597
    // Get the students of the course
2598
    if (empty($sessionId)) {
2599
        $students = CourseManager::get_student_list_from_course_code($courseCode);
2600
    } else {
2601
        $students = CourseManager::get_student_list_from_course_code($courseCode, true, $sessionId);
2602
    }
2603
    $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('HomeworkCreated');
2604
    $currentUser = api_get_user_info(api_get_user_id());
2605
    if (!empty($students)) {
2606
        foreach ($students as $student) {
2607
            $user_info = api_get_user_info($student['user_id']);
2608
            if (!empty($user_info)) {
2609
                $link = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId;
2610
                $emailbody = get_lang('Dear')." ".$user_info['complete_name'].",\n\n";
2611
                $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$courseCode.". "."\n\n".
2612
                    '<a href="'.$link.'">'.get_lang('PleaseCheckHomeworkPage').'</a>';
2613
                $emailbody .= "\n\n".$currentUser['complete_name'];
2614
2615
                $additionalParameters = [
2616
                    'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE,
2617
                    'userId' => $student['user_id'],
2618
                    'courseTitle' => $courseCode,
2619
                    'link' => $link,
2620
                ];
2621
2622
                MessageManager::send_message_simple(
2623
                    $student['user_id'],
2624
                    $emailsubject,
2625
                    $emailbody,
2626
                    null,
2627
                    false,
2628
                    false,
2629
                    $additionalParameters,
2630
                    false
2631
                );
2632
            }
2633
        }
2634
    }
2635
}
2636
2637
/**
2638
 * @param string $url
2639
 *
2640
 * @return bool
2641
 */
2642
function is_work_exist_by_url($url)
2643
{
2644
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2645
    $url = Database::escape_string($url);
2646
    $sql = "SELECT id FROM $table WHERE url='$url'";
2647
    $result = Database::query($sql);
2648
    if (Database::num_rows($result) > 0) {
2649
        $row = Database::fetch_row($result);
2650
        if (empty($row)) {
2651
            return false;
2652
        } else {
2653
            return true;
2654
        }
2655
    } else {
2656
        return false;
2657
    }
2658
}
2659
2660
/**
2661
 * Check if a user is the author of a work document.
2662
 *
2663
 * @param int $itemId
2664
 * @param int $userId
2665
 * @param int $courseId
2666
 * @param int $sessionId
2667
 *
2668
 * @return bool
2669
 */
2670
function user_is_author($itemId, $userId = null, $courseId = 0, $sessionId = 0)
2671
{
2672
    $userId = (int) $userId;
2673
2674
    if (empty($itemId)) {
2675
        return false;
2676
    }
2677
2678
    if (empty($userId)) {
2679
        $userId = api_get_user_id();
2680
    }
2681
2682
    $isAuthor = false;
2683
    $is_allowed_to_edit = api_is_allowed_to_edit();
2684
2685
    if ($is_allowed_to_edit) {
2686
        $isAuthor = true;
2687
    } else {
2688
        if (empty($courseId)) {
2689
            $courseId = api_get_course_int_id();
2690
        }
2691
        if (empty($sessionId)) {
2692
            $sessionId = api_get_session_id();
2693
        }
2694
2695
        $data = api_get_item_property_info($courseId, 'work', $itemId, $sessionId);
2696
        if ($data['insert_user_id'] == $userId) {
2697
            $isAuthor = true;
2698
        }
2699
2700
        $workData = get_work_data_by_id($itemId);
2701
        if ($workData['user_id'] == $userId) {
2702
            $isAuthor = true;
2703
        }
2704
    }
2705
2706
    if (!$isAuthor) {
2707
        return false;
2708
    }
2709
2710
    return $isAuthor;
2711
}
2712
2713
/**
2714
 * Get list of users who have not given the task.
2715
 *
2716
 * @param int
2717
 * @param int
2718
 *
2719
 * @return array
2720
 *
2721
 * @author cvargas
2722
 * @author Julio Montoya <[email protected]> Fixing query
2723
 */
2724
function get_list_users_without_publication($task_id, $studentId = 0)
2725
{
2726
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2727
    $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
2728
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2729
    $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2730
2731
    $users = getAllUserToWork($task_id, api_get_course_int_id());
2732
    $users = array_column($users, 'user_id');
2733
2734
    // Condition for the session
2735
    $session_id = api_get_session_id();
2736
    $course_id = api_get_course_int_id();
2737
    $task_id = (int) $task_id;
2738
    $sessionCondition = api_get_session_condition($session_id);
2739
2740
    if (0 == $session_id) {
2741
        $sql = "SELECT user_id as id FROM $work_table
2742
                WHERE
2743
                    c_id = $course_id AND
2744
                    parent_id = '$task_id' AND
2745
                    active IN (0, 1)";
2746
    } else {
2747
        $sql = "SELECT user_id as id FROM $work_table
2748
                WHERE
2749
                    c_id = $course_id AND
2750
                    parent_id = '$task_id' $sessionCondition AND
2751
                    active IN (0, 1)";
2752
    }
2753
2754
    $result = Database::query($sql);
2755
    $users_with_tasks = [];
2756
    while ($row = Database::fetch_array($result)) {
2757
        $users_with_tasks[] = $row['id'];
2758
    }
2759
2760
    if (0 == $session_id) {
2761
        $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
2762
                      FROM $table_course_user AS cu, $table_user AS u
2763
                      WHERE u.status != 1 and cu.c_id='".$course_id."' AND u.user_id = cu.user_id";
2764
    } else {
2765
        $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
2766
                      FROM $session_course_rel_user AS cu, $table_user AS u
2767
                      WHERE
2768
                        u.status != 1 AND
2769
                        cu.c_id='".$course_id."' AND
2770
                        u.user_id = cu.user_id AND
2771
                        cu.session_id = '".$session_id."'";
2772
    }
2773
2774
    if (!empty($studentId)) {
2775
        $sql_users .= ' AND u.user_id = '.(int) $studentId;
2776
    }
2777
2778
    $group_id = api_get_group_id();
2779
    $new_group_user_list = [];
2780
2781
    if ($group_id) {
2782
        $groupInfo = GroupManager::get_group_properties($group_id);
2783
        $group_user_list = GroupManager::get_subscribed_users($groupInfo);
2784
        if (!empty($group_user_list)) {
2785
            foreach ($group_user_list as $group_user) {
2786
                $new_group_user_list[] = $group_user['user_id'];
2787
            }
2788
        }
2789
    }
2790
2791
    $result_users = Database::query($sql_users);
2792
    $users_without_tasks = [];
2793
    while ($rowUsers = Database::fetch_array($result_users)) {
2794
        $userId = $rowUsers['user_id'];
2795
        if (in_array($userId, $users_with_tasks)) {
2796
            continue;
2797
        }
2798
2799
        if ($group_id && !in_array($userId, $new_group_user_list)) {
2800
            continue;
2801
        }
2802
2803
        if (!empty($users)) {
2804
            if (!in_array($userId, $users)) {
2805
                continue;
2806
            }
2807
        }
2808
2809
        $row_users = [];
2810
        $row_users[0] = $rowUsers['lastname'];
2811
        $row_users[1] = $rowUsers['firstname'];
2812
        $row_users[2] = Display::encrypted_mailto_link($rowUsers['email']);
2813
        $row_users[3] = $userId;
2814
        $users_without_tasks[] = $row_users;
2815
    }
2816
2817
    return $users_without_tasks;
2818
}
2819
2820
/**
2821
 * Display list of users who have not given the task.
2822
 *
2823
 * @param int task id
2824
 * @param int $studentId
2825
 *
2826
 * @author cvargas [email protected] cfasanando, [email protected]
2827
 * @author Julio Montoya <[email protected]> Fixes
2828
 */
2829
function display_list_users_without_publication($task_id, $studentId = null)
2830
{
2831
    $origin = api_get_origin();
2832
    $table_header[] = [get_lang('LastName'), true];
2833
    $table_header[] = [get_lang('FirstName'), true];
2834
    $table_header[] = [get_lang('Email'), true];
2835
2836
    $data = get_list_users_without_publication($task_id);
2837
2838
    $sorting_options = [];
2839
    $sorting_options['column'] = 1;
2840
    $paging_options = [];
2841
    $my_params = [];
2842
2843
    if (isset($_GET['edit_dir'])) {
2844
        $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
2845
    }
2846
    if (isset($_GET['list'])) {
2847
        $my_params['list'] = Security::remove_XSS($_GET['list']);
2848
    }
2849
    $my_params['origin'] = $origin;
2850
    $my_params['id'] = (int) ($_GET['id']);
2851
2852
    //$column_show
2853
    $column_show[] = 1;
2854
    $column_show[] = 1;
2855
    $column_show[] = 1;
2856
    Display::display_sortable_config_table(
2857
        'work',
2858
        $table_header,
2859
        $data,
2860
        $sorting_options,
2861
        $paging_options,
2862
        $my_params,
2863
        $column_show
2864
    );
2865
}
2866
2867
/**
2868
 * @param int $documentId
2869
 * @param int $workId
2870
 * @param int $courseId
2871
 */
2872
function addDocumentToWork($documentId, $workId, $courseId)
2873
{
2874
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2875
    $params = [
2876
        'document_id' => $documentId,
2877
        'work_id' => $workId,
2878
        'c_id' => $courseId,
2879
    ];
2880
    Database::insert($table, $params);
2881
}
2882
2883
/**
2884
 * @param int $documentId
2885
 * @param int $workId
2886
 * @param int $courseId
2887
 *
2888
 * @return array
2889
 */
2890
function getDocumentToWork($documentId, $workId, $courseId)
2891
{
2892
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2893
    $params = [
2894
        'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
2895
    ];
2896
2897
    return Database::select('*', $table, ['where' => $params]);
2898
}
2899
2900
/**
2901
 * @param int $documentId
2902
 * @param int $workId
2903
 * @param int $courseId
2904
 * @param int $sessionId
2905
 * @param int $userId
2906
 * @param int $active
2907
 *
2908
 * @return array
2909
 */
2910
function getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId, $active = 1)
2911
{
2912
    $workRel = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2913
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2914
2915
    $documentId = (int) $documentId;
2916
    $workId = (int) $workId;
2917
    $courseId = (int) $courseId;
2918
    $userId = (int) $userId;
2919
    $sessionId = (int) $sessionId;
2920
    $active = (int) $active;
2921
    $sessionCondition = api_get_session_condition($sessionId);
2922
2923
    $sql = "SELECT w.* FROM $work w
2924
            INNER JOIN $workRel rel
2925
            ON (w.parent_id = rel.work_id)
2926
            WHERE
2927
                w.document_id = $documentId AND
2928
                w.parent_id = $workId AND
2929
                w.c_id = $courseId
2930
                $sessionCondition AND
2931
                user_id = $userId AND
2932
                active = $active
2933
            ";
2934
2935
    $result = Database::query($sql);
2936
    $workInfo = [];
2937
    if (Database::num_rows($result)) {
2938
        $workInfo = Database::fetch_array($result, 'ASSOC');
2939
    }
2940
2941
    return $workInfo;
2942
}
2943
2944
/**
2945
 * @param int $workId
2946
 * @param int $courseId
2947
 *
2948
 * @return array
2949
 */
2950
function getAllDocumentToWork($workId, $courseId)
2951
{
2952
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2953
    $params = [
2954
        'work_id = ? and c_id = ?' => [$workId, $courseId],
2955
    ];
2956
2957
    return Database::select('*', $table, ['where' => $params]);
2958
}
2959
2960
/**
2961
 * @param int $documentId
2962
 * @param int $workId
2963
 * @param int $courseId
2964
 */
2965
function deleteDocumentToWork($documentId, $workId, $courseId)
2966
{
2967
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2968
    $params = [
2969
        'document_id = ? and work_id = ? and c_id = ?' => [$documentId, $workId, $courseId],
2970
    ];
2971
    Database::delete($table, $params);
2972
}
2973
2974
/**
2975
 * @param int $userId
2976
 * @param int $workId
2977
 * @param int $courseId
2978
 */
2979
function addUserToWork($userId, $workId, $courseId)
2980
{
2981
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
2982
    $params = [
2983
        'user_id' => $userId,
2984
        'work_id' => $workId,
2985
        'c_id' => $courseId,
2986
    ];
2987
    Database::insert($table, $params);
2988
}
2989
2990
/**
2991
 * @param int $userId
2992
 * @param int $workId
2993
 * @param int $courseId
2994
 *
2995
 * @return array
2996
 */
2997
function getUserToWork($userId, $workId, $courseId)
2998
{
2999
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
3000
    $params = [
3001
        'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
3002
    ];
3003
3004
    return Database::select('*', $table, ['where' => $params]);
3005
}
3006
3007
/**
3008
 * @param int  $workId
3009
 * @param int  $courseId
3010
 * @param bool $getCount
3011
 *
3012
 * @return array|int
3013
 */
3014
function getAllUserToWork($workId, $courseId, $getCount = false)
3015
{
3016
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
3017
    $params = [
3018
        'work_id = ? and c_id = ?' => [$workId, $courseId],
3019
    ];
3020
    if ($getCount) {
3021
        $count = 0;
3022
        $result = Database::select(
3023
            'count(user_id) as count',
3024
            $table,
3025
            ['where' => $params],
3026
            'simple'
3027
        );
3028
        if (!empty($result)) {
3029
            $count = (int) ($result['count']);
3030
        }
3031
3032
        return $count;
3033
    } else {
3034
        return Database::select('*', $table, ['where' => $params]);
3035
    }
3036
}
3037
3038
/**
3039
 * @param int $userId
3040
 * @param int $workId
3041
 * @param int $courseId
3042
 */
3043
function deleteUserToWork($userId, $workId, $courseId)
3044
{
3045
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
3046
    $params = [
3047
        'user_id = ? and work_id = ? and c_id = ?' => [$userId, $workId, $courseId],
3048
    ];
3049
    Database::delete($table, $params);
3050
}
3051
3052
/**
3053
 * @param int $userId
3054
 * @param int $workId
3055
 * @param int $courseId
3056
 *
3057
 * @return bool
3058
 */
3059
function userIsSubscribedToWork($userId, $workId, $courseId)
3060
{
3061
    $subscribedUsers = getAllUserToWork($workId, $courseId);
3062
3063
    if (empty($subscribedUsers)) {
3064
        return true;
3065
    } else {
3066
        $subscribedUsersList = [];
3067
        foreach ($subscribedUsers as $item) {
3068
            $subscribedUsersList[] = $item['user_id'];
3069
        }
3070
        if (in_array($userId, $subscribedUsersList)) {
3071
            return true;
3072
        }
3073
    }
3074
3075
    return false;
3076
}
3077
3078
/**
3079
 * Get the list of students that have to submit their work.
3080
 *
3081
 * @param int  $workId    The internal ID of the assignment
3082
 * @param int  $courseId  The course ID
3083
 * @param int  $groupId   The group ID, if any
3084
 * @param int  $sessionId The session ID, if any
3085
 * @param bool $getCount  Whether we want just the amount or the full result
3086
 *
3087
 * @return array|int An integer (if we just asked for the count) or an array of users
3088
 */
3089
function getStudentSubscribedToWork(
3090
    $workId,
3091
    $courseId,
3092
    $groupId = null,
3093
    $sessionId = null,
3094
    $getCount = false
3095
) {
3096
    $usersInWork = null;
3097
    $usersInCourse = null;
3098
3099
    if (empty($groupId)) {
3100
        $courseInfo = api_get_course_info_by_id($courseId);
3101
        $status = STUDENT;
3102
        if (!empty($sessionId)) {
3103
            $status = 0;
3104
        }
3105
        $usersInCourse = CourseManager::get_user_list_from_course_code(
3106
            $courseInfo['code'],
3107
            $sessionId,
3108
            null,
3109
            null,
3110
            $status,
3111
            $getCount
3112
        );
3113
    } else {
3114
        $usersInCourse = GroupManager::get_users(
3115
            $groupId,
3116
            false,
3117
            null,
3118
            null,
3119
            $getCount,
3120
            $courseId
3121
        );
3122
    }
3123
3124
    $usersInWork = getAllUserToWork($workId, $courseId, $getCount);
3125
3126
    if (empty($usersInWork)) {
3127
        return $usersInCourse;
3128
    } else {
3129
        return $usersInWork;
3130
    }
3131
}
3132
3133
/**
3134
 * @param int  $userId
3135
 * @param int  $workId
3136
 * @param int  $courseId
3137
 * @param bool $forceAccessForCourseAdmins
3138
 *
3139
 * @return bool
3140
 */
3141
function allowOnlySubscribedUser($userId, $workId, $courseId, $forceAccessForCourseAdmins = false)
3142
{
3143
    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
3144
        return true;
3145
    }
3146
3147
    if ($forceAccessForCourseAdmins) {
3148
        if (api_is_course_admin() || api_is_coach()) {
3149
            return true;
3150
        }
3151
    }
3152
3153
    return userIsSubscribedToWork($userId, $workId, $courseId);
3154
}
3155
3156
/**
3157
 * @param int   $workId
3158
 * @param array $courseInfo
3159
 * @param int   $documentId
3160
 *
3161
 * @return array
3162
 */
3163
function getDocumentTemplateFromWork($workId, $courseInfo, $documentId)
3164
{
3165
    $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
3166
    if (!empty($documents)) {
3167
        foreach ($documents as $doc) {
3168
            if ($documentId != $doc['document_id']) {
3169
                continue;
3170
            }
3171
            $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
3172
            $fileInfo = pathinfo($docData['path']);
3173
            if ('html' == $fileInfo['extension']) {
3174
                if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
3175
                    $docData['file_content'] = file_get_contents($docData['absolute_path']);
3176
3177
                    return $docData;
3178
                }
3179
            }
3180
        }
3181
    }
3182
3183
    return [];
3184
}
3185
3186
/**
3187
 * @param int   $workId
3188
 * @param array $courseInfo
3189
 *
3190
 * @return string
3191
 */
3192
function getAllDocumentsFromWorkToString($workId, $courseInfo)
3193
{
3194
    $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
3195
    $content = null;
3196
    if (!empty($documents)) {
3197
        $content .= '<ul class="nav nav-list well">';
3198
        $content .= '<li class="nav-header">'.get_lang('Documents').'</li>';
3199
        foreach ($documents as $doc) {
3200
            $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
3201
            if ($docData) {
3202
                $content .= '<li><a class="link_to_download" target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
3203
            }
3204
        }
3205
        $content .= '</ul><br />';
3206
    }
3207
3208
    return $content;
3209
}
3210
3211
/**
3212
 * Returns fck editor toolbar.
3213
 *
3214
 * @return array
3215
 */
3216
function getWorkDescriptionToolbar()
3217
{
3218
    return [
3219
        'ToolbarStartExpanded' => 'true',
3220
        'ToolbarSet' => 'Work',
3221
        'Width' => '100%',
3222
        'Height' => '400',
3223
    ];
3224
}
3225
3226
/**
3227
 * @param array $work
3228
 *
3229
 * @return array
3230
 */
3231
function getWorkComments($work)
3232
{
3233
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3234
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
3235
3236
    $courseId = (int) $work['c_id'];
3237
    $workId = (int) $work['id'];
3238
3239
    if (empty($courseId) || empty($workId)) {
3240
        return [];
3241
    }
3242
3243
    $sql = "SELECT
3244
                c.id,
3245
                c.user_id
3246
            FROM $commentTable c
3247
            INNER JOIN $userTable u
3248
            ON (u.id = c.user_id)
3249
            WHERE c_id = $courseId AND work_id = $workId
3250
            ORDER BY sent_at
3251
            ";
3252
    $result = Database::query($sql);
3253
    $comments = Database::store_result($result, 'ASSOC');
3254
    if (!empty($comments)) {
3255
        foreach ($comments as &$comment) {
3256
            $userInfo = api_get_user_info($comment['user_id']);
3257
            $comment['picture'] = $userInfo['avatar'];
3258
            $comment['complete_name'] = $userInfo['complete_name_with_username'];
3259
            $commentInfo = getWorkComment($comment['id']);
3260
            if (!empty($commentInfo)) {
3261
                $comment = array_merge($comment, $commentInfo);
3262
            }
3263
        }
3264
    }
3265
3266
    return $comments;
3267
}
3268
3269
/**
3270
 * Get total score from a work list.
3271
 *
3272
 * @param $workList
3273
 *
3274
 * @return int|null
3275
 */
3276
function getTotalWorkScore($workList)
3277
{
3278
    $count = 0;
3279
    foreach ($workList as $data) {
3280
        $count += $data['qualification_score'];
3281
    }
3282
3283
    return $count;
3284
}
3285
3286
/**
3287
 * Get comment count from a work list (docs sent by students).
3288
 *
3289
 * @param array $workList
3290
 * @param array $courseInfo
3291
 *
3292
 * @return int|null
3293
 */
3294
function getTotalWorkComment($workList, $courseInfo = [])
3295
{
3296
    if (empty($courseInfo)) {
3297
        $courseInfo = api_get_course_info();
3298
    }
3299
3300
    $count = 0;
3301
    foreach ($workList as $data) {
3302
        $count += getWorkCommentCount($data['id'], $courseInfo);
3303
    }
3304
3305
    return $count;
3306
}
3307
3308
/**
3309
 * Get comment count for a specific work sent by a student.
3310
 *
3311
 * @param int   $id
3312
 * @param array $courseInfo
3313
 *
3314
 * @return int
3315
 */
3316
function getWorkCommentCount($id, $courseInfo = [])
3317
{
3318
    if (empty($courseInfo)) {
3319
        $courseInfo = api_get_course_info();
3320
    }
3321
3322
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3323
    $id = (int) $id;
3324
3325
    $sql = "SELECT count(*) as count
3326
            FROM $commentTable
3327
            WHERE work_id = $id AND c_id = ".$courseInfo['real_id'];
3328
3329
    $result = Database::query($sql);
3330
    if (Database::num_rows($result)) {
3331
        $comment = Database::fetch_array($result);
3332
3333
        return $comment['count'];
3334
    }
3335
3336
    return 0;
3337
}
3338
3339
/**
3340
 * Get comment count for a specific parent.
3341
 *
3342
 * @param int   $parentId
3343
 * @param array $courseInfo
3344
 * @param int   $sessionId
3345
 *
3346
 * @return int
3347
 */
3348
function getWorkCommentCountFromParent(
3349
    $parentId,
3350
    $courseInfo = [],
3351
    $sessionId = 0
3352
) {
3353
    if (empty($courseInfo)) {
3354
        $courseInfo = api_get_course_info();
3355
    }
3356
3357
    if (empty($sessionId)) {
3358
        $sessionId = api_get_session_id();
3359
    } else {
3360
        $sessionId = (int) $sessionId;
3361
    }
3362
3363
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3364
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3365
    $parentId = (int) $parentId;
3366
    $sessionCondition = api_get_session_condition($sessionId, false, false, 'w.session_id');
3367
3368
    $sql = "SELECT count(*) as count
3369
            FROM $commentTable c INNER JOIN $work w
3370
            ON c.c_id = w.c_id AND w.id = c.work_id
3371
            WHERE
3372
                $sessionCondition AND
3373
                parent_id = $parentId AND
3374
                w.c_id = ".$courseInfo['real_id'];
3375
3376
    $result = Database::query($sql);
3377
    if (Database::num_rows($result)) {
3378
        $comment = Database::fetch_array($result);
3379
3380
        return $comment['count'];
3381
    }
3382
3383
    return 0;
3384
}
3385
3386
/**
3387
 * Get last work information from parent.
3388
 *
3389
 * @param int   $parentId
3390
 * @param array $courseInfo
3391
 * @param int   $sessionId
3392
 *
3393
 * @return int
3394
 */
3395
function getLastWorkStudentFromParent(
3396
    $parentId,
3397
    $courseInfo = [],
3398
    $sessionId = 0
3399
) {
3400
    if (empty($courseInfo)) {
3401
        $courseInfo = api_get_course_info();
3402
    }
3403
3404
    if (empty($sessionId)) {
3405
        $sessionId = api_get_session_id();
3406
    } else {
3407
        $sessionId = (int) $sessionId;
3408
    }
3409
3410
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3411
    $sessionCondition = api_get_session_condition($sessionId, false);
3412
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3413
    $parentId = (int) $parentId;
3414
3415
    $sql = "SELECT w.*
3416
            FROM $commentTable c INNER JOIN $work w
3417
            ON c.c_id = w.c_id AND w.id = c.work_id
3418
            WHERE
3419
                $sessionCondition AND
3420
                parent_id = $parentId AND
3421
                w.c_id = ".$courseInfo['real_id'].'
3422
            ORDER BY w.sent_date
3423
            LIMIT 1
3424
            ';
3425
3426
    $result = Database::query($sql);
3427
    if (Database::num_rows($result)) {
3428
        return Database::fetch_array($result, 'ASSOC');
3429
    }
3430
3431
    return [];
3432
}
3433
3434
/**
3435
 * Get last work information from parent.
3436
 *
3437
 * @param int   $userId
3438
 * @param array $parentInfo
3439
 * @param array $courseInfo
3440
 * @param int   $sessionId
3441
 *
3442
 * @return int
3443
 */
3444
function getLastWorkStudentFromParentByUser(
3445
    $userId,
3446
    $parentInfo,
3447
    $courseInfo = [],
3448
    $sessionId = 0
3449
) {
3450
    if (empty($courseInfo)) {
3451
        $courseInfo = api_get_course_info();
3452
    }
3453
3454
    if (empty($sessionId)) {
3455
        $sessionId = api_get_session_id();
3456
    } else {
3457
        $sessionId = (int) $sessionId;
3458
    }
3459
3460
    $userId = (int) $userId;
3461
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3462
    if (empty($parentInfo)) {
3463
        return false;
3464
    }
3465
    $parentId = $parentInfo['id'];
3466
3467
    $sessionCondition = api_get_session_condition($sessionId);
3468
3469
    $sql = "SELECT *
3470
            FROM $work
3471
            WHERE
3472
                user_id = $userId
3473
                $sessionCondition AND
3474
                parent_id = $parentId AND
3475
                c_id = ".$courseInfo['real_id']."
3476
            ORDER BY sent_date DESC
3477
            LIMIT 1
3478
            ";
3479
    $result = Database::query($sql);
3480
    if (Database::num_rows($result)) {
3481
        $work = Database::fetch_array($result, 'ASSOC');
3482
        $work['qualification_rounded'] = formatWorkScore($work['qualification'], $parentInfo['qualification']);
3483
3484
        return $work;
3485
    }
3486
3487
    return [];
3488
}
3489
3490
/**
3491
 * @param float $score
3492
 * @param int   $weight
3493
 *
3494
 * @return string
3495
 */
3496
function formatWorkScore($score, $weight)
3497
{
3498
    $label = 'info';
3499
    $weight = (int) $weight;
3500
    $relativeScore = 0;
3501
    if (!empty($weight)) {
3502
        $relativeScore = $score / $weight;
3503
    }
3504
3505
    if ($relativeScore < 0.5) {
3506
        $label = 'important';
3507
    } elseif ($relativeScore < 0.75) {
3508
        $label = 'warning';
3509
    }
3510
3511
    $scoreBasedInModel = ExerciseLib::convertScoreToModel($relativeScore * 100);
3512
    if (empty($scoreBasedInModel)) {
3513
        $finalScore = api_number_format($score, 1).' / '.$weight;
3514
3515
        return Display::label(
3516
            $finalScore,
3517
            $label
3518
        );
3519
    } else {
3520
        return $scoreBasedInModel;
3521
    }
3522
}
3523
3524
/**
3525
 * @param int   $id         comment id
3526
 * @param array $courseInfo
3527
 *
3528
 * @return string
3529
 */
3530
function getWorkComment($id, $courseInfo = [])
3531
{
3532
    if (empty($courseInfo)) {
3533
        $courseInfo = api_get_course_info();
3534
    }
3535
3536
    if (empty($courseInfo['real_id'])) {
3537
        return [];
3538
    }
3539
3540
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3541
    $id = intval($id);
3542
3543
    $sql = "SELECT * FROM $commentTable
3544
            WHERE id = $id AND c_id = ".$courseInfo['real_id'];
3545
    $result = Database::query($sql);
3546
    $comment = [];
3547
    if (Database::num_rows($result)) {
3548
        $comment = Database::fetch_array($result, 'ASSOC');
3549
        $filePath = null;
3550
        $fileUrl = null;
3551
        $deleteUrl = null;
3552
        $fileName = null;
3553
        if (!empty($comment['file'])) {
3554
            $work = get_work_data_by_id($comment['work_id']);
3555
            $workParent = get_work_data_by_id($work['parent_id']);
3556
            $filePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'.$workParent['url'].'/'.$comment['file'];
3557
            $fileUrl = api_get_path(WEB_CODE_PATH).'work/download_comment_file.php?comment_id='.$id.'&'.api_get_cidreq();
3558
            $deleteUrl = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$comment['work_id'].'&action=delete_attachment&comment_id='.$id;
3559
            $fileParts = explode('_', $comment['file']);
3560
            $fileName = str_replace($fileParts[0].'_'.$fileParts[1].'_', '', $comment['file']);
3561
        }
3562
        $comment['delete_file_url'] = $deleteUrl;
3563
        $comment['file_path'] = $filePath;
3564
        $comment['file_url'] = $fileUrl;
3565
        $comment['file_name_to_show'] = $fileName;
3566
        $comment['sent_at_with_label'] = Display::dateToStringAgoAndLongDate($comment['sent_at']);
3567
    }
3568
3569
    return $comment;
3570
}
3571
3572
/**
3573
 * @param int   $id
3574
 * @param array $courseInfo
3575
 */
3576
function deleteCommentFile($id, $courseInfo = [])
3577
{
3578
    $workComment = getWorkComment($id, $courseInfo);
3579
    if (isset($workComment['file']) && !empty($workComment['file'])) {
3580
        if (file_exists($workComment['file_path'])) {
3581
            $result = my_delete($workComment['file_path']);
3582
            if ($result) {
3583
                $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3584
                $params = ['file' => ''];
3585
                Database::update(
3586
                    $commentTable,
3587
                    $params,
3588
                    ['id = ? AND c_id = ? ' => [$workComment['id'], $workComment['c_id']]]
3589
                );
3590
            }
3591
        }
3592
    }
3593
}
3594
3595
/**
3596
 * Adds a comments to the work document.
3597
 *
3598
 * @param array $courseInfo
3599
 * @param int   $userId
3600
 * @param array $parentWork
3601
 * @param array $work
3602
 * @param array $data
3603
 *
3604
 * @return int
3605
 */
3606
function addWorkComment($courseInfo, $userId, $parentWork, $work, $data)
3607
{
3608
    $fileData = isset($data['attachment']) ? $data['attachment'] : null;
3609
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3610
3611
    // If no attachment and no comment then don't save comment
3612
    if (empty($fileData['name']) && empty($data['comment'])) {
3613
        return false;
3614
    }
3615
3616
    $params = [
3617
        'work_id' => $work['id'],
3618
        'c_id' => $work['c_id'],
3619
        'user_id' => $userId,
3620
        'comment' => $data['comment'],
3621
        'sent_at' => api_get_utc_datetime(),
3622
    ];
3623
3624
    $commentId = Database::insert($commentTable, $params);
3625
3626
    if ($commentId) {
3627
        Display::addFlash(
3628
            Display::return_message(get_lang('CommentAdded'))
3629
        );
3630
3631
        $sql = "UPDATE $commentTable SET id = iid WHERE iid = $commentId";
3632
        Database::query($sql);
3633
    }
3634
3635
    $userIdListToSend = [];
3636
    if (api_is_allowed_to_edit()) {
3637
        if (isset($data['send_email']) && $data['send_email']) {
3638
            // Teacher sends a feedback
3639
            $userIdListToSend = [$work['user_id']];
3640
        }
3641
    } else {
3642
        $sessionId = api_get_session_id();
3643
        if (empty($sessionId)) {
3644
            $teachers = CourseManager::get_teacher_list_from_course_code(
3645
                $courseInfo['code']
3646
            );
3647
            if (!empty($teachers)) {
3648
                $userIdListToSend = array_keys($teachers);
3649
            }
3650
        } else {
3651
            $teachers = SessionManager::getCoachesByCourseSession(
3652
                $sessionId,
3653
                $courseInfo['real_id']
3654
            );
3655
3656
            if (!empty($teachers)) {
3657
                $userIdListToSend = array_values($teachers);
3658
            }
3659
        }
3660
3661
        $sendNotification = api_get_course_setting('email_to_teachers_on_new_work_feedback');
3662
        if ($sendNotification != 1) {
3663
            $userIdListToSend = [];
3664
        }
3665
    }
3666
3667
    $url = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$work['id'];
3668
    $subject = sprintf(get_lang('ThereIsANewWorkFeedback'), $parentWork['title']);
3669
    $content = sprintf(get_lang('ThereIsANewWorkFeedbackInWorkXHere'), $work['title'], $url);
3670
3671
    if (!empty($data['comment'])) {
3672
        $content .= '<br /><b>'.get_lang('Comment').':</b><br />'.$data['comment'];
3673
    }
3674
3675
    if (!empty($userIdListToSend)) {
3676
        foreach ($userIdListToSend as $userIdToSend) {
3677
            MessageManager::send_message_simple(
3678
                $userIdToSend,
3679
                $subject,
3680
                $content
3681
            );
3682
        }
3683
    }
3684
3685
    if (!empty($commentId) && !empty($fileData)) {
3686
        $workParent = get_work_data_by_id($work['parent_id']);
3687
        if (!empty($workParent)) {
3688
            $uploadDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work'.$workParent['url'];
3689
            $newFileName = 'comment_'.$commentId.'_'.php2phps(api_replace_dangerous_char($fileData['name']));
3690
            $newFilePath = $uploadDir.'/'.$newFileName;
3691
            $result = move_uploaded_file($fileData['tmp_name'], $newFilePath);
3692
            if ($result) {
3693
                $params = ['file' => $newFileName];
3694
                Database::update(
3695
                    $commentTable,
3696
                    $params,
3697
                    ['id = ? AND c_id = ? ' => [$commentId, $work['c_id']]]
3698
                );
3699
            }
3700
        }
3701
    }
3702
}
3703
3704
/**
3705
 * @param array $work
3706
 * @param array $workParent
3707
 *
3708
 * @return string
3709
 */
3710
function getWorkCommentForm($work, $workParent)
3711
{
3712
    $url = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&action=send_comment&'.api_get_cidreq();
3713
    $form = new FormValidator(
3714
        'work_comment',
3715
        'post',
3716
        $url,
3717
        '',
3718
        ['enctype' => "multipart/form-data"]
3719
    );
3720
3721
    $qualification = $workParent['qualification'];
3722
3723
    $isCourseManager = api_is_platform_admin() || api_is_coach() || api_is_allowed_to_edit(false, false, true);
3724
    $allowEdition = false;
3725
    if ($isCourseManager) {
3726
        $allowEdition = true;
3727
        if (!empty($work['qualification']) && api_get_configuration_value('block_student_publication_score_edition')) {
3728
            $allowEdition = false;
3729
        }
3730
    }
3731
3732
    if (api_is_platform_admin()) {
3733
        $allowEdition = true;
3734
    }
3735
3736
    if ($allowEdition) {
3737
        if (!empty($qualification) && intval($qualification) > 0) {
3738
            $model = ExerciseLib::getCourseScoreModel();
3739
            if (empty($model)) {
3740
                $form->addFloat(
3741
                    'qualification',
3742
                    [get_lang('Qualification'), " / ".$qualification],
3743
                    false,
3744
                    [],
3745
                    false,
3746
                    0,
3747
                    $qualification
3748
                );
3749
            } else {
3750
                ExerciseLib::addScoreModelInput(
3751
                    $form,
3752
                    'qualification',
3753
                    $qualification,
3754
                    $work['qualification']
3755
                );
3756
            }
3757
            $form->addFile('file', get_lang('Correction'));
3758
            $form->setDefaults(['qualification' => $work['qualification']]);
3759
        }
3760
    }
3761
3762
    Skill::addSkillsToUserForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workParent['id'], $work['user_id'], $work['id']);
3763
    $form->addHtmlEditor('comment', get_lang('Comment'), false);
3764
    $form->addFile('attachment', get_lang('Attachment'));
3765
    $form->addElement('hidden', 'id', $work['id']);
3766
3767
    if (api_is_allowed_to_edit()) {
3768
        $form->addCheckBox(
3769
            'send_email',
3770
            null,
3771
            get_lang('SendMailToStudent')
3772
        );
3773
    }
3774
3775
    $form->addButtonSend(get_lang('Send'), 'button');
3776
3777
    return $form->returnForm();
3778
}
3779
3780
/**
3781
 * @param array $homework result of get_work_assignment_by_id()
3782
 *
3783
 * @return array
3784
 */
3785
function getWorkDateValidationStatus($homework)
3786
{
3787
    $message = null;
3788
    $has_expired = false;
3789
    $has_ended = false;
3790
3791
    if (!empty($homework)) {
3792
        if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) {
3793
            $time_now = time();
3794
3795
            if (!empty($homework['expires_on'])) {
3796
                $time_expires = api_strtotime($homework['expires_on'], 'UTC');
3797
                $difference = $time_expires - $time_now;
3798
                if ($difference < 0) {
3799
                    $has_expired = true;
3800
                }
3801
            }
3802
3803
            if (empty($homework['expires_on'])) {
3804
                $has_expired = false;
3805
            }
3806
3807
            if (!empty($homework['ends_on'])) {
3808
                $time_ends = api_strtotime($homework['ends_on'], 'UTC');
3809
                $difference2 = $time_ends - $time_now;
3810
                if ($difference2 < 0) {
3811
                    $has_ended = true;
3812
                }
3813
            }
3814
3815
            $ends_on = api_convert_and_format_date($homework['ends_on']);
3816
            $expires_on = api_convert_and_format_date($homework['expires_on']);
3817
        }
3818
3819
        if ($has_ended) {
3820
            $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
3821
        } elseif ($has_expired) {
3822
            $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
3823
        } else {
3824
            if ($has_expired) {
3825
                $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
3826
            }
3827
        }
3828
    }
3829
3830
    return [
3831
        'message' => $message,
3832
        'has_ended' => $has_ended,
3833
        'has_expired' => $has_expired,
3834
    ];
3835
}
3836
3837
/**
3838
 * @param FormValidator $form
3839
 * @param int           $uploadFormType
3840
 */
3841
function setWorkUploadForm($form, $uploadFormType = 0)
3842
{
3843
    $form->addHeader(get_lang('UploadADocument'));
3844
    $form->addHidden('contains_file', 0, ['id' => 'contains_file_id']);
3845
    $form->addHidden('active', 1);
3846
    $form->addHidden('accepted', 1);
3847
    $form->addElement('text', 'title', get_lang('Title'), ['id' => 'file_upload']);
3848
    $form->addElement(
3849
        'text',
3850
        'extension',
3851
        get_lang('FileExtension'),
3852
        ['id' => 'file_extension', 'readonly' => 'readonly']
3853
    );
3854
    $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
3855
3856
    switch ($uploadFormType) {
3857
        case 0:
3858
            // File and text.
3859
            $form->addElement(
3860
                'file',
3861
                'file',
3862
                get_lang('UploadADocument'),
3863
                'size="40" onchange="updateDocumentTitle(this.value)"'
3864
            );
3865
            $form->addProgress();
3866
            $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
3867
            break;
3868
        case 1:
3869
            // Only text.
3870
            $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
3871
            $form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
3872
            break;
3873
        case 2:
3874
            // Only file.
3875
            $form->addElement(
3876
                'file',
3877
                'file',
3878
                get_lang('UploadADocument'),
3879
                'size="40" onchange="updateDocumentTitle(this.value)"'
3880
            );
3881
            $form->addProgress();
3882
            $form->addRule('file', get_lang('ThisFieldIsRequired'), 'required');
3883
            break;
3884
    }
3885
3886
    $form->addButtonUpload(get_lang('Upload'), 'submitWork');
3887
}
3888
3889
/**
3890
 * @param array $my_folder_data
3891
 * @param array $_course
3892
 * @param bool  $isCorrection
3893
 * @param array $workInfo
3894
 * @param array $file
3895
 *
3896
 * @return array
3897
 */
3898
function uploadWork($my_folder_data, $_course, $isCorrection = false, $workInfo = [], $file = [])
3899
{
3900
    if (isset($_FILES['file']) && !empty($_FILES['file'])) {
3901
        $file = $_FILES['file'];
3902
    }
3903
3904
    if (empty($file['size'])) {
3905
        return [
3906
            'error' => Display:: return_message(
3907
                get_lang('UplUploadFailedSizeIsZero'),
3908
                'error'
3909
            ),
3910
        ];
3911
    }
3912
    $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload
3913
3914
    // Try to add an extension to the file if it has'nt one
3915
    $filename = add_ext_on_mime(stripslashes($file['name']), $file['type']);
3916
3917
    // Replace dangerous characters
3918
    $filename = api_replace_dangerous_char($filename);
3919
3920
    // Transform any .php file in .phps fo security
3921
    $filename = php2phps($filename);
3922
    $filesize = filesize($file['tmp_name']);
3923
3924
    if (empty($filesize)) {
3925
        return [
3926
            'error' => Display::return_message(
3927
                get_lang('UplUploadFailedSizeIsZero'),
3928
                'error'
3929
            ),
3930
        ];
3931
    } elseif (!filter_extension($new_file_name)) {
3932
        return [
3933
            'error' => Display::return_message(
3934
                get_lang('UplUnableToSaveFileFilteredExtension'),
3935
                'error'
3936
            ),
3937
        ];
3938
    }
3939
3940
    $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
3941
    $course_max_space = DocumentManager::get_course_quota($_course['code']);
3942
    $total_size = $filesize + $totalSpace;
3943
3944
    if ($total_size > $course_max_space) {
3945
        return [
3946
            'error' => Display::return_message(get_lang('NoSpace'), 'error'),
3947
        ];
3948
    }
3949
3950
    // Compose a unique file name to avoid any conflict
3951
    $new_file_name = api_get_unique_id();
3952
3953
    if ($isCorrection) {
3954
        if (!empty($workInfo['url'])) {
3955
            $new_file_name = basename($workInfo['url']).'_correction';
3956
        } else {
3957
            $new_file_name = $new_file_name.'_correction';
3958
        }
3959
    }
3960
3961
    $curdirpath = basename($my_folder_data['url']);
3962
3963
    // If we come from the group tools the groupid will be saved in $work_table
3964
    if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
3965
        $result = move_uploaded_file(
3966
            $file['tmp_name'],
3967
            $updir.$curdirpath.'/'.$new_file_name
3968
        );
3969
    } else {
3970
        return [
3971
            'error' => Display :: return_message(
3972
                get_lang('FolderDoesntExistsInFileSystem'),
3973
                'error'
3974
            ),
3975
        ];
3976
    }
3977
3978
    if ($result) {
3979
        $url = 'work/'.$curdirpath.'/'.$new_file_name;
3980
    } else {
3981
        return false;
3982
    }
3983
3984
    return [
3985
        'url' => $url,
3986
        'filename' => $filename,
3987
        'filesize' => $filesize,
3988
        'error' => '',
3989
    ];
3990
}
3991
3992
/**
3993
 * Send an e-mail to users related to this work.
3994
 *
3995
 * @param array $workInfo
3996
 * @param int   $workId
3997
 * @param array $courseInfo
3998
 * @param int   $sessionId
3999
 */
4000
function sendAlertToUsers($workInfo, $workId, $courseInfo, $sessionId = 0)
4001
{
4002
    $sessionId = (int) $sessionId;
4003
4004
    if (empty($workInfo) || empty($courseInfo) || empty($workId)) {
4005
        return false;
4006
    }
4007
4008
    $courseCode = $courseInfo['code'];
4009
4010
    $workData = get_work_data_by_id($workId, $courseInfo['real_id'], $sessionId);
4011
    // last value is to check this is not "just" an edit
4012
    // YW Tis part serve to send a e-mail to the tutors when a new file is sent
4013
    $send = api_get_course_setting('email_alert_manager_on_new_doc');
4014
4015
    $userList = [];
4016
    if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_TEACHERS) {
4017
        // Lets predefine some variables. Be sure to change the from address!
4018
        if (empty($sessionId)) {
4019
            // Teachers
4020
            $userList = CourseManager::get_user_list_from_course_code(
4021
                $courseCode,
4022
                null,
4023
                null,
4024
                null,
4025
                COURSEMANAGER
4026
            );
4027
        } else {
4028
            // Coaches
4029
            $userList = CourseManager::get_user_list_from_course_code(
4030
                $courseCode,
4031
                $sessionId,
4032
                null,
4033
                null,
4034
                2
4035
            );
4036
        }
4037
    }
4038
4039
    if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_STUDENTS) {
4040
        // Send mail only to sender
4041
        $studentList = [[
4042
           'user_id' => api_get_user_id(),
4043
        ]];
4044
        $userList = array_merge($userList, $studentList);
4045
    }
4046
4047
    if ($send) {
4048
        $folderUrl = api_get_path(WEB_CODE_PATH)."work/work_list_all.php?cidReq=".$courseInfo['code']."&id_session=".$sessionId."&id=".$workInfo['id'];
4049
        $fileUrl = api_get_path(WEB_CODE_PATH)."work/view.php?cidReq=".$courseInfo['code']."&id_session=".$sessionId."&id=".$workData['id'];
4050
4051
        foreach ($userList as $userData) {
4052
            $userId = $userData['user_id'];
4053
            $userInfo = api_get_user_info($userId);
4054
            if (empty($userInfo)) {
4055
                continue;
4056
            }
4057
4058
            $userPostedADocument = sprintf(
4059
                get_lang('UserXPostedADocumentInCourseX'),
4060
                $userInfo['complete_name'],
4061
                $courseInfo['name']
4062
            );
4063
4064
            $subject = "[".api_get_setting('siteName')."] ".$userPostedADocument;
4065
            $message = $userPostedADocument."<br />";
4066
            $message .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."<br />";
4067
            $message .= get_lang('AssignmentName')." : ".Display::url($workInfo['title'], $folderUrl)."<br />";
4068
            $message .= get_lang('Filename')." : ".$workData['title']."<br />";
4069
            $message .= '<a href="'.$fileUrl.'">'.get_lang('DownloadLink')."</a><br />";
4070
4071
            MessageManager::send_message_simple(
4072
                $userId,
4073
                $subject,
4074
                $message,
4075
                0,
4076
                false,
4077
                false,
4078
                [],
4079
                false
4080
            );
4081
        }
4082
    }
4083
}
4084
4085
/**
4086
 * Check if the current uploaded work filename already exists in the current assement.
4087
 *
4088
 * @param string $filename
4089
 * @param int    $workId
4090
 *
4091
 * @return array
4092
 */
4093
function checkExistingWorkFileName($filename, $workId)
4094
{
4095
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4096
    $filename = Database::escape_string($filename);
4097
    $workId = (int) $workId;
4098
4099
    $sql = "SELECT title FROM $table
4100
            WHERE parent_id = $workId AND title = '$filename' AND active = 1";
4101
    $result = Database::query($sql);
4102
4103
    return Database::fetch_assoc($result);
4104
}
4105
4106
/**
4107
 * @param array $workInfo
4108
 * @param array $values
4109
 * @param array $courseInfo
4110
 * @param int   $sessionId
4111
 * @param int   $groupId
4112
 * @param int   $userId
4113
 * @param array $file
4114
 * @param bool  $checkDuplicated
4115
 * @param bool  $showFlashMessage
4116
 *
4117
 * @return string|null
4118
 */
4119
function processWorkForm(
4120
    $workInfo,
4121
    $values,
4122
    $courseInfo,
4123
    $sessionId,
4124
    $groupId,
4125
    $userId,
4126
    $file = [],
4127
    $checkDuplicated = false,
4128
    $showFlashMessage = true
4129
) {
4130
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4131
4132
    $courseId = $courseInfo['real_id'];
4133
    $groupId = (int) $groupId;
4134
    $sessionId = (int) $sessionId;
4135
    $userId = (int) $userId;
4136
4137
    $extension = '';
4138
    if (isset($values['extension'])) {
4139
        $extension = $values['extension'];
4140
    } else {
4141
        $fileInfo = pathinfo($values['title']);
4142
        if (isset($fileInfo['extension']) && !empty($fileInfo['extension'])) {
4143
            $extension = '.'.$fileInfo['extension'];
4144
            $values['title'] = $fileInfo['filename'];
4145
        }
4146
    }
4147
4148
    $title = $values['title'].$extension;
4149
    $description = isset($values['description']) ? $values['description'] : '';
4150
    $containsFile = isset($values['contains_file']) && !empty($values['contains_file']) ? (int) $values['contains_file'] : 0;
4151
4152
    $saveWork = true;
4153
    $filename = null;
4154
    $url = null;
4155
    $filesize = null;
4156
    $workData = [];
4157
    $message = null;
4158
4159
    if ($containsFile) {
4160
        $saveWork = false;
4161
        if ($checkDuplicated) {
4162
            if (checkExistingWorkFileName($file['name'], $workInfo['id'])) {
4163
                $saveWork = false;
4164
                $result['error'] = get_lang('YouAlreadySentThisFile');
4165
                $workData['error'] = get_lang('UplAlreadyExists');
4166
            } else {
4167
                $result = uploadWork($workInfo, $courseInfo, false, [], $file);
4168
            }
4169
        } else {
4170
            $result = uploadWork($workInfo, $courseInfo, false, [], $file);
4171
        }
4172
4173
        if (isset($result['error'])) {
4174
            $saveWork = false;
4175
            if ($showFlashMessage) {
4176
                $message = $result['error'];
4177
            }
4178
            if (empty($result['error']) && isset($result['url']) && !empty($result['url'])) {
4179
                $saveWork = true;
4180
            }
4181
        }
4182
    }
4183
4184
    if ($saveWork) {
4185
        $filename = isset($result['filename']) ? $result['filename'] : null;
4186
        if (empty($title)) {
4187
            $title = isset($result['title']) && !empty($result['title']) ? $result['title'] : get_lang('Untitled');
4188
        }
4189
        $filesize = isset($result['filesize']) ? $result['filesize'] : null;
4190
        $url = isset($result['url']) ? $result['url'] : null;
4191
    }
4192
4193
    if (empty($title)) {
4194
        $title = get_lang('Untitled');
4195
    }
4196
4197
    $groupIid = 0;
4198
    $groupInfo = [];
4199
    if ($groupId) {
4200
        $groupInfo = GroupManager::get_group_properties($groupId);
4201
        $groupIid = $groupInfo['iid'];
4202
    }
4203
4204
    if ($saveWork) {
4205
        $active = '1';
4206
        $params = [
4207
            'c_id' => $courseId,
4208
            'url' => $url,
4209
            'filetype' => 'file',
4210
            'title' => $title,
4211
            'description' => $description,
4212
            'contains_file' => $containsFile,
4213
            'active' => $active,
4214
            'accepted' => '1',
4215
            'qualificator_id' => 0,
4216
            'document_id' => 0,
4217
            'weight' => 0,
4218
            'allow_text_assignment' => 0,
4219
            'post_group_id' => $groupIid,
4220
            'sent_date' => api_get_utc_datetime(),
4221
            'parent_id' => $workInfo['id'],
4222
            'session_id' => $sessionId ? $sessionId : null,
4223
            'user_id' => $userId,
4224
            'has_properties' => 0,
4225
            'qualification' => 0,
4226
            //'filesize' => $filesize
4227
        ];
4228
        $workId = Database::insert($work_table, $params);
4229
4230
        if ($workId) {
4231
            $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId ";
4232
            Database::query($sql);
4233
4234
            if (array_key_exists('filename', $workInfo) && !empty($filename)) {
4235
                $filename = Database::escape_string($filename);
4236
                $sql = "UPDATE $work_table SET
4237
                            filename = '$filename'
4238
                        WHERE iid = $workId";
4239
                Database::query($sql);
4240
            }
4241
4242
            if (array_key_exists('document_id', $workInfo)) {
4243
                $documentId = isset($values['document_id']) ? (int) $values['document_id'] : 0;
4244
                $sql = "UPDATE $work_table SET
4245
                            document_id = '$documentId'
4246
                        WHERE iid = $workId";
4247
                Database::query($sql);
4248
            }
4249
4250
            api_item_property_update(
4251
                $courseInfo,
4252
                'work',
4253
                $workId,
4254
                'DocumentAdded',
4255
                $userId,
4256
                $groupInfo
4257
            );
4258
            sendAlertToUsers($workInfo, $workId, $courseInfo, $sessionId);
4259
            Event::event_upload($workId);
4260
4261
            // The following feature requires the creation of a work-type
4262
            // extra_field and the following setting in the configuration file
4263
            // (until moved to the database). It allows te teacher to set a
4264
            // "considered work time", meaning the time we assume a student
4265
            // would have spent, approximately, to prepare the task before
4266
            // handing it in Chamilo, adding this time to the student total
4267
            // course use time, as a register of time spent *before* his
4268
            // connection to the platform to hand the work in.
4269
            $consideredWorkingTime = api_get_configuration_value('considered_working_time');
4270
4271
            if (!empty($consideredWorkingTime)) {
4272
                // Get the "considered work time" defined for this work
4273
                $fieldValue = new ExtraFieldValue('work');
4274
                $resultExtra = $fieldValue->getAllValuesForAnItem(
4275
                    $workInfo['iid'], //the ID of the work *folder*, not the document uploaded by the student
4276
                    true
4277
                );
4278
4279
                $workingTime = null;
4280
                foreach ($resultExtra as $field) {
4281
                    $field = $field['value'];
4282
                    if ($consideredWorkingTime == $field->getField()->getVariable()) {
4283
                        $workingTime = $field->getValue();
4284
                    }
4285
                }
4286
4287
                // If no time was defined, or a time of "0" was set, do nothing
4288
                if (!empty($workingTime)) {
4289
                    // If some time is set, get the list of docs handed in by
4290
                    // this student (to make sure we count the time only once)
4291
                    $userWorks = get_work_user_list(
4292
                        0,
4293
                        100,
4294
                        null,
4295
                        null,
4296
                        $workInfo['id'],
4297
                        null,
4298
                        $userId,
4299
                        false,
4300
                        $courseId,
4301
                        $sessionId
4302
                    );
4303
4304
                    if (1 == count($userWorks)) {
4305
                        // The student only uploaded one doc so far, so add the
4306
                        // considered work time to his course connection time
4307
                        Event::eventAddVirtualCourseTime($courseId, $userId, $sessionId, $workingTime);
4308
                    }
4309
                }
4310
            }
4311
            $workData = get_work_data_by_id($workId);
4312
            if ($workData && $showFlashMessage) {
4313
                Display::addFlash(Display::return_message(get_lang('DocAdd')));
4314
            }
4315
        }
4316
    } else {
4317
        if ($showFlashMessage) {
4318
            Display::addFlash(
4319
                Display::return_message(
4320
                    $message ? $message : get_lang('ImpossibleToSaveTheDocument'),
4321
                    'error'
4322
                )
4323
            );
4324
        }
4325
    }
4326
4327
    return $workData;
4328
}
4329
4330
/**
4331
 * Creates a new task (directory) in the assignment tool.
4332
 *
4333
 * @param array $formValues
4334
 * @param int   $user_id
4335
 * @param array $courseInfo
4336
 * @param int   $groupId
4337
 * @param int   $sessionId
4338
 *
4339
 * @return bool|int
4340
 * @note $params can have the following elements, but should at least have the 2 first ones: (
4341
 *       'new_dir' => 'some-name',
4342
 *       'description' => 'some-desc',
4343
 *       'qualification' => 20 (e.g. 20),
4344
 *       'weight' => 50 (percentage) to add to gradebook (e.g. 50),
4345
 *       'allow_text_assignment' => 0/1/2,
4346
 *
4347
 * @todo Rename createAssignment or createWork, or something like that
4348
 */
4349
function addDir($formValues, $user_id, $courseInfo, $groupId, $sessionId = 0)
4350
{
4351
    $em = Database::getManager();
4352
4353
    $user_id = (int) $user_id;
4354
    $groupId = (int) $groupId;
4355
    $sessionId = (int) $sessionId;
4356
4357
    $groupIid = 0;
4358
    $groupInfo = [];
4359
    if (!empty($groupId)) {
4360
        $groupInfo = GroupManager::get_group_properties($groupId);
4361
        $groupIid = $groupInfo['iid'];
4362
    }
4363
    $session = $em->find('ChamiloCoreBundle:Session', $sessionId);
4364
4365
    $base_work_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work';
4366
    $course_id = $courseInfo['real_id'];
4367
4368
    $directory = api_replace_dangerous_char($formValues['new_dir']);
4369
    $directory = disable_dangerous_file($directory);
4370
4371
    $created_dir = create_unexisting_work_directory($base_work_dir, $directory);
4372
4373
    if (empty($created_dir)) {
4374
        return false;
4375
    }
4376
4377
    $enableEndDate = isset($formValues['enableEndDate']) ? true : false;
4378
    $enableExpiryDate = isset($formValues['enableExpiryDate']) ? true : false;
4379
4380
    if ($enableEndDate && $enableExpiryDate) {
4381
        if ($formValues['expires_on'] > $formValues['ends_on']) {
4382
            Display::addFlash(
4383
                Display::return_message(
4384
                    get_lang('DateExpiredNotBeLessDeadLine'),
4385
                    'warning'
4386
                )
4387
            );
4388
4389
            return false;
4390
        }
4391
    }
4392
4393
    $dirName = '/'.$created_dir;
4394
    $today = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
4395
    $title = isset($formValues['work_title']) ? $formValues['work_title'] : $formValues['new_dir'];
4396
4397
    $workTable = new CStudentPublication();
4398
    $workTable
4399
        ->setCId($course_id)
4400
        ->setUrl($dirName)
4401
        ->setTitle($title)
4402
        ->setDescription($formValues['description'])
4403
        ->setActive(true)
4404
        ->setAccepted(true)
4405
        ->setFiletype('folder')
4406
        ->setPostGroupId($groupIid)
4407
        ->setSentDate($today)
4408
        ->setQualification($formValues['qualification'] != '' ? $formValues['qualification'] : 0)
4409
        ->setParentId(0)
4410
        ->setQualificatorId(0)
4411
        ->setWeight(!empty($formValues['weight']) ? $formValues['weight'] : 0)
4412
        ->setSession($session)
4413
        ->setAllowTextAssignment($formValues['allow_text_assignment'])
4414
        ->setContainsFile(0)
4415
        ->setUserId($user_id)
4416
        ->setHasProperties(0)
4417
        ->setDocumentId(0);
4418
4419
    $em->persist($workTable);
4420
    $em->flush();
4421
4422
    $workTable->setId($workTable->getIid());
4423
    $em->merge($workTable);
4424
    $em->flush();
4425
4426
    // Folder created
4427
    api_item_property_update(
4428
        $courseInfo,
4429
        'work',
4430
        $workTable->getIid(),
4431
        'DirectoryCreated',
4432
        $user_id,
4433
        $groupInfo
4434
    );
4435
4436
    updatePublicationAssignment(
4437
        $workTable->getIid(),
4438
        $formValues,
4439
        $courseInfo,
4440
        $groupIid
4441
    );
4442
4443
    // Added the new Work ID to the extra field values
4444
    $formValues['item_id'] = $workTable->getIid();
4445
4446
    $workFieldValue = new ExtraFieldValue('work');
4447
    $workFieldValue->saveFieldValues($formValues);
4448
4449
    $sendEmailAlert = api_get_course_setting('email_alert_students_on_new_homework');
4450
4451
    switch ($sendEmailAlert) {
4452
        case 1:
4453
            sendEmailToStudentsOnHomeworkCreation(
4454
                $workTable->getIid(),
4455
                $course_id,
4456
                $sessionId
4457
            );
4458
            //no break
4459
        case 2:
4460
            sendEmailToDrhOnHomeworkCreation(
4461
                $workTable->getIid(),
4462
                $course_id,
4463
                $sessionId
4464
            );
4465
            break;
4466
    }
4467
4468
    return $workTable->getIid();
4469
}
4470
4471
/**
4472
 * @param int   $workId
4473
 * @param array $courseInfo
4474
 *
4475
 * @return int
4476
 */
4477
function agendaExistsForWork($workId, $courseInfo)
4478
{
4479
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
4480
    $courseId = $courseInfo['real_id'];
4481
    $workId = (int) $workId;
4482
4483
    $sql = "SELECT add_to_calendar FROM $workTable
4484
            WHERE c_id = $courseId AND publication_id = ".$workId;
4485
    $res = Database::query($sql);
4486
    if (Database::num_rows($res)) {
4487
        $row = Database::fetch_array($res, 'ASSOC');
4488
        if (!empty($row['add_to_calendar'])) {
4489
            return $row['add_to_calendar'];
4490
        }
4491
    }
4492
4493
    return 0;
4494
}
4495
4496
/**
4497
 * Update work description, qualification, weight, allow_text_assignment.
4498
 *
4499
 * @param int   $workId     (iid)
4500
 * @param array $params
4501
 * @param array $courseInfo
4502
 * @param int   $sessionId
4503
 */
4504
function updateWork($workId, $params, $courseInfo, $sessionId = 0)
4505
{
4506
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4507
    $filteredParams = [
4508
        'description' => $params['description'],
4509
        'qualification' => $params['qualification'],
4510
        'weight' => $params['weight'],
4511
        'allow_text_assignment' => $params['allow_text_assignment'],
4512
    ];
4513
4514
    Database::update(
4515
        $workTable,
4516
        $filteredParams,
4517
        [
4518
            'iid = ? AND c_id = ?' => [
4519
                $workId,
4520
                $courseInfo['real_id'],
4521
            ],
4522
        ]
4523
    );
4524
4525
    $workFieldValue = new ExtraFieldValue('work');
4526
    $workFieldValue->saveFieldValues($params);
4527
}
4528
4529
/**
4530
 * @param int   $workId
4531
 * @param array $params
4532
 * @param array $courseInfo
4533
 * @param int   $groupId
4534
 */
4535
function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
4536
{
4537
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
4538
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4539
    $workId = (int) $workId;
4540
    $now = api_get_utc_datetime();
4541
    $course_id = $courseInfo['real_id'];
4542
4543
    // Insert into agenda
4544
    $agendaId = 0;
4545
    if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
4546
        // Setting today date
4547
        $date = $end_date = $now;
4548
4549
        if (isset($params['enableExpiryDate'])) {
4550
            $end_date = $params['expires_on'];
4551
            $date = $end_date;
4552
        }
4553
4554
        $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
4555
        $description = isset($params['description']) ? $params['description'] : '';
4556
        $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
4557
            .$params['new_dir'].'</a>'.$description;
4558
4559
        $agendaId = agendaExistsForWork($workId, $courseInfo);
4560
4561
        // Add/edit agenda
4562
        $agenda = new Agenda('course');
4563
        $agenda->set_course($courseInfo);
4564
4565
        if (!empty($agendaId)) {
4566
            // add_to_calendar is set but it doesnt exists then invalidate
4567
            $eventInfo = $agenda->get_event($agendaId);
4568
            if (empty($eventInfo)) {
4569
                $agendaId = 0;
4570
            }
4571
        }
4572
4573
        $eventColor = $agenda->eventStudentPublicationColor;
4574
4575
        if (empty($agendaId)) {
4576
            $agendaId = $agenda->addEvent(
4577
                $date,
4578
                $end_date,
4579
                'false',
4580
                $title,
4581
                $content,
4582
                ['GROUP:'.$groupId],
4583
                false,
4584
                null,
4585
                [],
4586
                [],
4587
                null,
4588
                $eventColor
4589
            );
4590
        } else {
4591
            $agenda->editEvent(
4592
                $agendaId,
4593
                $end_date,
4594
                $end_date,
4595
                'false',
4596
                $title,
4597
                $content,
4598
                [],
4599
                [],
4600
                [],
4601
                null,
4602
                $eventColor
4603
            );
4604
        }
4605
    }
4606
4607
    $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
4608
    $expiryDate = isset($params['enableExpiryDate']) && (int) $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
4609
    $endDate = isset($params['enableEndDate']) && (int) $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
4610
    $data = get_work_assignment_by_id($workId, $course_id);
4611
    if (!empty($expiryDate)) {
4612
        $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', ";
4613
    } else {
4614
        $expiryDateCondition = "expires_on = null, ";
4615
    }
4616
4617
    if (!empty($endDate)) {
4618
        $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', ";
4619
    } else {
4620
        $endOnCondition = 'ends_on = null, ';
4621
    }
4622
4623
    if (empty($data)) {
4624
        $sql = "INSERT INTO $table SET
4625
                c_id = $course_id ,
4626
                $expiryDateCondition
4627
                $endOnCondition
4628
                add_to_calendar = $agendaId,
4629
                enable_qualification = '$qualification',
4630
                publication_id = '$workId'";
4631
        Database::query($sql);
4632
        $my_last_id = Database::insert_id();
4633
4634
        if ($my_last_id) {
4635
            $sql = "UPDATE $table SET
4636
                        id = iid
4637
                    WHERE iid = $my_last_id";
4638
            Database::query($sql);
4639
4640
            $sql = "UPDATE $workTable SET
4641
                        has_properties  = $my_last_id,
4642
                        view_properties = 1
4643
                    WHERE c_id = $course_id AND id = $workId";
4644
            Database::query($sql);
4645
        }
4646
    } else {
4647
        $sql = "UPDATE $table SET
4648
                    $expiryDateCondition
4649
                    $endOnCondition
4650
                    add_to_calendar  = $agendaId,
4651
                    enable_qualification = '".$qualification."'
4652
                WHERE
4653
                    publication_id = $workId AND
4654
                    c_id = $course_id AND
4655
                    iid = ".$data['iid'];
4656
        Database::query($sql);
4657
    }
4658
4659
    if (!empty($params['category_id'])) {
4660
        $link_info = GradebookUtils::isResourceInCourseGradebook(
4661
            $courseInfo['code'],
4662
            LINK_STUDENTPUBLICATION,
4663
            $workId,
4664
            api_get_session_id()
4665
        );
4666
4667
        $linkId = null;
4668
        if (!empty($link_info)) {
4669
            $linkId = $link_info['id'];
4670
        }
4671
4672
        if (isset($params['make_calification']) &&
4673
            $params['make_calification'] == 1
4674
        ) {
4675
            if (empty($linkId)) {
4676
                GradebookUtils::add_resource_to_course_gradebook(
4677
                    $params['category_id'],
4678
                    $courseInfo['code'],
4679
                    LINK_STUDENTPUBLICATION,
4680
                    $workId,
4681
                    $params['new_dir'],
4682
                    api_float_val($params['weight']),
4683
                    api_float_val($params['qualification']),
4684
                    $params['description'],
4685
                    1,
4686
                    api_get_session_id()
4687
                );
4688
            } else {
4689
                GradebookUtils::updateResourceFromCourseGradebook(
4690
                    $linkId,
4691
                    $courseInfo['code'],
4692
                    $params['weight']
4693
                );
4694
            }
4695
        } else {
4696
            // Delete everything of the gradebook for this $linkId
4697
            GradebookUtils::remove_resource_from_course_gradebook($linkId);
4698
        }
4699
    }
4700
}
4701
4702
/**
4703
 * Delete all work by student.
4704
 *
4705
 * @param int   $userId
4706
 * @param array $courseInfo
4707
 *
4708
 * @return array return deleted items
4709
 */
4710
function deleteAllWorkPerUser($userId, $courseInfo)
4711
{
4712
    $deletedItems = [];
4713
    $workPerUser = getWorkPerUser($userId);
4714
    if (!empty($workPerUser)) {
4715
        foreach ($workPerUser as $work) {
4716
            $work = $work['work'];
4717
            foreach ($work->user_results as $userResult) {
4718
                $result = deleteWorkItem($userResult['id'], $courseInfo);
4719
                if ($result) {
4720
                    $deletedItems[] = $userResult;
4721
                }
4722
            }
4723
        }
4724
    }
4725
4726
    return $deletedItems;
4727
}
4728
4729
/**
4730
 * @param int   $item_id
4731
 * @param array $courseInfo course info
4732
 *
4733
 * @return bool
4734
 */
4735
function deleteWorkItem($item_id, $courseInfo)
4736
{
4737
    $item_id = (int) $item_id;
4738
4739
    if (empty($item_id) || empty($courseInfo)) {
4740
        return false;
4741
    }
4742
4743
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4744
    $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
4745
    $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
4746
    $is_allowed_to_edit = api_is_allowed_to_edit();
4747
    $file_deleted = false;
4748
    $is_author = user_is_author($item_id);
4749
    $work_data = get_work_data_by_id($item_id);
4750
    $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
4751
    $course_id = $courseInfo['real_id'];
4752
4753
    if (($is_allowed_to_edit && $locked == false) ||
4754
        (
4755
            $locked == false &&
4756
            $is_author &&
4757
            api_get_course_setting('student_delete_own_publication') == 1 &&
4758
            $work_data['qualificator_id'] == 0
4759
        )
4760
    ) {
4761
        // We found the current user is the author
4762
        $sql = "SELECT url, contains_file, user_id, session_id, parent_id
4763
                FROM $work_table
4764
                WHERE c_id = $course_id AND id = $item_id";
4765
        $result = Database::query($sql);
4766
        $row = Database::fetch_array($result);
4767
        $count = Database::num_rows($result);
4768
4769
        if ($count > 0) {
4770
            // If the "considered_working_time" option is enabled, check
4771
            // whether some time should be removed from track_e_course_access
4772
            $consideredWorkingTime = api_get_configuration_value('considered_working_time');
4773
            if ($consideredWorkingTime) {
4774
                $userWorks = get_work_user_list(
4775
                    0,
4776
                    100,
4777
                    null,
4778
                    null,
4779
                    $row['parent_id'],
4780
                    null,
4781
                    $row['user_id'],
4782
                    false,
4783
                    $course_id,
4784
                    $row['session_id']
4785
                );
4786
                // We're only interested in deleting the time if this is the latest work sent
4787
                if (count($userWorks) == 1) {
4788
                    // Get the "considered work time" defined for this work
4789
                    $fieldValue = new ExtraFieldValue('work');
4790
                    $resultExtra = $fieldValue->getAllValuesForAnItem(
4791
                        $row['parent_id'],
4792
                        true
4793
                    );
4794
4795
                    $workingTime = null;
4796
                    foreach ($resultExtra as $field) {
4797
                        $field = $field['value'];
4798
4799
                        if ($consideredWorkingTime == $field->getField()->getVariable()) {
4800
                            $workingTime = $field->getValue();
4801
                        }
4802
                    }
4803
                    // If no time was defined, or a time of "0" was set, do nothing
4804
                    if (!empty($workingTime)) {
4805
                        $sessionId = empty($row['session_id']) ? 0 : $row['session_id'];
4806
                        // Getting false from the following call would mean the
4807
                        // time record
4808
                        Event::eventRemoveVirtualCourseTime(
4809
                            $course_id,
4810
                            $row['user_id'],
4811
                            $sessionId,
4812
                            $workingTime
4813
                        );
4814
                    }
4815
                }
4816
            } // end of considered_working_time check section
4817
4818
            $sql = "UPDATE $work_table SET active = 2
4819
                    WHERE c_id = $course_id AND id = $item_id";
4820
            Database::query($sql);
4821
            $sql = "DELETE FROM $TSTDPUBASG
4822
                    WHERE c_id = $course_id AND publication_id = $item_id";
4823
            Database::query($sql);
4824
4825
            Compilatio::plagiarismDeleteDoc($course_id, $item_id);
4826
4827
            api_item_property_update(
4828
                $courseInfo,
4829
                'work',
4830
                $item_id,
4831
                'DocumentDeleted',
4832
                api_get_user_id()
4833
            );
4834
4835
            Event::addEvent(
4836
                LOG_WORK_FILE_DELETE,
4837
                LOG_WORK_DATA,
4838
                [
4839
                    'id' => $work_data['id'],
4840
                    'url' => $work_data['url'],
4841
                    'title' => $work_data['title'],
4842
                ],
4843
                null,
4844
                api_get_user_id(),
4845
                api_get_course_int_id(),
4846
                api_get_session_id()
4847
            );
4848
4849
            $work = $row['url'];
4850
4851
            if ($row['contains_file'] == 1) {
4852
                if (!empty($work)) {
4853
                    if (api_get_setting('permanently_remove_deleted_files') === 'true') {
4854
                        my_delete($currentCourseRepositorySys.'/'.$work);
4855
                        $file_deleted = true;
4856
                    } else {
4857
                        $extension = pathinfo($work, PATHINFO_EXTENSION);
4858
                        $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
4859
4860
                        if (file_exists($currentCourseRepositorySys.'/'.$work)) {
4861
                            rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
4862
                            $file_deleted = true;
4863
                        }
4864
                    }
4865
                }
4866
            } else {
4867
                $file_deleted = true;
4868
            }
4869
        }
4870
    }
4871
4872
    return $file_deleted;
4873
}
4874
4875
/**
4876
 * @param FormValidator $form
4877
 * @param array         $defaults
4878
 * @param int           $workId
4879
 *
4880
 * @return FormValidator
4881
 */
4882
function getFormWork($form, $defaults = [], $workId = 0)
4883
{
4884
    $sessionId = api_get_session_id();
4885
    if (!empty($defaults)) {
4886
        if (isset($defaults['submit'])) {
4887
            unset($defaults['submit']);
4888
        }
4889
    }
4890
4891
    // Create the form that asks for the directory name
4892
    $form->addText('new_dir', get_lang('AssignmentName'));
4893
    $form->addHtmlEditor(
4894
        'description',
4895
        get_lang('Description'),
4896
        false,
4897
        false,
4898
        getWorkDescriptionToolbar()
4899
    );
4900
    $form->addButtonAdvancedSettings('advanced_params', get_lang('AdvancedParameters'));
4901
4902
    if (!empty($defaults) && (isset($defaults['enableEndDate']) || isset($defaults['enableExpiryDate']))) {
4903
        $form->addHtml('<div id="advanced_params_options" style="display:block">');
4904
    } else {
4905
        $form->addHtml('<div id="advanced_params_options" style="display:none">');
4906
    }
4907
4908
    // QualificationOfAssignment
4909
    $form->addElement('text', 'qualification', get_lang('QualificationNumeric'));
4910
4911
    if (($sessionId != 0 && Gradebook::is_active()) || $sessionId == 0) {
4912
        $form->addElement(
4913
            'checkbox',
4914
            'make_calification',
4915
            null,
4916
            get_lang('MakeQualifiable'),
4917
            [
4918
                'id' => 'make_calification_id',
4919
                'onclick' => "javascript: if(this.checked) { document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}",
4920
            ]
4921
        );
4922
    } else {
4923
        // QualificationOfAssignment
4924
        $form->addElement('hidden', 'make_calification', false);
4925
    }
4926
4927
    if (!empty($defaults) && isset($defaults['category_id'])) {
4928
        $form->addHtml('<div id=\'option1\' style="display:block">');
4929
    } else {
4930
        $form->addHtml('<div id=\'option1\' style="display:none">');
4931
    }
4932
4933
    // Loading Gradebook select
4934
    GradebookUtils::load_gradebook_select_in_tool($form);
4935
4936
    $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
4937
    $form->addHtml('</div>');
4938
4939
    $form->addElement('checkbox', 'enableExpiryDate', null, get_lang('EnableExpiryDate'), 'id="expiry_date"');
4940
    if (isset($defaults['enableExpiryDate']) && $defaults['enableExpiryDate']) {
4941
        $form->addHtml('<div id="option2" style="display: block;">');
4942
    } else {
4943
        $form->addHtml('<div id="option2" style="display: none;">');
4944
    }
4945
4946
    $timeNextWeek = time() + 86400 * 7;
4947
    $nextWeek = substr(api_get_local_time($timeNextWeek), 0, 10);
4948
    if (!isset($defaults['expires_on'])) {
4949
        $date = substr($nextWeek, 0, 10);
4950
        $defaults['expires_on'] = $date.' 23:59';
4951
    }
4952
4953
    $form->addElement('date_time_picker', 'expires_on', get_lang('ExpiresAt'));
4954
    $form->addHtml('</div>');
4955
    $form->addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'id="end_date"');
4956
4957
    if (!isset($defaults['ends_on'])) {
4958
        $nextDay = substr(api_get_local_time($timeNextWeek + 86400), 0, 10);
4959
        $date = substr($nextDay, 0, 10);
4960
        $defaults['ends_on'] = $date.' 23:59';
4961
    }
4962
    if (isset($defaults['enableEndDate']) && $defaults['enableEndDate']) {
4963
        $form->addHtml('<div id="option3" style="display: block;">');
4964
    } else {
4965
        $form->addHtml('<div id="option3" style="display: none;">');
4966
    }
4967
4968
    $form->addElement('date_time_picker', 'ends_on', get_lang('EndsAt'));
4969
    $form->addHtml('</div>');
4970
4971
    $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
4972
    $form->addElement('select', 'allow_text_assignment', get_lang('DocumentType'), getUploadDocumentType());
4973
4974
    // Extra fields
4975
    $extraField = new ExtraField('work');
4976
    $extra = $extraField->addElements($form, $workId);
4977
4978
    $htmlHeadXtra[] = '
4979
        <script>
4980
        $(function() {
4981
            '.$extra['jquery_ready_content'].'
4982
        });
4983
        </script>';
4984
4985
    $form->addHtml('</div>');
4986
4987
    $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_STUDENT_PUBLICATION, $workId);
4988
4989
    if (!empty($defaults)) {
4990
        $defaults['skills'] = array_keys($skillList);
4991
        $form->setDefaults($defaults);
4992
    }
4993
4994
    return $form;
4995
}
4996
4997
/**
4998
 * @return array
4999
 */
5000
function getUploadDocumentType()
5001
{
5002
    return [
5003
        0 => get_lang('AllowFileOrText'),
5004
        1 => get_lang('AllowOnlyText'),
5005
        2 => get_lang('AllowOnlyFiles'),
5006
    ];
5007
}
5008
5009
/**
5010
 * @param int   $itemId
5011
 * @param array $course_info
5012
 *
5013
 * @return bool
5014
 */
5015
function makeVisible($itemId, $course_info)
5016
{
5017
    $itemId = (int) $itemId;
5018
    if (empty($course_info) || empty($itemId)) {
5019
        return false;
5020
    }
5021
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
5022
    $course_id = $course_info['real_id'];
5023
5024
    $sql = "UPDATE $work_table SET accepted = 1
5025
            WHERE c_id = $course_id AND id = $itemId";
5026
    Database::query($sql);
5027
    api_item_property_update($course_info, 'work', $itemId, 'visible', api_get_user_id());
5028
5029
    return true;
5030
}
5031
5032
/**
5033
 * @param int   $itemId
5034
 * @param array $course_info
5035
 *
5036
 * @return int
5037
 */
5038
function makeInvisible($itemId, $course_info)
5039
{
5040
    $itemId = (int) $itemId;
5041
    if (empty($course_info) || empty($itemId)) {
5042
        return false;
5043
    }
5044
5045
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
5046
    $course_id = $course_info['real_id'];
5047
    $sql = "UPDATE $table
5048
            SET accepted = 0
5049
            WHERE c_id = $course_id AND id = '".$itemId."'";
5050
    Database::query($sql);
5051
    api_item_property_update(
5052
        $course_info,
5053
        'work',
5054
        $itemId,
5055
        'invisible',
5056
        api_get_user_id()
5057
    );
5058
5059
    return true;
5060
}
5061
5062
/**
5063
 * @param int    $item_id
5064
 * @param string $path
5065
 * @param array  $courseInfo
5066
 * @param int    $groupId    iid
5067
 * @param int    $sessionId
5068
 *
5069
 * @return string
5070
 */
5071
function generateMoveForm($item_id, $path, $courseInfo, $groupId, $sessionId)
5072
{
5073
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
5074
    $courseId = $courseInfo['real_id'];
5075
    $folders = [];
5076
    $session_id = (int) $sessionId;
5077
    $groupId = (int) $groupId;
5078
    $sessionCondition = empty($sessionId) ? ' AND (session_id = 0 OR session_id IS NULL) ' : " AND session_id='".$session_id."'";
5079
5080
    $groupIid = 0;
5081
    if ($groupId) {
5082
        $groupInfo = GroupManager::get_group_properties($groupId);
5083
        $groupIid = $groupInfo['iid'];
5084
    }
5085
5086
    $sql = "SELECT id, url, title
5087
            FROM $work_table
5088
            WHERE
5089
                c_id = $courseId AND
5090
                active IN (0, 1) AND
5091
                url LIKE '/%' AND
5092
                post_group_id = $groupIid
5093
                $sessionCondition";
5094
    $res = Database::query($sql);
5095
    while ($folder = Database::fetch_array($res)) {
5096
        $title = empty($folder['title']) ? basename($folder['url']) : $folder['title'];
5097
        $folders[$folder['id']] = $title;
5098
    }
5099
5100
    return build_work_move_to_selector($folders, $path, $item_id);
5101
}
5102
5103
/**
5104
 * @param int $workId
5105
 *
5106
 * @return string
5107
 */
5108
function showStudentList($workId)
5109
{
5110
    $columnModel = [
5111
        [
5112
            'name' => 'student',
5113
            'index' => 'student',
5114
            'width' => '350px',
5115
            'align' => 'left',
5116
            'sortable' => 'false',
5117
        ],
5118
        [
5119
            'name' => 'works',
5120
            'index' => 'works',
5121
            'align' => 'center',
5122
            'sortable' => 'false',
5123
        ],
5124
    ];
5125
    $token = null;
5126
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student_list_overview&work_id='.$workId.'&'.api_get_cidreq();
5127
5128
    $columns = [
5129
        get_lang('Students'),
5130
        get_lang('Works'),
5131
    ];
5132
5133
    $order = api_is_western_name_order() ? 'firstname' : 'lastname';
5134
    $params = [
5135
        'autowidth' => 'true',
5136
        'height' => 'auto',
5137
        'rowNum' => 5,
5138
        'sortname' => $order,
5139
        'sortorder' => 'asc',
5140
    ];
5141
5142
    $html = '<script>
5143
    $(function() {
5144
        '.Display::grid_js('studentList', $url, $columns, $columnModel, $params, [], null, true).'
5145
        $("#workList").jqGrid(
5146
            "navGrid",
5147
            "#studentList_pager",
5148
            { edit: false, add: false, del: false },
5149
            { height:280, reloadAfterSubmit:false }, // edit options
5150
            { height:280, reloadAfterSubmit:false }, // add options
5151
            { width:500 } // search options
5152
        );
5153
    });
5154
    </script>';
5155
    $html .= Display::grid_html('studentList');
5156
5157
    return $html;
5158
}
5159
5160
/**
5161
 * @param string $courseCode
5162
 * @param int    $sessionId
5163
 * @param int    $groupId
5164
 * @param int    $start
5165
 * @param int    $limit
5166
 * @param string $sidx
5167
 * @param string $sord
5168
 * @param $getCount
5169
 *
5170
 * @return array|int
5171
 */
5172
function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
5173
{
5174
    if (!empty($groupId)) {
5175
        $userList = GroupManager::get_users(
5176
            $groupId,
5177
            false,
5178
            $start,
5179
            $limit,
5180
            $getCount,
5181
            null,
5182
            $sidx,
5183
            $sord
5184
        );
5185
    } else {
5186
        $limitString = null;
5187
        if (!empty($start) && !empty($limit)) {
5188
            $start = (int) $start;
5189
            $limit = (int) $limit;
5190
            $limitString = " LIMIT $start, $limit";
5191
        }
5192
5193
        $orderBy = null;
5194
5195
        if (!empty($sidx) && !empty($sord)) {
5196
            if (in_array($sidx, ['firstname', 'lastname'])) {
5197
                $orderBy = "ORDER BY $sidx $sord";
5198
            }
5199
        }
5200
5201
        if (empty($sessionId)) {
5202
            $userList = CourseManager::get_user_list_from_course_code(
5203
                $courseCode,
5204
                $sessionId,
5205
                $limitString,
5206
                $orderBy,
5207
                STUDENT,
5208
                $getCount
5209
            );
5210
        } else {
5211
            $userList = CourseManager::get_user_list_from_course_code(
5212
                $courseCode,
5213
                $sessionId,
5214
                $limitString,
5215
                $orderBy,
5216
                0,
5217
                $getCount
5218
            );
5219
        }
5220
5221
        if ($getCount == false) {
5222
            $userList = array_keys($userList);
5223
        }
5224
    }
5225
5226
    return $userList;
5227
}
5228
5229
/**
5230
 * @param int    $workId
5231
 * @param string $courseCode
5232
 * @param int    $sessionId
5233
 * @param int    $groupId
5234
 * @param int    $start
5235
 * @param int    $limit
5236
 * @param int    $sidx
5237
 * @param string $sord
5238
 * @param bool   $getCount
5239
 *
5240
 * @return array|int
5241
 */
5242
function getWorkUserListData(
5243
    $workId,
5244
    $courseCode,
5245
    $sessionId,
5246
    $groupId,
5247
    $start,
5248
    $limit,
5249
    $sidx,
5250
    $sord,
5251
    $getCount = false
5252
) {
5253
    $my_folder_data = get_work_data_by_id($workId);
5254
    $workParents = [];
5255
    if (empty($my_folder_data)) {
5256
        $workParents = getWorkList($workId, $my_folder_data, null);
5257
    }
5258
5259
    $workIdList = [];
5260
    if (!empty($workParents)) {
5261
        foreach ($workParents as $work) {
5262
            $workIdList[] = $work->id;
5263
        }
5264
    }
5265
5266
    $courseInfo = api_get_course_info($courseCode);
5267
5268
    $userList = getWorkUserList(
5269
        $courseCode,
5270
        $sessionId,
5271
        $groupId,
5272
        $start,
5273
        $limit,
5274
        $sidx,
5275
        $sord,
5276
        $getCount
5277
    );
5278
5279
    if ($getCount) {
5280
        return $userList;
5281
    }
5282
    $results = [];
5283
    if (!empty($userList)) {
5284
        foreach ($userList as $userId) {
5285
            $user = api_get_user_info($userId);
5286
            $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
5287
            $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
5288
            $userWorks = 0;
5289
            if (!empty($workIdList)) {
5290
                $userWorks = getUniqueStudentAttempts(
5291
                    $workIdList,
5292
                    $groupId,
5293
                    $courseInfo['real_id'],
5294
                    $sessionId,
5295
                    $user['user_id']
5296
                );
5297
            }
5298
            $works = $userWorks." / ".count($workParents);
5299
            $results[] = [
5300
                'student' => $url,
5301
                'works' => Display::url($works, $link),
5302
            ];
5303
        }
5304
    }
5305
5306
    return $results;
5307
}
5308
5309
/**
5310
 * @param int   $id
5311
 * @param array $course_info
5312
 * @param bool  $isCorrection
5313
 *
5314
 * @return bool
5315
 */
5316
function downloadFile($id, $course_info, $isCorrection)
5317
{
5318
    return getFile($id, $course_info, true, $isCorrection, true);
5319
}
5320
5321
/**
5322
 * @param int   $id
5323
 * @param array $course_info
5324
 * @param bool  $download
5325
 * @param bool  $isCorrection
5326
 * @param bool  $forceAccessForCourseAdmins
5327
 *
5328
 * @return bool
5329
 */
5330
function getFile($id, $course_info, $download = true, $isCorrection = false, $forceAccessForCourseAdmins = false)
5331
{
5332
    $file = getFileContents($id, $course_info, 0, $isCorrection, $forceAccessForCourseAdmins);
5333
    if (!empty($file) && is_array($file)) {
5334
        return DocumentManager::file_send_for_download(
5335
            $file['path'],
5336
            $download,
5337
            $file['title']
5338
        );
5339
    }
5340
5341
    return false;
5342
}
5343
5344
/**
5345
 * Get the file contents for an assigment.
5346
 *
5347
 * @param int   $id
5348
 * @param array $courseInfo
5349
 * @param int   $sessionId
5350
 * @param bool  $correction
5351
 * @param bool  $forceAccessForCourseAdmins
5352
 *
5353
 * @return array|bool
5354
 */
5355
function getFileContents($id, $courseInfo, $sessionId = 0, $correction = false, $forceAccessForCourseAdmins = false)
5356
{
5357
    $id = (int) $id;
5358
    if (empty($courseInfo) || empty($id)) {
5359
        return false;
5360
    }
5361
    if (empty($sessionId)) {
5362
        $sessionId = api_get_session_id();
5363
    }
5364
5365
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
5366
    if (!empty($courseInfo['real_id'])) {
5367
        $sql = "SELECT *
5368
                FROM $table
5369
                WHERE c_id = ".$courseInfo['real_id']." AND id = $id";
5370
5371
        $result = Database::query($sql);
5372
        if ($result && Database::num_rows($result)) {
5373
            $row = Database::fetch_array($result, 'ASSOC');
5374
5375
            if ($correction) {
5376
                $row['url'] = $row['url_correction'];
5377
            }
5378
5379
            if (empty($row['url'])) {
5380
                return false;
5381
            }
5382
5383
            $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
5384
5385
            $item_info = api_get_item_property_info(
5386
                api_get_course_int_id(),
5387
                'work',
5388
                $row['id'],
5389
                $sessionId
5390
            );
5391
5392
            if (empty($item_info)) {
5393
                return false;
5394
            }
5395
5396
            $isAllow = allowOnlySubscribedUser(
5397
                api_get_user_id(),
5398
                $row['parent_id'],
5399
                $courseInfo['real_id'],
5400
                $forceAccessForCourseAdmins
5401
            );
5402
5403
            if (empty($isAllow)) {
5404
                return false;
5405
            }
5406
5407
            /*
5408
            field show_score in table course :
5409
                0 =>    New documents are visible for all users
5410
                1 =>    New documents are only visible for the teacher(s)
5411
            field visibility in table item_property :
5412
                0 => eye closed, invisible for all students
5413
                1 => eye open
5414
            field accepted in table c_student_publication :
5415
                0 => eye closed, invisible for all students
5416
                1 => eye open
5417
            ( We should have visibility == accepted, otherwise there is an
5418
            inconsistency in the Database)
5419
            field value in table c_course_setting :
5420
                0 => Allow learners to delete their own publications = NO
5421
                1 => Allow learners to delete their own publications = YES
5422
5423
            +------------------+-------------------------+------------------------+
5424
            |Can download work?| doc visible for all = 0 | doc visible for all = 1|
5425
            +------------------+-------------------------+------------------------+
5426
            |  visibility = 0  | editor only             | editor only            |
5427
            |                  |                         |                        |
5428
            +------------------+-------------------------+------------------------+
5429
            |  visibility = 1  | editor                  | editor                 |
5430
            |                  | + owner of the work     | + any student          |
5431
            +------------------+-------------------------+------------------------+
5432
            (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
5433
            */
5434
5435
            $work_is_visible = $item_info['visibility'] == 1 && $row['accepted'] == 1;
5436
            $doc_visible_for_all = (int) $courseInfo['show_score'] === 0;
5437
5438
            $is_editor = api_is_allowed_to_edit(true, true, true);
5439
            $student_is_owner_of_work = user_is_author($row['id'], api_get_user_id());
5440
5441
            if (($forceAccessForCourseAdmins && $isAllow) ||
5442
                $is_editor ||
5443
                $student_is_owner_of_work ||
5444
                ($doc_visible_for_all && $work_is_visible)
5445
            ) {
5446
                $title = $row['title'];
5447
                if ($correction) {
5448
                    $title = $row['title_correction'];
5449
                }
5450
                if (array_key_exists('filename', $row) && !empty($row['filename'])) {
5451
                    $title = $row['filename'];
5452
                }
5453
5454
                $title = str_replace(' ', '_', $title);
5455
5456
                if ($correction == false) {
5457
                    $userInfo = api_get_user_info($row['user_id']);
5458
                    if ($userInfo) {
5459
                        $date = api_get_local_time($row['sent_date']);
5460
                        $date = str_replace([':', '-', ' '], '_', $date);
5461
                        $title = $date.'_'.$userInfo['username'].'_'.$title;
5462
                    }
5463
                }
5464
5465
                if (Security::check_abs_path(
5466
                    $full_file_name,
5467
                    api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'
5468
                )) {
5469
                    Event::event_download($title);
5470
5471
                    return [
5472
                        'path' => $full_file_name,
5473
                        'title' => $title,
5474
                        'title_correction' => $row['title_correction'],
5475
                    ];
5476
                }
5477
            }
5478
        }
5479
    }
5480
5481
    return false;
5482
}
5483
5484
/**
5485
 * @param int    $userId
5486
 * @param array  $courseInfo
5487
 * @param string $format
5488
 *
5489
 * @return bool
5490
 */
5491
function exportAllWork($userId, $courseInfo, $format = 'pdf')
5492
{
5493
    $userInfo = api_get_user_info($userId);
5494
    if (empty($userInfo) || empty($courseInfo)) {
5495
        return false;
5496
    }
5497
5498
    $workPerUser = getWorkPerUser($userId);
5499
5500
    switch ($format) {
5501
        case 'pdf':
5502
            if (!empty($workPerUser)) {
5503
                $pdf = new PDF();
5504
5505
                $content = null;
5506
                foreach ($workPerUser as $work) {
5507
                    $work = $work['work'];
5508
                    foreach ($work->user_results as $userResult) {
5509
                        $content .= $userResult['title'];
5510
                        // No need to use api_get_local_time()
5511
                        $content .= $userResult['sent_date'];
5512
                        $content .= $userResult['qualification'];
5513
                        $content .= $userResult['description'];
5514
                    }
5515
                }
5516
5517
                if (!empty($content)) {
5518
                    $pdf->content_to_pdf(
5519
                        $content,
5520
                        null,
5521
                        api_replace_dangerous_char($userInfo['complete_name']),
5522
                        $courseInfo['code']
5523
                    );
5524
                }
5525
            }
5526
            break;
5527
    }
5528
}
5529
5530
/**
5531
 * @param int    $workId
5532
 * @param array  $courseInfo
5533
 * @param int    $sessionId
5534
 * @param string $format
5535
 *
5536
 * @return bool
5537
 */
5538
function exportAllStudentWorkFromPublication(
5539
    $workId,
5540
    $courseInfo,
5541
    $sessionId,
5542
    $format = 'pdf'
5543
) {
5544
    if (empty($courseInfo)) {
5545
        return false;
5546
    }
5547
5548
    $workData = get_work_data_by_id($workId);
5549
    if (empty($workData)) {
5550
        return false;
5551
    }
5552
5553
    $assignment = get_work_assignment_by_id($workId);
5554
5555
    $courseCode = $courseInfo['code'];
5556
    $header = get_lang('Course').': '.$courseInfo['title'];
5557
    $teachers = CourseManager::getTeacherListFromCourseCodeToString(
5558
        $courseCode
5559
    );
5560
5561
    if (!empty($sessionId)) {
5562
        $sessionInfo = api_get_session_info($sessionId);
5563
        if (!empty($sessionInfo)) {
5564
            $header .= ' - '.$sessionInfo['name'];
5565
            $header .= '<br />'.$sessionInfo['description'];
5566
            $teachers = SessionManager::getCoachesByCourseSessionToString(
5567
                $sessionId,
5568
                $courseInfo['real_id']
5569
            );
5570
        }
5571
    }
5572
5573
    $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
5574
    $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
5575
    $header .= '<br />'.get_lang('WorkName').': '.$workData['title'].'<br />';
5576
5577
    $content = null;
5578
    $expiresOn = null;
5579
5580
    if (!empty($assignment) && isset($assignment['expires_on'])) {
5581
        $content .= '<br /><strong>'.get_lang('PostedExpirationDate').'</strong>: '.api_get_local_time($assignment['expires_on']);
5582
        $expiresOn = api_get_local_time($assignment['expires_on']);
5583
    }
5584
5585
    if (!empty($workData['description'])) {
5586
        $content .= '<br /><strong>'.get_lang('Description').'</strong>: '.$workData['description'];
5587
    }
5588
5589
    $workList = get_work_user_list(null, null, null, null, $workId);
5590
5591
    switch ($format) {
5592
        case 'pdf':
5593
            if (!empty($workList)) {
5594
                $table = new HTML_Table(['class' => 'data_table']);
5595
                $headers = [
5596
                    get_lang('Name'),
5597
                    get_lang('User'),
5598
                    get_lang('HandOutDateLimit'),
5599
                    get_lang('SentDate'),
5600
                    get_lang('FileName'),
5601
                    get_lang('Score'),
5602
                    get_lang('Feedback'),
5603
                ];
5604
5605
                $column = 0;
5606
                foreach ($headers as $header) {
5607
                    $table->setHeaderContents(0, $column, $header);
5608
                    $column++;
5609
                }
5610
5611
                $row = 1;
5612
5613
                //$pdf->set_custom_header($header);
5614
                foreach ($workList as $work) {
5615
                    $content .= '<hr />';
5616
                    // getWorkComments need c_id
5617
                    $work['c_id'] = $courseInfo['real_id'];
5618
5619
                    //$content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
5620
                    $score = null;
5621
                    if (!empty($work['qualification_only'])) {
5622
                        $score = $work['qualification_only'];
5623
                    }
5624
5625
                    $comments = getWorkComments($work);
5626
5627
                    $feedback = null;
5628
                    if (!empty($comments)) {
5629
                        $content .= '<h4>'.get_lang('Feedback').': </h4>';
5630
                        foreach ($comments as $comment) {
5631
                            $feedback .= get_lang('User').': '.$comment['complete_name'].
5632
                                '<br />';
5633
                            $feedback .= $comment['comment'].'<br />';
5634
                        }
5635
                    }
5636
                    $table->setCellContents($row, 0, strip_tags($workData['title']));
5637
                    $table->setCellContents($row, 1, strip_tags($work['fullname']));
5638
                    $table->setCellContents($row, 2, $expiresOn);
5639
                    $table->setCellContents($row, 3, api_get_local_time($work['sent_date_from_db']));
5640
                    $table->setCellContents($row, 4, strip_tags($work['title']));
5641
                    $table->setCellContents($row, 5, $score);
5642
                    $table->setCellContents($row, 6, $feedback);
5643
5644
                    $row++;
5645
                }
5646
5647
                $content = $table->toHtml();
5648
5649
                if (!empty($content)) {
5650
                    $params = [
5651
                        'filename' => $workData['title'].'_'.api_get_local_time(),
5652
                        'pdf_title' => api_replace_dangerous_char($workData['title']),
5653
                        'course_code' => $courseInfo['code'],
5654
                    ];
5655
                    $pdf = new PDF('A4', null, $params);
5656
                    $pdf->html_to_pdf_with_template($content);
5657
                }
5658
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
5659
            }
5660
            break;
5661
    }
5662
}
5663
5664
/**
5665
 * Downloads all user files per user.
5666
 *
5667
 * @param int   $userId
5668
 * @param array $courseInfo
5669
 *
5670
 * @return bool
5671
 */
5672
function downloadAllFilesPerUser($userId, $courseInfo)
5673
{
5674
    $userInfo = api_get_user_info($userId);
5675
5676
    if (empty($userInfo) || empty($courseInfo)) {
5677
        return false;
5678
    }
5679
5680
    $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
5681
    $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/';
5682
    $zip = new PclZip($tempZipFile);
5683
    $workPerUser = getWorkPerUser($userId);
5684
5685
    if (!empty($workPerUser)) {
5686
        $files = [];
5687
        foreach ($workPerUser as $work) {
5688
            $work = $work['work'];
5689
            foreach ($work->user_results as $userResult) {
5690
                if (empty($userResult['url']) || empty($userResult['contains_file'])) {
5691
                    continue;
5692
                }
5693
                $data = getFileContents($userResult['id'], $courseInfo);
5694
                if (!empty($data) && isset($data['path'])) {
5695
                    $files[basename($data['path'])] = [
5696
                        'title' => $data['title'],
5697
                        'path' => $data['path'],
5698
                    ];
5699
                }
5700
            }
5701
        }
5702
5703
        if (!empty($files)) {
5704
            Session::write('files', $files);
5705
            foreach ($files as $data) {
5706
                $zip->add(
5707
                    $data['path'],
5708
                    PCLZIP_OPT_REMOVE_PATH,
5709
                    $coursePath,
5710
                    PCLZIP_CB_PRE_ADD,
5711
                    'preAddAllWorkStudentCallback'
5712
                );
5713
            }
5714
        }
5715
5716
        // Start download of created file
5717
        $name = basename(api_replace_dangerous_char($userInfo['complete_name'])).'.zip';
5718
        Event::event_download($name.'.zip (folder)');
5719
        if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
5720
            DocumentManager::file_send_for_download($tempZipFile, true, $name);
5721
            @unlink($tempZipFile);
5722
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
5723
        }
5724
    }
5725
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
5726
}
5727
5728
/**
5729
 * @param $p_event
5730
 * @param array $p_header
5731
 *
5732
 * @return int
5733
 */
5734
function preAddAllWorkStudentCallback($p_event, &$p_header)
5735
{
5736
    $files = Session::read('files');
5737
    if (isset($files[basename($p_header['stored_filename'])])) {
5738
        $p_header['stored_filename'] = $files[basename($p_header['stored_filename'])]['title'];
5739
5740
        return 1;
5741
    }
5742
5743
    return 0;
5744
}
5745
5746
/**
5747
 * Get all work created by a user.
5748
 *
5749
 * @param int $user_id
5750
 * @param int $courseId
5751
 * @param int $sessionId
5752
 *
5753
 * @return array
5754
 */
5755
function getWorkCreatedByUser($user_id, $courseId, $sessionId)
5756
{
5757
    $items = api_get_item_property_list_by_tool_by_user(
5758
        $user_id,
5759
        'work',
5760
        $courseId,
5761
        $sessionId
5762
    );
5763
5764
    $list = [];
5765
    if (!empty($items)) {
5766
        foreach ($items as $work) {
5767
            $item = get_work_data_by_id(
5768
                $work['ref'],
5769
                $courseId,
5770
                $sessionId
5771
            );
5772
            if (!empty($item)) {
5773
                $list[] = [
5774
                    $item['title'],
5775
                    api_get_local_time($work['insert_date']),
5776
                    api_get_local_time($work['lastedit_date']),
5777
                ];
5778
            }
5779
        }
5780
    }
5781
5782
    return $list;
5783
}
5784
5785
/**
5786
 * @param array $courseInfo
5787
 * @param int   $workId
5788
 *
5789
 * @return bool
5790
 */
5791
function protectWork($courseInfo, $workId)
5792
{
5793
    $userId = api_get_user_id();
5794
    $groupId = api_get_group_id();
5795
    $sessionId = api_get_session_id();
5796
    $workData = get_work_data_by_id($workId);
5797
5798
    if (empty($workData) || empty($courseInfo)) {
5799
        api_not_allowed(true);
5800
    }
5801
5802
    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
5803
        return true;
5804
    }
5805
5806
    $workId = $workData['id'];
5807
5808
    if ($workData['active'] != 1) {
5809
        api_not_allowed(true);
5810
    }
5811
5812
    $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
5813
5814
    if ($visibility != 1) {
5815
        api_not_allowed(true);
5816
    }
5817
5818
    $isAllow = allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
5819
    if (empty($isAllow)) {
5820
        api_not_allowed(true);
5821
    }
5822
5823
    $groupInfo = GroupManager::get_group_properties($groupId);
5824
5825
    if (!empty($groupId)) {
5826
        $showWork = GroupManager::user_has_access(
5827
            $userId,
5828
            $groupInfo['iid'],
5829
            GroupManager::GROUP_TOOL_WORK
5830
        );
5831
        if (!$showWork) {
5832
            api_not_allowed(true);
5833
        }
5834
    }
5835
}
5836
5837
/**
5838
 * @param array $courseInfo
5839
 * @param array $work
5840
 */
5841
function deleteCorrection($courseInfo, $work)
5842
{
5843
    if (isset($work['url_correction']) && !empty($work['url_correction']) && isset($work['iid'])) {
5844
        $id = $work['iid'];
5845
        $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
5846
        $sql = "UPDATE $table SET
5847
                    url_correction = '',
5848
                    title_correction = ''
5849
                WHERE iid = $id";
5850
        Database::query($sql);
5851
        $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
5852
        if (file_exists($coursePath.$work['url_correction'])) {
5853
            if (Security::check_abs_path($coursePath.$work['url_correction'], $coursePath)) {
5854
                unlink($coursePath.$work['url_correction']);
5855
            }
5856
        }
5857
    }
5858
}
5859
5860
/**
5861
 * @param int $workId
5862
 *
5863
 * @return string
5864
 */
5865
function workGetExtraFieldData($workId)
5866
{
5867
    $sessionField = new ExtraField('work');
5868
    $extraFieldData = $sessionField->getDataAndFormattedValues($workId);
5869
    $result = '';
5870
    if (!empty($extraFieldData)) {
5871
        $result .= '<div class="well">';
5872
        foreach ($extraFieldData as $data) {
5873
            $result .= $data['text'].': <b>'.$data['value'].'</b>';
5874
        }
5875
        $result .= '</div>';
5876
    }
5877
5878
    return $result;
5879
}
5880