Completed
Push — master ( 6f5084...9b811e )
by Julito
14:55
created

uploadWork()   B

Complexity

Conditions 9
Paths 14

Size

Total Lines 93
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 38
nc 14
nop 5
dl 0
loc 93
rs 7.7564
c 0
b 0
f 0

How to fix   Long Method   

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