Passed
Push — 1.11.x ( 018de8...7b54c8 )
by Julito
09:51
created

getWorkCommentForm()   C

Complexity

Conditions 12
Paths 144

Size

Total Lines 68
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 12
eloc 45
c 2
b 0
f 0
nc 144
nop 2
dl 0
loc 68
rs 6.6

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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