Passed
Push — 1.11.x ( 340c2f...932035 )
by Julito
10:42
created

showStudentAllWorkGrid()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 43
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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