Completed
Pull Request — 1.10.x (#1244)
by
unknown
42:26
created

work.lib.php ➔ plagiarismDeleteDoc()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 8
rs 9.4285
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 *  @package chamilo.work
8
 *  @author Thomas, Hugues, Christophe - original version
9
 *  @author Patrick Cool <[email protected]>, Ghent University -
10
 * ability for course admins to specify wether uploaded documents are visible or invisible by default.
11
 *  @author Roan Embrechts, code refactoring and virtual course support
12
 *  @author Frederic Vauthier, directories management
13
 *  @author Julio Montoya <[email protected]> BeezNest 2011 LOTS of bug fixes
14
 *  @todo   this lib should be convert in a static class and moved to main/inc/lib
15
 */
16
17
/**
18
 * Displays action links (for admins, authorized groups members and authorized students)
19
 * @param   string  Current dir
20
 * @param   integer Whether to show tool options
21
 * @param   integer Whether to show upload form option
22
 * @return  void
23
 */
24
function display_action_links($id, $cur_dir_path, $action)
25
{
26
    global $gradebook;
27
28
    $id = $my_back_id = intval($id);
29
    if ($action == 'list') {
30
        $my_back_id = 0;
31
    }
32
33
    $display_output = '';
34
    $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '';
35
36
    if (!empty($id)) {
37
        $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'&id='.$my_back_id.'">'.
38
            Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
39
    }
40
41
    if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath') {
42
        // Create dir
43
        if (empty($id)) {
44
            $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=create_dir&origin='.$origin.'&gradebook='.$gradebook.'">';
45
            $display_output .= Display::return_icon('new_work.png', get_lang('CreateAssignment'),'',ICON_SIZE_MEDIUM).'</a>';
46
        }
47
        if (empty($id)) {
48
            // Options
49
            $display_output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=settings&origin='.$origin.'&gradebook='.$gradebook.'">';
50
            $display_output .= Display::return_icon('settings.png', get_lang('EditToolOptions'),'',ICON_SIZE_MEDIUM).'</a>';
51
        }
52
        $display_output .= '<a id="open-view-list" href="#">' . Display::return_icon('listwork.png', get_lang('ViewStudents'),'',ICON_SIZE_MEDIUM) . '</a>';
53
54
    }
55
56
    if (api_is_allowed_to_edit(null, true) && $origin != 'learnpath' && api_is_allowed_to_session_edit(false, true)) {
57
        // Delete all files
58
        if (api_get_setting('permanently_remove_deleted_files') == 'true'){
59
            $message = get_lang('ConfirmYourChoiceDeleteAllfiles');
60
        } else {
61
            $message = get_lang('ConfirmYourChoice');
62
        }
63
    }
64
65
    if ($display_output != '') {
66
        echo '<div class="actions">';
67
        echo $display_output;
68
        echo '</div>';
69
    }
70
}
71
72
/**
73
 * Returns a form displaying all options for this tool.
74
 * These are
75
 * - make all files visible / invisible
76
 * - set the default visibility of uploaded files
77
 * @param $defaults
78
 * @return string The HTML form
79
 */
80
function settingsForm($defaults)
81
{
82
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
83
84
    if (!$is_allowed_to_edit) {
85
        return;
86
    }
87
88
    $url = api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq().'&action=settings';
89
    $form = new FormValidator('edit_settings', 'post', $url);
90
    $form->addElement('hidden', 'changeProperties', 1);
91
    $form->addElement('header', get_lang('EditToolOptions'));
92
93
    $group = array(
94
        $form->createElement('radio', 'show_score', null, get_lang('NewVisible'), 0),
95
        $form->createElement('radio', 'show_score', null, get_lang('NewUnvisible'), 1)
96
    );
97
    $form->addGroup($group, '', get_lang('DefaultUpload'));
98
99
    $group = array(
100
        $form->createElement('radio', 'student_delete_own_publication', null, get_lang('Yes'), 1),
101
        $form->createElement('radio', 'student_delete_own_publication', null, get_lang('No'), 0)
102
    );
103
    $form->addGroup($group, '', get_lang('StudentAllowedToDeleteOwnPublication'));
104
    $form->addButtonSave(get_lang('Save'));
105
    $form->setDefaults($defaults);
106
107
    return $form->returnForm();
108
}
109
110
/**
111
 * converts 1-9 to 01-09
112
 */
113
function two_digits($number)
114
{
115
    $number = (int)$number;
116
    return ($number < 10) ? '0'.$number : $number;
117
}
118
119
/**
120
 * Converts 2008-10-06 12:45:00 to -> array('prefix' => array(year'=>2008, 'month'=>10, etc...)
121
 * @param string
122
 * @param string
123
 * @param array
124
 */
125
function convert_date_to_array($date, $group)
126
{
127
    $parts = explode(' ', $date);
128
    $date_parts = explode('-', $parts[0]);
129
    $date_parts_tmp = array();
130
    foreach ($date_parts as $item) {
131
        $date_parts_tmp[] = intval($item);
132
    }
133
134
    $time_parts = explode(':', $parts[1]);
135
    $time_parts_tmp = array();
136
    foreach ($time_parts as $item) {
137
        $time_parts_tmp[] = intval($item);
138
    }
139
    list($data[$group]['year'], $data[$group]['month'], $data[$group]['day']) = $date_parts_tmp;
140
    list($data[$group]['hour'], $data[$group]['minute']) = $time_parts_tmp;
141
    return $data;
0 ignored issues
show
Bug introduced by
The variable $data does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
142
}
143
144
/**
145
 * get date from a group of date
146
 */
147 View Code Duplication
function get_date_from_group($group)
148
{
149
    return
150
        $_POST[$group]['year'].'-'.
151
        two_digits($_POST[$group]['month']).'-'.
152
        two_digits($_POST[$group]['day']).' '.
153
        two_digits($_POST[$group]['hour']).':'.
154
        two_digits($_POST[$group]['minute']).':00';
155
}
156
157
/**
158
 * Create a group of select from a date
159
 * @param FormValidator $form
160
 * @param string $prefix
161
 * @return array
162
 */
163
function create_group_date_select($form, $prefix = '')
164
{
165
    $minute = range(10, 59);
166
    $d_year = date('Y');
167
    array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
168
169
    $group_name = array(
170
        $form->createElement('select', $prefix.'day', '', array_combine(range(1, 31), range(1, 31))),
171
        $form->createElement('select', $prefix.'month', '', array_combine(range(1, 12), api_get_months_long())),
172
        $form->createElement('select', $prefix.'year', '', array($d_year => $d_year, $d_year + 1 => $d_year + 1)),
173
        $form->createElement('select', $prefix.'hour', '', array_combine(range(0, 23), range(0, 23))),
174
        $form->createElement('select', $prefix.'minute', '', $minute)
175
    );
176
    return $group_name;
177
}
178
179
/**
180
 * @param string $path
181
 * @param int $courseId
182
 *
183
 * @return array
184
 */
185 View Code Duplication
function get_work_data_by_path($path, $courseId = null)
186
{
187
    $path = Database::escape_string($path);
188
    if (empty($courseId)) {
189
        $courseId = api_get_course_int_id();
190
    } else {
191
        $courseId = intval($courseId);
192
    }
193
194
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
195
    $sql = "SELECT *  FROM  ".$work_table."
196
            WHERE url = '$path' AND c_id = $courseId ";
197
    $result = Database::query($sql);
198
    $return = array();
199
    if (Database::num_rows($result)) {
200
        $return = Database::fetch_array($result, 'ASSOC');
201
    }
202
203
    return $return;
204
}
205
206
/**
207
 * @param int $id
208
 * @param int $courseId
209
 * @param int $sessionId
210
 * @return array
211
 */
212
function get_work_data_by_id($id, $courseId = null, $sessionId = null)
213
{
214
    $id = intval($id);
215
216
    if (!empty($courseId)) {
217
        $courseId = intval($courseId);
218
    } else {
219
        $courseId = api_get_course_int_id();
220
    }
221
222
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
223
224
    $sessionCondition = null;
225
    if (!empty($sessionId)) {
226
        $sessionCondition = api_get_session_condition($sessionId, true);
227
    }
228
229
    $sql = "SELECT * FROM $table
230
            WHERE
231
                id = $id AND c_id = $courseId
232
                $sessionCondition";
233
    $result = Database::query($sql);
234
    $work = array();
235
    if (Database::num_rows($result)) {
236
        $work = Database::fetch_array($result, 'ASSOC');
237
        if (empty($work['title'])) {
238
            $work['title'] = basename($work['url']);
239
        }
240
        $work['download_url'] = api_get_path(WEB_CODE_PATH).'work/download.php?id='.$work['id'].'&'.api_get_cidreq();
241
        $work['view_url'] = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&'.api_get_cidreq();
242
        $work['show_url'] = api_get_path(WEB_CODE_PATH).'work/show_file.php?id='.$work['id'].'&'.api_get_cidreq();
243
        $work['show_content'] = '';
244
        if ($work['contains_file']) {
245
            $fileInfo = pathinfo($work['title']);
246
            if (is_array($fileInfo) &&
247
                !empty($fileInfo['extension']) &&
248
                in_array($fileInfo['extension'], array('jpg', 'png', 'gif'))
249
            ) {
250
                $work['show_content'] = '<img src="'.$work['show_url'].'"/>';
251
            }
252
        }
253
    }
254
255
    return $work;
256
}
257
258
/**
259
 * @param int $user_id
260
 * @param int $work_id
261
 *
262
 * @return int
263
 */
264
function get_work_count_by_student($user_id, $work_id)
265
{
266
    $user_id = intval($user_id);
267
    $work_id = intval($work_id);
268
    $course_id = api_get_course_int_id();
269
    $session_id = api_get_session_id();
270
271
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
272
    $sql = "SELECT COUNT(*) as count
273
            FROM  $table
274
            WHERE
275
                c_id = $course_id AND
276
                parent_id = $work_id AND
277
                user_id = $user_id AND
278
                active IN (0, 1) AND
279
                session_id = $session_id ";
280
    $result = Database::query($sql);
281
    $return = 0;
282
    if (Database::num_rows($result)) {
283
        $return = Database::fetch_row($result, 'ASSOC');
284
        $return = intval($return[0]);
285
    }
286
287
    return $return;
288
}
289
290
/**
291
 * @param int $id
292
 * @param int $courseId
293
 *
294
 * @return array
295
 */
296 View Code Duplication
function get_work_assignment_by_id($id, $courseId = null)
297
{
298
    if (empty($courseId)) {
299
        $courseId = api_get_course_int_id();
300
    } else {
301
        $courseId = intval($courseId);
302
    }
303
    $id = intval($id);
304
305
    $table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
306
    $sql = "SELECT * FROM $table
307
            WHERE c_id = $courseId AND publication_id = $id";
308
    $result = Database::query($sql);
309
    $return = array();
310
    if (Database::num_rows($result)) {
311
        $return = Database::fetch_array($result, 'ASSOC');
312
    }
313
314
    return $return;
315
}
316
317
/**
318
 * @param int $id
319
 * @param array $my_folder_data
320
 * @param string $add_in_where_query
321
 *
322
 * @return array
323
 */
324
function getWorkList($id, $my_folder_data, $add_in_where_query = null)
325
{
326
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
327
328
    $course_id = api_get_course_int_id();
329
    $session_id = api_get_session_id();
330
    $condition_session = api_get_session_condition($session_id);
331
    $group_id = api_get_group_id();
332
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
333
334
    $linkInfo = GradebookUtils::is_resource_in_course_gradebook(
335
        api_get_course_id(),
336
        3,
337
        $id,
338
        api_get_session_id()
339
    );
340
341
    if ($linkInfo) {
342
        $workInGradeBookLinkId = $linkInfo['id'];
343
        if ($workInGradeBookLinkId) {
344
            if ($is_allowed_to_edit) {
345
                if (intval($my_folder_data['qualification']) == 0) {
346
                    Display::display_warning_message(
347
                        get_lang('MaxWeightNeedToBeProvided')
348
                    );
349
                }
350
            }
351
        }
352
    }
353
354
    $contains_file_query = '';
355
356
    // Get list from database
357
    if ($is_allowed_to_edit) {
358
        $active_condition = ' active IN (0, 1)';
359
        $sql = "SELECT * FROM $work_table
360
                WHERE
361
                    c_id = $course_id
362
                    $add_in_where_query
363
                    $condition_session AND
364
                    $active_condition AND
365
                    (parent_id = 0)
366
                    $contains_file_query AND
367
                    post_group_id = '".$group_id."'
368
                ORDER BY sent_date DESC";
369
    } else {
370 View Code Duplication
        if (!empty($group_id)) {
371
            // set to select only messages posted by the user's group
372
            $group_query = " WHERE c_id = $course_id AND post_group_id = '".$group_id."' ";
373
            $subdirs_query = "AND parent_id = 0";
374
        } else {
375
            $group_query = " WHERE c_id = $course_id AND  post_group_id = '0' ";
376
            $subdirs_query = "AND parent_id = 0";
377
        }
378
        //@todo how we can active or not an assignment?
379
        $active_condition = ' AND active IN (1, 0)';
380
        $sql = "SELECT * FROM  $work_table
381
                $group_query
382
                $subdirs_query
383
                $add_in_where_query
384
                $active_condition
385
                $condition_session
386
                ORDER BY title";
387
    }
388
389
    $work_parents = array();
390
391
    $sql_result = Database::query($sql);
392
    if (Database::num_rows($sql_result)) {
393
        while ($work = Database::fetch_object($sql_result)) {
394
            if ($work->parent_id == 0) {
395
                $work_parents[] = $work;
396
            }
397
        }
398
    }
399
400
    return $work_parents;
401
}
402
403
/**
404
 * @param int $userId
405
 * @return array
406
 */
407
function getWorkPerUser($userId)
408
{
409
    $works = getWorkList(null, null, null);
410
    $result = array();
411
    if (!empty($works)) {
412
        foreach ($works as $workData) {
413
            $workId = $workData->id;
414
            $result[$workId]['work'] = $workData;
415
            $result[$workId]['work']->user_results = get_work_user_list(
416
                0,
417
                100,
418
                null,
419
                null,
420
                $workId,
421
                null,
422
                $userId
423
            );
424
        }
425
    }
426
    return $result;
427
}
428
429
/**
430
 * @param int $workId
431
 * @param int $groupId
432
 * @param int $course_id
433
 * @param int $sessionId
434
 * @return mixed
435
 */
436
function getUniqueStudentAttemptsTotal($workId, $groupId, $course_id, $sessionId)
437
{
438
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
439
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
440
    $course_id = intval($course_id);
441
    $workId = intval($workId);
442
    $sessionId = intval($sessionId);
443
    $groupId = intval($groupId);
444
445
    $sql = "SELECT count(DISTINCT u.user_id)
446
            FROM $work_table w
447
            INNER JOIN $user_table u
448
                ON w.user_id = u.user_id
449
            WHERE
450
                w.c_id = $course_id AND
451
                w.session_id = $sessionId AND
452
                w.parent_id = ".$workId." AND
453
                w.post_group_id = ".$groupId." AND
454
                w.active IN (0, 1)
455
            ";
456
457
    $res_document = Database::query($sql);
458
    $rowCount = Database::fetch_row($res_document);
459
460
    return $rowCount[0];
461
}
462
463
/**
464
 * @param mixed $workId
465
 * @param int $groupId
466
 * @param int $course_id
467
 * @param int $sessionId
468
 * @param int $userId user id to filter
469
 * @param array $onlyUserList only parse this user list
470
 * @return mixed
471
 */
472
function getUniqueStudentAttempts(
473
    $workId,
474
    $groupId,
475
    $course_id,
476
    $sessionId,
477
    $userId = null,
478
    $onlyUserList = array()
479
) {
480
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
481
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
482
483
    $course_id = intval($course_id);
484
    $workCondition = null;
485
    if (is_array($workId)) {
486
        $workId = array_map('intval', $workId);
487
        $workId = implode("','", $workId);
488
        $workCondition = " w.parent_id IN ('".$workId."') AND";
489
    } else {
490
        $workId = intval($workId);
491
        $workCondition = " w.parent_id = ".$workId." AND";
492
    }
493
494
    $sessionId = intval($sessionId);
495
    $groupId = intval($groupId);
496
497
    $studentCondition = null;
498
499 View Code Duplication
    if (!empty($onlyUserList)) {
500
        $onlyUserList = array_map('intval', $onlyUserList);
501
        $studentCondition = "AND u.user_id IN ('".implode("', '", $onlyUserList)."') ";
502
    } else {
503
        if (empty($userId)) {
504
            return 0;
505
        }
506
    }
507
508
    $sql = "SELECT count(*) FROM (
509
                SELECT count(*), w.parent_id
510
                FROM $work_table w
511
                INNER JOIN $user_table u
512
                    ON w.user_id = u.user_id
513
                WHERE
514
                    w.filetype = 'file' AND
515
                    w.c_id = $course_id AND
516
                    w.session_id = $sessionId AND
517
                    $workCondition
518
                    w.post_group_id = ".$groupId." AND
519
                    w.active IN (0, 1) $studentCondition
520
                ";
521
    if (!empty($userId)) {
522
        $userId = intval($userId);
523
        $sql .= " AND u.user_id = ".$userId;
524
    }
525
    $sql .= " GROUP BY u.user_id, w.parent_id) as t";
526
    $result = Database::query($sql);
527
    $row = Database::fetch_row($result);
528
529
    return $row[0];
530
}
531
532
/**
533
 * Shows the work list (student view)
534
 * @return string
535
 */
536
function showStudentWorkGrid()
537
{
538
    $courseInfo = api_get_course_info();
539
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student&'.api_get_cidreq();
540
541
    $columns = array(
542
        get_lang('Type'),
543
        get_lang('Title'),
544
        get_lang('HandOutDateLimit'),
545
        get_lang('Feedback'),
546
        get_lang('LastUpload')
547
    );
548
549
    $columnModel = array(
550
        array('name'=>'type', 'index'=>'type', 'width'=>'30',   'align'=>'center', 'sortable' => 'false'),
551
        array('name'=>'title', 'index'=>'title', 'width'=>'250',   'align'=>'left'),
552
        array('name'=>'expires_on', 'index'=>'expires_on', 'width'=>'80',  'align'=>'center', 'sortable'=>'false'),
553
        array('name'=>'feedback', 'index'=>'feedback', 'width'=>'80',  'align'=>'center'),
554
        array('name'=>'last_upload', 'index'=>'feedback', 'width'=>'125',  'align'=>'center'),
555
    );
556
557 View Code Duplication
    if ($courseInfo['show_score'] == 0) {
558
        $columnModel[] = array(
559
            'name' => 'others',
560
            'index' => 'others',
561
            'width' => '80',
562
            'align' => 'left',
563
            'sortable' => 'false'
564
        );
565
        $columns[] = get_lang('Others');
566
    }
567
568
    $params = array(
569
        'autowidth' => 'true',
570
        'height' => 'auto'
571
    );
572
573
    $html = '<script>
574
    $(function() {
575
        '.Display::grid_js('workList', $url, $columns, $columnModel, $params, array(), null, true).'
576
    });
577
    </script>';
578
579
    $html .= Display::grid_html('workList');
580
    return $html;
581
}
582
583
/**
584
 * Shows the work list (teacher view)
585
 * @return string
586
 */
587
function showTeacherWorkGrid()
588
{
589
    $columnModel = array(
590
        array('name'=>'type', 'index'=>'type', 'width'=>'35', 'align'=>'center', 'sortable' => 'false'),
591
        array('name'=>'title', 'index'=>'title',  'width'=>'300',   'align'=>'left', 'wrap_cell' => "true"),
592
        array('name'=>'sent_date', 'index'=>'sent_date', 'width'=>'125',  'align'=>'center'),
593
        array('name'=>'expires_on', 'index'=>'expires_on', 'width'=>'125',  'align'=>'center'),
594
        array('name'=>'amount', 'index'=>'end_on', 'width'=>'110',  'align'=>'center'),
595
        array('name'=>'actions', 'index'=>'actions', 'width'=>'110', 'align'=>'left', 'sortable'=>'false')
596
    );
597
598
    $token = null;
599
600
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_teacher&'.api_get_cidreq();
601
    $deleteUrl = api_get_path(WEB_AJAX_PATH).'work.ajax.php?a=delete_work&'.api_get_cidreq();
602
603
    $columns = array(
604
        get_lang('Type'),
605
        get_lang('Title'),
606
        get_lang('SentDate'),
607
        get_lang('HandOutDateLimit'),
608
        get_lang('AmountSubmitted'),
609
        get_lang('Actions')
610
    );
611
612
    $params = array(
613
        'multiselect' => true,
614
        'autowidth' => 'true',
615
        'height' => 'auto'
616
    );
617
618
    $html = '<script>
619
    $(function() {
620
        '.Display::grid_js('workList', $url, $columns, $columnModel, $params, array(), null, true).'
621
        $("#workList").jqGrid(
622
            "navGrid",
623
            "#workList_pager",
624
            { edit: false, add: false, del: true },
625
            { height:280, reloadAfterSubmit:false }, // edit options
626
            { height:280, reloadAfterSubmit:false }, // add options
627
            { reloadAfterSubmit:false, url: "'.$deleteUrl.'" }, // del options
628
            { width:500 } // search options
629
        );
630
    });
631
    </script>';
632
    $html .= Display::grid_html('workList');
633
    return $html;
634
}
635
636
/**
637
 * Builds the form thats enables the user to
638
 * select a directory to browse/upload in
639
 * This function has been copied from the document/document.inc.php library
640
 *
641
 * @param array $folders
642
 * @param string $curdirpath
643
 * @param string $group_dir
644
 * @return string html form
645
 */
646
// TODO: This function is a candidate for removal, it is not used anywhere.
647
function build_work_directory_selector($folders, $curdirpath, $group_dir = '')
648
{
649
    $form = '<form name="selector" action="'.api_get_self().'?'.api_get_cidreq().'" method="POST">';
650
    $form .= get_lang('CurrentDirectory').' <select name="curdirpath" onchange="javascript: document.selector.submit();">';
651
    //group documents cannot be uploaded in the root
652
    if ($group_dir == '') {
653
        $form .= '<option value="/">/ ('.get_lang('Root').')</option>';
654
        if (is_array($folders)) {
655
            foreach ($folders as $folder) {
656
                $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
657
                $form .= '<option'.$selected.' value="'.$folder.'">'.$folder.'</option>'."\n";
658
            }
659
        }
660
    } else {
661
        foreach ($folders as $folder) {
662
            $selected = ($curdirpath == $folder) ? ' selected="selected"' : '';
663
            $display_folder = substr($folder, strlen($group_dir));
664
            $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
665
            $form .= '<option'.$selected.' value="'.$folder.'">'.$display_folder.'</option>'."\n";
666
        }
667
    }
668
669
    $form .= '</select>';
670
    $form .= '<noscript><input type="submit" name="change_path" value="'.get_lang('Ok').'" /></noscript>';
671
    $form .= '</form>';
672
673
    return $form;
674
}
675
676
/**
677
 * Builds the form thats enables the user to
678
 * move a document from one directory to another
679
 * This function has been copied from the document/document.inc.php library
680
 *
681
 * @param array $folders
682
 * @param string $curdirpath
683
 * @param string $move_file
684
 * @param string $group_dir
685
 * @return string html form
686
 */
687
function build_work_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
688
{
689
    $course_id = api_get_course_int_id();
690
    $move_file = intval($move_file);
691
    $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
692
    $sql = "SELECT title, url FROM $tbl_work
693
            WHERE c_id = $course_id AND id ='".$move_file."'";
694
    $result = Database::query($sql);
695
    $row = Database::fetch_array($result, 'ASSOC');
696
    $title = empty($row['title']) ? basename($row['url']) : $row['title'];
697
698
    $form = new FormValidator(
699
        'move_to_form',
700
        'post',
701
        api_get_self().'?'.api_get_cidreq().'&curdirpath='.Security::remove_XSS($curdirpath)
702
    );
703
704
    $form->addHeader(get_lang('MoveFile').' - '.Security::remove_XSS($title));
705
    $form->addHidden('item_id', $move_file);
706
    $form->addHidden('action', 'move_to');
707
708
    //group documents cannot be uploaded in the root
709
    if ($group_dir == '') {
710
        if ($curdirpath != '/') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
711
            //$form .= '<option value="0">/ ('.get_lang('Root').')</option>';
712
        }
713
        if (is_array($folders)) {
714
            foreach ($folders as $fid => $folder) {
715
                //you cannot move a file to:
716
                //1. current directory
717
                //2. inside the folder you want to move
718
                //3. inside a subfolder of the folder you want to move
719
                if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
720
                    //$form .= '<option value="'.$fid.'">'.$folder.'</option>';
721
                    $options[$fid] = $folder;
722
                }
723
            }
724
        }
725
    } else {
726
        if ($curdirpath != '/') {
727
            $form .= '<option value="0">/ ('.get_lang('Root').')</option>';
728
        }
729
        foreach ($folders as $fid => $folder) {
730
            if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
731
                //cannot copy dir into his own subdir
732
                $display_folder = substr($folder, strlen($group_dir));
733
                $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
734
                //$form .= '<option value="'.$fid.'">'.$display_folder.'</option>'."\n";
735
                $options[$fid] = $display_folder;
736
            }
737
        }
738
    }
739
740
    $form->addSelect('move_to_id', get_lang('Select'), $options);
741
    $form->addButtonSend(get_lang('MoveFile'), 'move_file_submit');
742
743
    return $form->returnForm();
744
}
745
746
/**
747
 * creates a new directory trying to find a directory name
748
 * that doesn't already exist
749
 * (we could use unique_name() here...)
750
 *
751
 * @author Hugues Peeters <[email protected]>
752
 * @author Bert Vanderkimpen
753
 * @author Yannick Warnier <[email protected]> Adaptation for work tool
754
 * @param   string $base_work_dir Base work dir (.../work)
755
 * @param   string $desiredDirName complete path of the desired name
0 ignored issues
show
Bug introduced by
There is no parameter named $desiredDirName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
756
 *
757
 * @return  string actual directory name if it succeeds, boolean false otherwise
758
 */
759
function create_unexisting_work_directory($base_work_dir, $desired_dir_name)
760
{
761
    $nb = '';
762
    $base_work_dir = (substr($base_work_dir, -1, 1) == '/' ? $base_work_dir : $base_work_dir.'/');
763
    while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
764
        $nb += 1;
765
    }
766
767
    if (@mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories())) {
768
        return $desired_dir_name.$nb;
769
    } else {
770
        return false;
771
    }
772
}
773
774
/**
775
 * Delete a work-tool directory
776
 * @param   int  $id work directory id to delete
777
 * @return  integer -1 on error
778
 */
779
function deleteDirWork($id)
780
{
781
    $locked = api_resource_is_locked_by_gradebook($id, LINK_STUDENTPUBLICATION);
782
783
    if ($locked == true) {
784
        Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
785
        return false;
786
    }
787
788
    $_course = api_get_course_info();
789
    $id = intval($id);
790
    $work_data = get_work_data_by_id($id);
791
792
    if (empty($work_data)) {
793
        return false;
794
    }
795
796
    $base_work_dir = api_get_path(SYS_COURSE_PATH) .$_course['path'].'/work';
797
    $work_data_url = $base_work_dir.$work_data['url'];
798
    $check = Security::check_abs_path($work_data_url.'/', $base_work_dir.'/');
799
800
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
801
    $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
802
    $t_agenda = Database::get_course_table(TABLE_AGENDA);
803
804
    $course_id = api_get_course_int_id();
805
806
    if (!empty($work_data['url'])) {
807
        if ($check) {
808
            // Deleting all contents inside the folder
809
            $sql = "UPDATE $table SET active = 2
810
                    WHERE c_id = $course_id AND filetype = 'folder' AND id = $id";
811
            Database::query($sql);
812
813
            $sql = "UPDATE $table SET active = 2
814
                    WHERE c_id = $course_id AND parent_id = $id";
815
            Database::query($sql);
816
817
            $new_dir = $work_data_url.'_DELETED_'.$id;
818
819 View Code Duplication
            if (api_get_setting('permanently_remove_deleted_files') == 'true') {
820
                my_delete($work_data_url);
821
            } else {
822
                if (file_exists($work_data_url)) {
823
                    rename($work_data_url, $new_dir);
824
                }
825
            }
826
827
            // Gets calendar_id from student_publication_assigment
828
            $sql = "SELECT add_to_calendar FROM $TSTDPUBASG
829
                    WHERE c_id = $course_id AND publication_id = $id";
830
            $res = Database::query($sql);
831
            $calendar_id = Database::fetch_row($res);
832
833
            // delete from agenda if it exists
834
            if (!empty($calendar_id[0])) {
835
                $sql = "DELETE FROM $t_agenda
836
                        WHERE c_id = $course_id AND id = '".$calendar_id[0]."'";
837
                Database::query($sql);
838
            }
839
            $sql = "DELETE FROM $TSTDPUBASG
840
                    WHERE c_id = $course_id AND publication_id = $id";
841
            Database::query($sql);
842
843
            $link_info = GradebookUtils::is_resource_in_course_gradebook(
844
                api_get_course_id(),
845
                3,
846
                $id,
847
                api_get_session_id()
848
            );
849
            $link_id = $link_info['id'];
850
            if ($link_info !== false) {
851
                GradebookUtils::remove_resource_from_course_gradebook($link_id);
852
            }
853
            return true;
854
        }
855
    }
856
}
857
858
/**
859
 * Get the path of a document in the student_publication table (path relative to the course directory)
860
 * @param   integer $id
861
 * @return  string  Path (or -1 on error)
862
 */
863
function get_work_path($id)
864
{
865
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
866
    $course_id  = api_get_course_int_id();
867
    $sql = 'SELECT url FROM '.$table.'
868
            WHERE c_id = '.$course_id.' AND id='.intval($id);
869
    $res = Database::query($sql);
870
    if (Database::num_rows($res)) {
871
        $row = Database::fetch_array($res);
872
        return $row['url'];
873
    }
874
    return -1;
875
}
876
877
/**
878
 * Update the url of a work in the student_publication table
879
 * @param integer $id of the work to update
880
 * @param string  $new_path Destination directory where the work has been moved (must end with a '/')
881
 * @param int $parent_id
882
 *
883
 * @return  -1 on error, sql query result on success
0 ignored issues
show
Documentation introduced by
The doc-type -1 could not be parsed: Unknown type name "-1" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
884
 */
885
function updateWorkUrl($id, $new_path, $parent_id)
886
{
887
    if (empty($id)) {
888
        return -1;
889
    }
890
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
891
    $course_id = api_get_course_int_id();
892
    $id = intval($id);
893
    $parent_id = intval($parent_id);
894
895
    $sql = "SELECT * FROM $table
896
            WHERE c_id = $course_id AND id = $id";
897
    $res = Database::query($sql);
898
    if (Database::num_rows($res) != 1) {
899
        return -1;
900
    } else {
901
        $row = Database::fetch_array($res);
902
        $filename = basename($row['url']);
903
        $new_url = $new_path.$filename;
904
        $new_url = Database::escape_string($new_url);
905
906
        $sql = "UPDATE $table SET
907
                   url = '$new_url',
908
                   parent_id = '$parent_id'
909
                WHERE c_id = $course_id AND id = $id";
910
        $res = Database::query($sql);
911
912
        return $res;
913
    }
914
}
915
916
/**
917
 * Update the url of a dir in the student_publication table
918
 * @param  array $work_data work original data
919
 * @param  string $newPath Example: "folder1"
920
 * @return bool
921
 */
922
function updateDirName($work_data, $newPath)
923
{
924
    $course_id = $work_data['c_id'];
925
    $sessionId = intval($work_data['session_id']);
926
    $work_id = intval($work_data['id']);
927
    $oldPath = $work_data['url'];
928
    $originalNewPath = Database::escape_string($newPath);
929
    $newPath = Database::escape_string($newPath);
930
    $newPath = api_replace_dangerous_char($newPath);
931
    $newPath = disable_dangerous_file($newPath);
932
933
    if ($oldPath == '/'.$newPath) {
934
        return true;
935
    }
936
937
    if (!empty($newPath)) {
938
        $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
939
        $sql = "UPDATE $table SET
940
                    title = '".$originalNewPath."'
941
                WHERE
942
                    c_id = $course_id AND
943
                    id = $work_id AND
944
                    session_id = $sessionId
945
                ";
946
        Database::query($sql);
947
    }
948
}
949
950
/**
951
 * Return an array with all the folder's ids that are in the given path
952
 * @param   string Path of the directory
953
 * @return  array The list of ids of all the directories in the path
954
 * @author  Julio Montoya Dokeos
955
 * @version April 2008
956
 */
957
958
function get_parent_directories($id)
959
{
960
    $course_id = api_get_course_int_id();
961
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
962
    $id = intval($id);
963
    $sql = "SELECT id FROM $work_table WHERE c_id = $course_id AND parent_id = $id";
964
    $result = Database::query($sql);
965
    $list_id = array();
966
    if (Database::num_rows($result)) {
967
        while ($row = Database::fetch_array($result)) {
968
            $list_id[] = $row['id'];
969
        }
970
    }
971
    return $list_id;
972
}
973
974
/**
975
 * Transform an all directory structure (only directories) in an array
976
 * @param   string path of the directory
977
 * @return  array the directory structure into an array
978
 * @author  Julio Montoya Dokeos
979
 * @version April 2008
980
 */
981 View Code Duplication
function directory_to_array($directory)
982
{
983
    $array_items = array();
984
    if ($handle = @opendir($directory)) {
985
        while (false !== ($file = readdir($handle))) {
986
            if ($file != '.' && $file != '..') {
987
                if (is_dir($directory. '/' . $file)) {
988
                    $array_items = array_merge($array_items, directory_to_array($directory. '/' . $file));
989
                    $file = $directory . '/' . $file;
990
                    $array_items[] = preg_replace("/\/\//si", '/', $file);
991
                }
992
            }
993
        }
994
        closedir($handle);
995
    }
996
    return $array_items;
997
}
998
999
/**
1000
 * Insert into the DB of the course all the directories
1001
 * @param   string path of the /work directory of the course
1002
 * @return  -1 on error, sql query result on success
1003
 * @author  Julio Montoya
0 ignored issues
show
Documentation introduced by
The doc-type -1 could not be parsed: Unknown type name "-1" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1004
 * @version April 2008
1005
 * @param string $base_work_dir
1006
 */
1007
1008
function insert_all_directory_in_course_table($base_work_dir)
1009
{
1010
    $dir_to_array = directory_to_array($base_work_dir, true);
1011
    $only_dir = array();
1012
1013
    for ($i = 0; $i < count($dir_to_array); $i++) {
1014
        $only_dir[] = substr($dir_to_array[$i], strlen($base_work_dir), strlen($dir_to_array[$i]));
1015
    }
1016
    $course_id = api_get_course_int_id();
1017
    $group_id  = api_get_group_id();
1018
1019
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
1020
1021
    for($i = 0; $i < count($only_dir); $i++) {
1022
        $url = $only_dir[$i];
1023
1024
        $params = [
1025
            'c_id' => $course_id,
1026
            'url' => $url,
1027
            'title' => '',
1028
            'description' => '',
1029
            'author' => '',
1030
            'active' => '1',
1031
            'accepted' => '1',
1032
            'filetype' => 'folder',
1033
            'post_group_id' => $group_id,
1034
        ];
1035
1036
        Database::insert($work_table, $params);
1037
    }
1038
}
1039
1040
/**
1041
 * This function displays the number of files contained in a directory
1042
 *
1043
 * @param   string the path of the directory
1044
 * @param   boolean true if we want the total quantity of files
1045
 * include in others child directories, false only  files in the directory
1046
 * @return  array the first element is an integer with the number of files
1047
 * in the folder, the second element is the number of directories
1048
 * @author  Julio Montoya
1049
 * @version April 2008
1050
 */
1051
function count_dir($path_dir, $recurse)
1052
{
1053
    $count = 0;
1054
    $count_dir = 0;
1055
    $d = dir($path_dir);
1056
    while ($entry = $d->Read()) {
1057
        if (!(($entry == '..') || ($entry == '.'))) {
1058
            if (is_dir($path_dir.'/'.$entry)) {
1059
                $count_dir++;
1060
                if ($recurse) {
1061
                    $count += count_dir($path_dir . '/' . $entry, $recurse);
1062
                }
1063
            } else {
1064
                $count++;
1065
            }
1066
        }
1067
    }
1068
    $return_array = array();
1069
    $return_array[] = $count;
1070
    $return_array[] = $count_dir;
1071
    return $return_array;
1072
}
1073
1074
/**
1075
 * returns all the javascript that is required for easily
1076
 * validation when you create a work
1077
 * this goes into the $htmlHeadXtra[] array
1078
 */
1079
function to_javascript_work()
1080
{
1081
    $js = '<script>
1082
        function updateDocumentTitle(value) {
1083
            var temp = value.indexOf("/");
1084
            //linux path
1085
            if(temp!=-1){
1086
                var temp=value.split("/");
1087
            } else {
1088
                var temp=value.split("\\\");
1089
            }
1090
            document.getElementById("file_upload").value=temp[temp.length-1];
1091
            $("#contains_file_id").attr("value", 1);
1092
        }
1093
1094
        function checkDate(month, day, year) {
1095
          var monthLength =
1096
            new Array(31,28,31,30,31,30,31,31,30,31,30,31);
1097
1098
          if (!day || !month || !year)
1099
            return false;
1100
1101
          // check for bisestile year
1102
          if (year/4 == parseInt(year/4))
1103
            monthLength[1] = 29;
1104
1105
          if (month < 1 || month > 12)
1106
            return false;
1107
1108
          if (day > monthLength[month-1])
1109
            return false;
1110
1111
          return true;
1112
        }
1113
1114
        function mktime() {
1115
1116
            var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
1117
            d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
1118
1119
            var dateManip = {
1120
                0: function(tt){ return d.setHours(tt); },
1121
                1: function(tt){ return d.setMinutes(tt); },
1122
                2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
1123
                3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
1124
                4: function(tt){ return d.setDate(tt+mb); },
1125
                5: function(tt){ return d.setYear(tt+ma); }
1126
            };
1127
1128
            for( i = 0; i < argc; i++ ){
1129
                no = parseInt(argv[i]*1);
1130
                if (isNaN(no)) {
1131
                    return false;
1132
                } else {
1133
                    // arg is number, lets manipulate date object
1134
                    if(!dateManip[i](no)){
1135
                        // failed
1136
                        return false;
1137
                    }
1138
                }
1139
            }
1140
            return Math.floor(d.getTime()/1000);
1141
        }
1142
1143
        function setFocus() {
1144
            $("#work_title").focus();
1145
        }
1146
1147
        $(document).ready(function() {
1148
            setFocus();
1149
1150
            var checked = $("#expiry_date").attr("checked");
1151
            if (checked) {
1152
                $("#option2").show();
1153
                $("#option3").show();
1154
                $("#end_date").attr("checked", true);
1155
            } else {
1156
                $("#option2").hide();
1157
                $("#option3").hide();
1158
                $("#end_date").attr("checked", false);
1159
            }
1160
1161
            $("#expiry_date").click(function() {
1162
                $("#option2").toggle();
1163
            });
1164
1165
            $("#end_date").click(function() {
1166
                $("#option3").toggle();
1167
            });
1168
        });
1169
    </script>';
1170
1171
    return $js;
1172
}
1173
1174
/**
1175
 * Gets the id of a student publication with a given path
1176
 * @param string $path
1177
 * @return true if is found / false if not found
1178
 */
1179
// TODO: The name of this function does not fit with the kind of information it returns. Maybe check_work_id() or is_work_id()?
1180
function get_work_id($path)
1181
{
1182
    $TBL_STUDENT_PUBLICATION = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1183
    $TBL_PROP_TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
1184
    $course_id = api_get_course_int_id();
1185
    $path = Database::escape_string($path);
1186
1187
    if (api_is_allowed_to_edit()) {
1188
        $sql = "SELECT work.id
1189
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1190
                WHERE
1191
                    props.c_id = $course_id AND
1192
                    work.c_id = $course_id AND
1193
                    props.tool='work' AND
1194
                    work.id=props.ref AND
1195
                    work.url LIKE 'work/".$path."%' AND
1196
                    work.filetype='file' AND
1197
                    props.visibility<>'2'";
1198
    } else {
1199
        $sql = "SELECT work.id
1200
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1201
                WHERE
1202
                    props.c_id = $course_id AND
1203
                    work.c_id = $course_id AND
1204
                    props.tool='work' AND
1205
                    work.id=props.ref AND
1206
                    work.url LIKE 'work/".$path."%' AND
1207
                    work.filetype='file' AND
1208
                    props.visibility<>'2' AND
1209
                    props.lastedit_user_id = '".api_get_user_id()."'";
1210
    }
1211
    $result = Database::query($sql);
1212
    $num_rows = Database::num_rows($result);
1213
1214
    if ($result && $num_rows > 0) {
1215
        return true;
1216
    } else {
1217
        return false;
1218
    }
1219
}
1220
1221
/**
1222
 * @param int $work_id
1223
 * @param int $onlyMeUserId show only my works
1224
 * @param int $notMeUserId show works from everyone except me
1225
 * @return int
1226
 */
1227
function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null)
1228
{
1229
    $work_table      = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1230
    $iprop_table     = Database::get_course_table(TABLE_ITEM_PROPERTY);
1231
    $user_table      = Database::get_main_table(TABLE_MAIN_USER);
1232
1233
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
1234
    $session_id = api_get_session_id();
1235
    $condition_session = api_get_session_condition($session_id, true, false, 'work.session_id');
1236
1237
    $group_id = api_get_group_id();
1238
    $course_info = api_get_course_info();
1239
    $course_id = $course_info['real_id'];
1240
    $work_id = intval($work_id);
1241
1242 View Code Duplication
    if (!empty($group_id)) {
1243
        // set to select only messages posted by the user's group
1244
        $extra_conditions = " work.post_group_id = '".intval($group_id)."' ";
1245
    } else {
1246
        $extra_conditions = " work.post_group_id = '0' ";
1247
    }
1248
1249 View Code Duplication
    if ($is_allowed_to_edit) {
1250
        $extra_conditions .= ' AND work.active IN (0, 1) ';
1251
    } else {
1252
        $extra_conditions .= ' AND work.active IN (0, 1) AND accepted = 1';
1253
        if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
1254
            $extra_conditions .= " AND work.user_id = ".api_get_user_id()." ";
1255
        } else {
1256
            $extra_conditions .= '';
1257
        }
1258
    }
1259
1260
    $extra_conditions .= " AND parent_id  = ".$work_id."  ";
1261
1262
    $where_condition = null;
1263
1264
    if (!empty($notMeUserId)) {
1265
        $where_condition .= " AND u.user_id <> ".intval($notMeUserId);
1266
    }
1267
1268
    if (!empty($onlyMeUserId)) {
1269
        $where_condition .= " AND u.user_id =  ".intval($onlyMeUserId);
1270
    }
1271
1272
    $sql = "SELECT count(*) as count
1273
            FROM $iprop_table prop
1274
            INNER JOIN $work_table work
1275
            ON (
1276
                prop.ref = work.id AND
1277
                prop.c_id = $course_id AND
1278
                prop.tool='work' AND
1279
                prop.visibility <> 2 AND
1280
                work.c_id = $course_id
1281
            )
1282
            INNER JOIN $user_table u ON (work.user_id = u.user_id)
1283
            WHERE $extra_conditions $where_condition $condition_session";
1284
1285
    $result = Database::query($sql);
1286
1287
    $users_with_work = 0;
1288
    if (Database::num_rows($result)) {
1289
        $result = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1290
        $users_with_work = $result['count'];
1291
    }
1292
    return $users_with_work;
1293
}
1294
1295
/**
1296
 * @param int $start
1297
 * @param int $limit
1298
 * @param string $column
1299
 * @param string $direction
1300
 * @param string $where_condition
1301
 * @param bool $getCount
1302
 * @return array
1303
 */
1304
function getWorkListStudent(
1305
    $start,
1306
    $limit,
1307
    $column,
1308
    $direction,
1309
    $where_condition,
1310
    $getCount = false
1311
) {
1312
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1313
    $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1314
    $courseInfo = api_get_course_info();
1315
    $course_id = $courseInfo['real_id'];
1316
    $session_id = api_get_session_id();
1317
    $condition_session = api_get_session_condition($session_id);
1318
    $group_id = api_get_group_id();
1319
    $userId = api_get_user_id();
1320
1321
    $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
1322
        api_get_user_id(),
1323
        $courseInfo
1324
    );
1325
1326
    if (!in_array($direction, array('asc','desc'))) {
1327
        $direction = 'desc';
1328
    }
1329
    if (!empty($where_condition)) {
1330
        $where_condition = ' AND ' . $where_condition;
1331
    }
1332
1333
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1334
    $start = intval($start);
1335
    $limit = intval($limit);
1336
1337
    // Get list from database
1338
1339 View Code Duplication
    if (!empty($group_id)) {
1340
        $group_query = " WHERE w.c_id = $course_id AND post_group_id = '".$group_id."' ";
1341
        $subdirs_query = "AND parent_id = 0";
1342
    } else {
1343
        $group_query = " WHERE w.c_id = $course_id AND post_group_id = '0' ";
1344
        $subdirs_query = "AND parent_id = 0";
1345
    }
1346
1347
    $active_condition = ' AND active IN (1, 0)';
1348
1349
    if ($getCount) {
1350
        $select = "SELECT count(w.id) as count ";
1351
    } else {
1352
        $select = "SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
1353
    }
1354
1355
    $sql = "$select
1356
            FROM $workTable w
1357
            LEFT JOIN $workTableAssignment a
1358
            ON (a.publication_id = w.id AND a.c_id = w.c_id)
1359
                $group_query
1360
                $subdirs_query
1361
                $active_condition
1362
                $condition_session
1363
                $where_condition
1364
            ";
1365
1366
    $sql .= " ORDER BY $column $direction ";
1367
1368
    if (!empty($start) && !empty($limit)) {
1369
        $sql .= " LIMIT $start, $limit";
1370
    }
1371
1372
    $result = Database::query($sql);
1373
1374
    if ($getCount) {
1375
        $row = Database::fetch_array($result);
1376
        return $row['count'];
1377
    }
1378
1379
    $works = array();
1380
1381
    $url = api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq();
1382
    if ($isDrhOfCourse) {
1383
        $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
1384
    }
1385
1386
    $urlOthers = api_get_path(WEB_CODE_PATH).'work/work_list_others.php?'.api_get_cidreq().'&id=';
1387
    while ($work = Database::fetch_array($result, 'ASSOC')) {
1388
        $isSubscribed = userIsSubscribedToWork($userId, $work['id'], $course_id);
1389
        if ($isSubscribed == false) {
1390
            continue;
1391
        }
1392
1393
        $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $session_id);
1394
1395
        if ($visibility != 1) {
1396
            continue;
1397
        }
1398
1399
        $work['type'] = Display::return_icon('work.png');
1400
        $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
1401
1402
        if (empty($work['title'])) {
1403
            $work['title'] = basename($work['url']);
1404
        }
1405
1406
        $whereCondition = " AND u.user_id = ".intval($userId);
1407
1408
        $workList = get_work_user_list(
1409
            0,
1410
            1000,
1411
            null,
1412
            null,
1413
            $work['id'],
1414
            $whereCondition
1415
        );
1416
1417
        $count = getTotalWorkComment($workList, $courseInfo);
1418
1419 View Code Duplication
        if (!is_null($count) && !empty($count)) {
1420
            $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info');
1421
        }
1422
1423
        $lastWork = getLastWorkStudentFromParentByUser($userId, $work['id'], $courseInfo);
1424
1425
        if (!empty($lastWork)) {
1426
            $work['last_upload'] = Display::label($lastWork['qualification'], 'warning').' - ';
1427
            $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
1428
        }
1429
1430
1431
        $work['title'] = Display::url($work['title'], $url.'&id='.$work['id']);
1432
        $work['others'] = Display::url(
1433
            Display::return_icon('group.png', get_lang('Others')),
1434
            $urlOthers.$work['id']
1435
        );
1436
        $works[] = $work;
1437
    }
1438
1439
    return $works;
1440
}
1441
1442
/**
1443
 * @param int $start
1444
 * @param int $limit
1445
 * @param string $column
1446
 * @param string $direction
1447
 * @param string $where_condition
1448
 * @param bool $getCount
1449
 * @return array
1450
 */
1451
function getWorkListTeacher(
1452
    $start,
1453
    $limit,
1454
    $column,
1455
    $direction,
1456
    $where_condition,
1457
    $getCount = false
1458
) {
1459
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1460
    $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1461
1462
    $courseInfo = api_get_course_info();
1463
    $course_id = api_get_course_int_id();
1464
    $session_id = api_get_session_id();
1465
    $condition_session = api_get_session_condition($session_id);
1466
    $group_id = api_get_group_id();
1467
    $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
1468
1469
    if (!in_array($direction, array('asc', 'desc'))) {
1470
        $direction = 'desc';
1471
    }
1472
    if (!empty($where_condition)) {
1473
        $where_condition = ' AND ' . $where_condition;
1474
    }
1475
1476
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1477
    $start = intval($start);
1478
    $limit = intval($limit);
1479
    $works = array();
1480
1481
    // Get list from database
1482
    if ($is_allowed_to_edit) {
1483
        $active_condition = ' active IN (0, 1)';
1484
        if ($getCount) {
1485
            $select = " SELECT count(w.id) as count";
1486
        } else {
1487
            $select = " SELECT w.*, a.expires_on, expires_on, ends_on, enable_qualification ";
1488
        }
1489
        $sql = " $select
1490
                FROM $workTable w
1491
                LEFT JOIN $workTableAssignment a
1492
                ON (a.publication_id = w.id AND a.c_id = w.c_id)
1493
                WHERE
1494
                    w.c_id = $course_id
1495
                    $condition_session AND
1496
                    $active_condition AND
1497
                    (parent_id = 0) AND
1498
                    post_group_id = '".$group_id."'
1499
                    $where_condition
1500
                ORDER BY $column $direction
1501
                LIMIT $start, $limit";
1502
        $result = Database::query($sql);
1503
1504
        if ($getCount) {
1505
            $row = Database::fetch_array($result);
1506
1507
            return $row['count'];
1508
        }
1509
        $url = api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq();
1510
        while ($work = Database::fetch_array($result, 'ASSOC')) {
1511
            $workId = $work['id'];
1512
            $work['type'] = Display::return_icon('work.png');
1513
            $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']);
1514
1515
            $totalUsers = getStudentSubscribedToWork(
1516
                $workId,
1517
                $course_id,
1518
                $group_id,
1519
                $session_id,
1520
                true
1521
            );
1522
1523
            $countUniqueAttempts = getUniqueStudentAttemptsTotal(
1524
                $workId,
1525
                $group_id,
1526
                $course_id,
1527
                $session_id
1528
            );
1529
1530
            $work['amount'] = Display::label(
1531
                $countUniqueAttempts . '/' .
1532
                $totalUsers,
1533
                'success'
1534
            );
1535
1536
            $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $session_id);
1537
1538
            if ($visibility == 1) {
1539
                $icon = 'visible.png';
1540
                $text = get_lang('Visible');
1541
                $action = 'invisible';
1542
                $class = '';
1543
            } else {
1544
                $icon = 'invisible.png';
1545
                $text = get_lang('Invisible');
1546
                $action = 'visible';
1547
                $class = 'muted';
1548
            }
1549
1550
            $visibilityLink = Display::url(
1551
                Display::return_icon($icon, $text, array(), ICON_SIZE_SMALL),
1552
                api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action='.$action.'&'.api_get_cidreq()
1553
            );
1554
1555
            if (empty($work['title'])) {
1556
                $work['title'] = basename($work['url']);
1557
            }
1558
            $work['title'] = Display::url($work['title'], $url.'&id='.$workId, ['class' => $class]);
1559
            $work['title'] .= ' '.Display::label(get_count_work($work['id']), 'success');
1560
            $work['sent_date'] = api_get_local_time($work['sent_date']);
1561
1562
            $editLink = Display::url(
1563
                Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL),
1564
                api_get_path(WEB_CODE_PATH).'work/edit_work.php?id='.$workId.'&'.api_get_cidreq()
1565
            );
1566
1567
            $correctionLink = Display::url(
1568
                Display::return_icon('upload_file.png', get_lang('UploadCorrections'), '', ICON_SIZE_SMALL),
1569
                api_get_path(WEB_CODE_PATH).'work/upload_corrections.php?'.api_get_cidreq().'&id='.$workId
1570
            );
1571
1572
            if ($countUniqueAttempts > 0) {
1573
                $downloadLink = Display::url(
1574
                    Display::return_icon(
1575
                        'save_pack.png',
1576
                        get_lang('Save'),
1577
                        array(),
1578
                        ICON_SIZE_SMALL
1579
                    ),
1580
                    api_get_path(WEB_CODE_PATH) . 'work/downloadfolder.inc.php?id=' . $workId . '&' . api_get_cidreq()
1581
                );
1582
            } else {
1583
                $downloadLink = Display::url(
1584
                    Display::return_icon(
1585
                        'save_pack_na.png',
1586
                        get_lang('Save'),
1587
                        array(),
1588
                        ICON_SIZE_SMALL
1589
                    ),
1590
                    '#'
1591
                );
1592
            }
1593
            // Remove Delete Work Button from action List
1594
            // Because removeXSS "removes" the onClick JS Event to do the action (See model.ajax.php - Line 1639)
1595
            // But still can use the another jqgrid button to remove works (trash icon)
1596
            //
1597
            // $deleteUrl = api_get_path(WEB_CODE_PATH).'work/work.php?id='.$workId.'&action=delete_dir&'.api_get_cidreq();
1598
            // $deleteLink = '<a href="#" onclick="showConfirmationPopup(this, \'' . $deleteUrl . '\' ) " >' .
1599
            //     Display::return_icon(
1600
            //         'delete.png',
1601
            //         get_lang('Delete'),
1602
            //         array(),
1603
            //         ICON_SIZE_SMALL
1604
            //     ) . '</a>';
1605
1606
            if (!api_is_allowed_to_edit()) {
1607
                // $deleteLink = null;
1608
                $editLink = null;
1609
            }
1610
            $work['actions'] = $visibilityLink.$correctionLink.$downloadLink.$editLink;
1611
            $works[] = $work;
1612
        }
1613
    }
1614
1615
    return $works;
1616
}
1617
1618
/**
1619
 * @param int $start
1620
 * @param int $limit
1621
 * @param string $column
1622
 * @param string $direction
1623
 * @param int $workId
1624
 * @param int $studentId
1625
 * @param string $whereCondition
1626
 * @param bool $getCount
1627
 * @return array
1628
 */
1629
function get_work_user_list_from_documents(
1630
    $start,
1631
    $limit,
1632
    $column,
1633
    $direction,
1634
    $workId,
1635
    $studentId = null,
1636
    $whereCondition,
1637
    $getCount = false
1638
) {
1639
    if ($getCount) {
1640
        $select1 = " SELECT count(u.user_id) as count ";
1641
        $select2 = " SELECT count(u.user_id) as count ";
1642
    } else {
1643
        $select1 = " SELECT DISTINCT u.firstname, u.lastname, u.user_id, w.title, w.parent_id, w.document_id document_id, w.id, qualification, qualificator_id";
1644
        $select2 = " SELECT DISTINCT u.firstname, u.lastname, u.user_id, d.title, w.parent_id, d.id document_id, 0, 0, 0";
1645
    }
1646
1647
    $documentTable = Database::get_course_table(TABLE_DOCUMENT);
1648
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1649
    $workRelDocument = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
1650
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
1651
1652
    $courseId = api_get_course_int_id();
1653
    $sessionId = api_get_session_id();
1654
1655
    if (empty($studentId)) {
1656
        $studentId = api_get_user_id();
1657
    }
1658
    $studentId = intval($studentId);
1659
    $workId = intval($workId);
1660
1661
    $userCondition = " AND u.user_id = $studentId ";
1662
    $sessionCondition = " AND w.session_id = $sessionId ";
1663
    $workCondition = " AND w_rel.work_id = $workId";
1664
    $workParentCondition  = " AND w.parent_id = $workId";
1665
1666
    $sql = "(
1667
                $select1 FROM $userTable u
1668
                INNER JOIN $workTable w
1669
                ON (u.user_id = w.user_id AND w.active IN (0, 1) AND w.filetype = 'file')
1670
                WHERE
1671
                    w.c_id = $courseId
1672
                    $userCondition
1673
                    $sessionCondition
1674
                    $whereCondition
1675
                    $workParentCondition
1676
            ) UNION (
1677
                $select2 FROM $workTable w
1678
                INNER JOIN $workRelDocument w_rel
1679
                ON (w_rel.work_id = w.id AND w.active IN (0, 1) AND w_rel.c_id = w.c_id)
1680
                INNER JOIN $documentTable d
1681
                ON (w_rel.document_id = d.id AND d.c_id = w.c_id)
1682
                INNER JOIN $userTable u ON (u.user_id = $studentId)
1683
                WHERE
1684
                    w.c_id = $courseId
1685
                    $workCondition
1686
                    $sessionCondition AND
1687
                    d.id NOT IN (
1688
                        SELECT w.document_id id
1689
                        FROM $workTable w
1690
                        WHERE
1691
                            user_id = $studentId AND
1692
                            c_id = $courseId AND
1693
                            filetype = 'file' AND
1694
                            active IN (0, 1)
1695
                            $sessionCondition
1696
                            $workParentCondition
1697
                    )
1698
            )";
1699
1700
    $start = intval($start);
1701
    $limit = intval($limit);
1702
1703
    $direction = in_array(strtolower($direction), array('desc', 'asc')) ? $direction : 'desc';
1704
    $column = Database::escape_string($column);
1705
1706
    if ($getCount) {
1707
        $result = Database::query($sql);
1708
        $result = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1709
        return $result['count'];
1710
    }
1711
1712
    $sql .= " ORDER BY $column $direction";
1713
    $sql .= " LIMIT $start, $limit";
1714
1715
    $result = Database::query($sql);
1716
1717
    $currentUserId = api_get_user_id();
1718
    $work_data = get_work_data_by_id($workId);
1719
1720
    $qualificationExists = false;
1721
1722 View Code Duplication
    if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0) {
1723
        $qualificationExists = true;
1724
    }
1725
1726
    $urlAdd = api_get_path(WEB_CODE_PATH).'work/upload_from_template.php?'.api_get_cidreq();
1727
    $urlEdit = api_get_path(WEB_CODE_PATH).'work/edit.php?'.api_get_cidreq();
1728
    $urlDelete = api_get_path(WEB_CODE_PATH).'work/work_list.php?action=delete&'.api_get_cidreq();
1729
    $urlView = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq();
1730
1731
    $editIcon = Display::return_icon('edit.png', get_lang('Edit'));
1732
    $addIcon = Display::return_icon('add.png', get_lang('Add'));
1733
    $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'));
1734
    $viewIcon = Display::return_icon('default.png', get_lang('View'));
1735
    $allowEdition = api_get_course_setting('student_delete_own_publication');
1736
1737
    $workList = array();
1738
    while ($row = Database::fetch_array($result, 'ASSOC')) {
1739
        $userId = $row['user_id'];
1740
        $documentId = $row['document_id'];
1741
        $itemId = $row['id'];
1742
        $addLinkShowed = false;
1743
1744
        if (empty($documentId)) {
1745
            $url = $urlEdit.'&item_id='.$row['id'].'&id='.$workId;
1746
            $editLink = Display::url($editIcon, $url);
1747
            if ($allowEdition == false) {
1748
                $editLink = null;
1749
            }
1750
        } else {
1751
            $documentToWork = getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId);
1752
1753
            if (empty($documentToWork)) {
1754
                $url = $urlAdd.'&document_id='.$documentId.'&id='.$workId;
1755
                $editLink = Display::url($addIcon, $url);
1756
                $addLinkShowed = true;
1757
            } else {
1758
1759
                $row['title'] = $documentToWork['title'];
1760
                $row['sent_date'] = $documentToWork['sent_date'];
1761
                $newWorkId = $documentToWork['id'];
1762
                $url = $urlEdit.'&item_id='.$newWorkId.'&id='.$workId;
1763
                $editLink = Display::url($editIcon, $url);
1764
1765
                if ($allowEdition == false) {
1766
                    $editLink = null;
1767
                }
1768
            }
1769
        }
1770
1771
        if ($allowEdition && !empty($itemId)) {
1772
            $deleteLink  = Display::url($deleteIcon, $urlDelete.'&item_id='.$itemId.'&id='.$workId);
1773
        } else {
1774
            $deleteLink = null;
1775
        }
1776
1777
        $viewLink = null;
1778
1779
        if (!empty($itemId)) {
1780
            $viewLink = Display::url($viewIcon, $urlView.'&id='.$itemId);
1781
        }
1782
1783
        //$row['type'] = build_document_icon_tag('file', $row['url']);
1784
        $row['type'] = null;
1785
1786
        if ($qualificationExists) {
1787 View Code Duplication
            if (empty($row['qualificator_id'])) {
1788
                $status = Display::label(get_lang('NotRevised'), 'warning');
1789
            } else {
1790
                $status = Display::label(get_lang('Revised'), 'success');
1791
            }
1792
            $row['qualificator_id'] = $status;
1793
        }
1794
1795
        if (!empty($row['qualification'])) {
1796
            $row['qualification'] = Display::label($row['qualification'], 'info');
1797
        }
1798
1799
        if (!empty($row['sent_date'])) {
1800
            $row['sent_date'] = api_get_local_time($row['sent_date']);
1801
        }
1802
1803
        if ($userId == $currentUserId) {
1804
            $row['actions'] = $viewLink.$editLink.$deleteLink;
1805
        }
1806
1807
        if ($addLinkShowed) {
1808
            $row['qualification'] = '';
1809
            $row['qualificator_id'] = '';
1810
        }
1811
1812
        $workList[] = $row;
1813
    }
1814
1815
    return $workList;
1816
}
1817
1818
/**
1819
 * @param int $start
1820
 * @param int $limit
1821
 * @param int $column
1822
 * @param string $direction
1823
 * @param int $work_id
1824
 * @param array $where_condition
1825
 * @param int $studentId
1826
 * @param bool $getCount
1827
 * @return array
1828
 */
1829
function get_work_user_list(
1830
    $start,
1831
    $limit,
1832
    $column,
1833
    $direction,
1834
    $work_id,
1835
    $where_condition = null,
1836
    $studentId = null,
1837
    $getCount = false
1838
) {
1839
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1840
    $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1841
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
1842
1843
    $session_id = api_get_session_id();
1844
    $group_id = api_get_group_id();
1845
    $course_info = api_get_course_info();
1846
    $course_id = $course_info['real_id'];
1847
1848
    $work_id = intval($work_id);
1849
    $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
1850
    $start = intval($start);
1851
    $limit = intval($limit);
1852
1853
    /*Call Compilatio's API*/
1854
    require_once(api_get_path(SYS_CODE_PATH) . 'plagiarism/compilatio/config.php');
1855
    require_once(api_get_path(SYS_CODE_PATH) . 'plagiarism/compilatio/compilatio.class.php');
1856
1857
    $compilatio_web_folder = api_get_path(WEB_CODE_PATH).'plagiarism/compilatio/';
1858
    $compilatio = new compilatio(
1859
        $compilatioParameter['key'],
0 ignored issues
show
Bug introduced by
The variable $compilatioParameter does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1860
        $compilatioParameter['$urlsoap'],
1861
        $compilatioParameter['proxy_host'],
1862
        $compilatioParameter['proxy_port']
1863
    );
1864
1865
1866
    if (!in_array($direction, array('asc','desc'))) {
1867
        $direction = 'desc';
1868
    }
1869
1870
    $work_data = get_work_data_by_id($work_id);
1871
    $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach();
1872
    $condition_session  = api_get_session_condition($session_id, true, false, 'work.session_id');
1873
    $locked = api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION);
1874
1875
    $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
1876
        api_get_user_id(),
1877
        $course_info
1878
    );
1879
1880
    if (!empty($work_data)) {
1881 View Code Duplication
        if (!empty($group_id)) {
1882
            $extra_conditions = " work.post_group_id = '".intval($group_id)."' ";
1883
            // set to select only messages posted by the user's group
1884
        } else {
1885
            $extra_conditions = " work.post_group_id = '0' ";
1886
        }
1887
1888 View Code Duplication
        if ($is_allowed_to_edit || $isDrhOfCourse) {
1889
            $extra_conditions .= ' AND work.active IN (0, 1) ';
1890
        } else {
1891
            if (isset($course_info['show_score']) &&
1892
                $course_info['show_score'] == 1
1893
            ) {
1894
                $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1)) ";
1895
            } else {
1896
                $extra_conditions .= ' AND work.active IN (0, 1) ';
1897
            }
1898
        }
1899
1900
        $extra_conditions .= " AND parent_id  = ".$work_id." ";
1901
1902
        $select = 'SELECT DISTINCT
1903
                        u.user_id,
1904
                        work.id as id,
1905
                        title as title,
1906
                        description,
1907
                        url,
1908
                        sent_date,
1909
                        contains_file,
1910
                        has_properties,
1911
                        view_properties,
1912
                        qualification,
1913
                        weight,
1914
                        allow_text_assignment,
1915
                        u.firstname,
1916
                        u.lastname,
1917
                        u.username,
1918
                        parent_id,
1919
                        accepted,
1920
                        qualificator_id,
1921
                        url_correction
1922
                        ';
1923
        if ($getCount) {
1924
            $select = "SELECT DISTINCT count(u.user_id) as count ";
1925
        }
1926
1927
        $user_condition = "INNER JOIN $user_table u  ON (work.user_id = u.user_id) ";
1928
        $work_condition = "$iprop_table prop INNER JOIN $work_table work
1929
                           ON (prop.ref = work.id AND prop.c_id = $course_id AND work.c_id = $course_id ) ";
1930
1931
        $work_assignment = get_work_assignment_by_id($work_id);
1932
1933
        if (!empty($studentId)) {
1934
            $where_condition.= " AND u.user_id = ".intval($studentId);
1935
        }
1936
1937
        $sql = " $select
1938
                FROM $work_condition  $user_condition
1939
                WHERE $extra_conditions $where_condition $condition_session
1940
                    AND u.status != " . INVITEE . "
1941
                ORDER BY $column $direction";
1942
1943
        if (!empty($start) && !empty($limit)) {
1944
            $sql .= " LIMIT $start, $limit";
1945
        }
1946
        $result = Database::query($sql);
1947
        $works = array();
1948
1949
        if ($getCount) {
1950
            $work = Database::fetch_array($result, 'ASSOC');
1951
            return $work['count'];
1952
        }
1953
1954
        $url = api_get_path(WEB_CODE_PATH).'work/';
1955
1956
        $unoconv = api_get_configuration_value('unoconv.binaries');
1957
1958
        while ($work = Database::fetch_array($result, 'ASSOC')) {
1959
            $item_id = $work['id'];
1960
            $dbTitle = $work['title']; 
1961
1962
            // Get the author ID for that document from the item_property table
1963
            $is_author  = false;
1964
            $can_read   = false;
1965
1966
            $owner_id = $work['user_id'];
1967
1968
            /* Because a bug found when saving items using the api_item_property_update()
1969
               the field $item_property_data['insert_user_id'] is not reliable. */
1970
1971
            if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) {
1972
                $is_author = true;
1973
            }
1974
1975
            if ($course_info['show_score'] == 0) {
1976
                $can_read = true;
1977
            }
1978
1979
            if ($work['accepted'] == '0') {
1980
                $class = 'invisible';
1981
            } else {
1982
                $class = '';
1983
            }
1984
1985
            $qualification_exists = false;
1986 View Code Duplication
            if (!empty($work_data['qualification']) &&
1987
                intval($work_data['qualification']) > 0
1988
            ) {
1989
                $qualification_exists = true;
1990
            }
1991
1992
            $qualification_string = '';
1993
            if ($qualification_exists) {
1994
                if ($work['qualification'] == '') {
1995
                    $qualification_string = Display::label('-');
1996
                } else {
1997
                    $label = 'info';
1998
                    $relativeScore = $work['qualification']/$work_data['qualification'];
1999
                    if ($relativeScore < 0.5) {
2000
                        $label = 'important';
2001
                    } elseif ($relativeScore < 0.75) {
2002
                        $label = 'warning';
2003
                    }
2004
                    $qualification_string = Display::label(
2005
                        $work['qualification'].' / '.$work_data['qualification'],
2006
                        $label
2007
                    );
2008
                }
2009
            }
2010
2011
            $work['qualification_score'] = $work['qualification'];
2012
2013
            $add_string = '';
2014
2015
            $time_expires = '';
2016
            if (!empty($work_assignment['expires_on'])) {
2017
                $time_expires = api_strtotime(
2018
                    $work_assignment['expires_on'],
2019
                    'UTC'
2020
                );
2021
            }
2022
2023
            if (!empty($work_assignment['expires_on']) &&
2024
                !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) {
2025
                $add_string = Display::label(get_lang('Expired'), 'important');
2026
            }
2027
2028
            if (($can_read && $work['accepted'] == '1') ||
2029
                ($is_author && in_array($work['accepted'], array('1', '0'))) ||
2030
                ($is_allowed_to_edit || api_is_drh())
2031
            ) {
2032
                // Firstname, lastname, username
2033
                $work['firstname'] = Display::div($work['firstname'], array('class' => $class));
2034
                $work['lastname'] = Display::div($work['lastname'], array('class' => $class));
2035
2036
                $work['title_clean'] = $work['title'];
2037
2038
                if (strlen($work['title']) > 30) {
2039
                    $short_title = substr($work['title'], 0, 27).'...';
2040
                    $work['title'] = Display::span($short_title, array('class' => $class, 'title' => $work['title']));
2041
                } else {
2042
                    $work['title'] = Display::div($work['title'], array('class' => $class));
2043
                }
2044
2045
                // Type.
2046
                $work['type'] = DocumentManager::build_document_icon_tag('file', $work['url']);
2047
2048
                // File name.
2049
                $link_to_download = null;
2050
2051
                // If URL is present then there's a file to download keep BC.
2052 View Code Duplication
                if ($work['contains_file'] || !empty($work['url'])) {
2053
                    $link_to_download = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'.
2054
                        Display::return_icon('save.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> ';
2055
                }
2056
2057
                $send_to = Portfolio::share('work', $work['id'],  array('style' => 'white-space:nowrap;'));
2058
2059
                $feedback = null;
2060
                $count = getWorkCommentCount($item_id, $course_info);
2061
                if (!is_null($count) && !empty($count)) {
2062
                    if ($qualification_exists) {
2063
                        $feedback .= "<br />";
2064
                    }
2065
                    $feedback .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2066
                        Display::label($count.' '.get_lang('Feedback'), 'info').'</a> ';
2067
                }
2068
2069
                $work['qualification'] = $qualification_string.$feedback;
2070
                $work['qualification_only'] = $qualification_string;
2071
2072
                // Date.
2073
                $work_date = api_convert_and_format_date($work['sent_date']);
2074
2075
                $work['sent_date_from_db'] = $work['sent_date'];
2076
                $work['sent_date'] = '<div class="date-time">' . date_to_str_ago(api_get_local_time($work['sent_date'])) . ' ' . $add_string . ' ' . $work_date . '</div>';
2077
2078
                // Actions.
2079
                $correction = '';
2080
2081
                $action = '';
2082
                if (api_is_allowed_to_edit()) {
2083
                    if (!empty($work['url_correction'])) {
2084
                        $action .= Display::url(
2085
                            Display::return_icon('check-circle.png', get_lang('Correction'), null, ICON_SIZE_SMALL),
2086
                            api_get_path(WEB_CODE_PATH).'work/download.php?id='.$item_id.'&'.api_get_cidreq().'&correction=1'
2087
                        );
2088
                    }
2089
2090
                    $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2091
                        Display::return_icon('default.png', get_lang('View'), array(), ICON_SIZE_SMALL).'</a> ';
2092
2093
                    if ($unoconv && empty($work['contains_file'])) {
2094
                        $action .=  '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=export_to_doc&item_id='.$item_id.'" title="'.get_lang('ExportToDoc').'" >'.
2095
                            Display::return_icon('export_doc.png', get_lang('ExportToDoc'),array(), ICON_SIZE_SMALL).'</a> ';
2096
                    }
2097
2098
                    $correction = '
2099
                        <form
2100
                            id="file_upload_'.$item_id.'"
2101
                            class="work_correction_file_upload file_upload_small"
2102
                            action="'.api_get_path(WEB_AJAX_PATH).'work.ajax.php?'.api_get_cidreq().'&a=upload_correction_file&item_id='.$item_id.'" 
2103
                            method="POST" 
2104
                            enctype="multipart/form-data"
2105
                            style="overflow:hidden"
2106
                        >
2107
                            <div class="fileUpload btn btn-default" >
2108
                                <span>'.get_lang('Send').'</span>
2109
                                <input type="file" name="file" class="upload"/>
2110
                            </div>
2111
                            <button type="submit"></button>
2112
                        </form>
2113
                    ';
2114
2115
                    $correction .= "
2116
                        <script>
2117
                            $(document).ready(function() {
2118
                                // remove title for this td
2119
                                $('#file_upload_".$item_id."').parent().attr('title', '');
2120
2121
                                // upload behaviour
2122
                                $('#file_upload_".$item_id."').fileupload({
2123
                                    uploadTable: $('.files'),
2124
                                    downloadTable: $('.files'),
2125
                                    done: function (e, data) {
2126
                                        // display a message and the sent button
2127
                                        // $(this).parent().parent().children().last().children().first().append('-');
2128
                                        $(this).children().first().children().first().append('".
2129
                                            preg_replace('/"/',
2130
                                                '\"',
2131
                                                Display::return_icon(
2132
                                                    'check-circle.png',
2133
                                                    get_lang('Correction'),
2134
                                                    ['style' => 'position:absolute;top:-5px;right:-5px;opacity:0.8;'],
2135
                                                    ICON_SIZE_SMALL
2136
                                                )
2137
                                            )
2138
                                        ."');                                    
2139
                                    }
2140
                                });
2141
                            });
2142
                        </script>
2143
                    ";
2144
2145
                    if ($locked) {
2146
                        if ($qualification_exists) {
2147
                            $action .= Display::return_icon('rate_work_na.png', get_lang('CorrectAndRate'),array(), ICON_SIZE_SMALL);
2148
                        } else {
2149
                            $action .= Display::return_icon('edit_na.png', get_lang('Comment'),array(), ICON_SIZE_SMALL);
2150
                        }
2151 View Code Duplication
                    } else {
2152
                        if ($qualification_exists) {
2153
                            $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Edit').'"  >'.
2154
                                Display::return_icon('rate_work.png', get_lang('CorrectAndRate'), array(), ICON_SIZE_SMALL).'</a>';
2155
                        } else {
2156
                            $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
2157
                                Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
2158
                        }
2159
                    }
2160
2161 View Code Duplication
                    if ($work['contains_file']) {
2162
                        if ($locked) {
2163
                            $action .= Display::return_icon('move_na.png', get_lang('Move'),array(), ICON_SIZE_SMALL);
2164
                        } else {
2165
                            $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Move').'">'.
2166
                                Display::return_icon('move.png', get_lang('Move'),array(), ICON_SIZE_SMALL).'</a>';
2167
                        }
2168
                    }
2169
2170 View Code Duplication
                    if ($work['accepted'] == '1') {
2171
                        $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').'" >'.
2172
                            Display::return_icon('visible.png', get_lang('Invisible'),array(), ICON_SIZE_SMALL).'</a>';
2173
                    } else {
2174
                        $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').'" >'.
2175
                            Display::return_icon('invisible.png', get_lang('Visible'),array(), ICON_SIZE_SMALL).'</a> ';
2176
                    }
2177
2178
                    if ($locked) {
2179
                        $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2180
                    } else {
2181
                        $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=delete&item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'.
2182
                            Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
2183
                    }
2184
                } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
2185
                    $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2186
                        Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
2187
2188
                    if (api_get_course_setting('student_delete_own_publication') == 1) {
2189 View Code Duplication
                        if (api_is_allowed_to_session_edit(false, true)) {
2190
                            $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'.
2191
                                Display::return_icon('edit.png', get_lang('Comment'),array(), ICON_SIZE_SMALL).'</a>';
2192
                        }
2193
                        $action .= ' <a href="'.$url.'work_list.php?'.api_get_cidreq().'&action=delete&item_id='.$item_id.'&id='.$work['parent_id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'"  >'.
2194
                            Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
2195
                    } else {
2196
                        $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
2197
                    }
2198
                } else {
2199
                    $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'.
2200
                        Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
2201
                    $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
2202
                }
2203
2204
                // Status.
2205 View Code Duplication
                if (empty($work['qualificator_id'])) {
2206
                    $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
2207
                } else {
2208
                    $qualificator_id = Display::label(get_lang('Revised'), 'success');
2209
                }
2210
                $work['qualificator_id'] = $qualificator_id;
2211
                $work['actions'] = $send_to.$link_to_download.$action;
2212
                $work['correction'] = $correction;
2213
                // colonne Compilatio
2214
                $compTable = Database::get_course_table("plagiarism_compilatio_docs");
2215
                $compilatioQuery = "SELECT compilatio_id FROM " 
2216
                    . $compTable 
2217
                    . " WHERE id_doc=" 
2218
                    . $item_id 
2219
                    . " AND c_id=" 
2220
                    . $course_id;
2221
                $compiSqlResult = Database::query($compilatioQuery);
2222
                $compi = Database::fetch_object($compiSqlResult);
2223
                $workDirectory = api_get_path(SYS_COURSE_PATH) . $course_info['directory'];
2224
                if (isset($compi->compilatio_id)) {
2225
                    $actionCompilatio = "<div id='id_avancement"
2226
                        . $item_id
2227
                        . "'><img src='"
2228
                        . $compilatio_web_folder
2229
                        . "/img/ajax-loader2.gif' style='margin-right:10px'/>"
2230
                        . get_lang('compilatioConnectionWithServer')
2231
                        . "</div>";
2232
                } else {
2233
                    if (!verifiFileType($dbTitle)) {
2234
                        $status = "BAD_FILETYPE";
2235
                        $actionCompilatio = "<div style='font-style:italic'>"
2236
                            . get_lang('compilatioFileisnotsupported')
2237
                            ."</div>";
2238
                    } elseif (filesize($workDirectory . "/" . $work['url']) > $compilatioParameter['max_filesize']) {
2239
                        $sizeFile = round(filesize($workDirectory . "/" . $work['url']) / 1000000);
2240
                        $status = "BAD_FILESIZE";
2241
                        $actionCompilatio = "<div style='font-style:italic'>"
2242
                            .get_lang('compilatioTooHeavyDocument')
2243
                            . ": "
2244
                            . $sizeFile
2245
                            . " Mo.<br/></div>";
2246
                    } else {
2247
                        $actionCompilatio = "<div id='id_avancement"
2248
                            . $item_id
2249
                            . "'>"
2250
                            . "<a href='javascript:void(0)' onClick='getSingleCompilatio("
2251
                            . $item_id
2252
                            .");'>"
2253
                            . get_lang('compilatioAnalyse')
2254
                            . " </a>"
2255
                            . get_lang('compilatioWithCompilatio')
2256
                            . "</div>";
2257
                    }
2258
                }
2259
                $work['compilatio'] = $actionCompilatio;
2260
                $works[] = $work;
2261
            }
2262
        }
2263
2264
        return $works;
2265
    }
2266
}
2267
2268
/**
2269
 * Send reminder to users who have not given the task
2270
 *
2271
 * @param int
2272
 * @return array
2273
 * @author cvargas [email protected] cfasanando, [email protected]
2274
 */
2275
function send_reminder_users_without_publication($task_data)
2276
{
2277
    $_course = api_get_course_info();
2278
    $task_id = $task_data['id'];
2279
    $task_title = !empty($task_data['title']) ? $task_data['title'] : basename($task_data['url']);
2280
    $subject = '[' . api_get_setting('siteName') . '] ';
2281
2282
    // The body can be as long as you wish, and any combination of text and variables
2283
    $content = get_lang('ReminderToSubmitPendingTask')."\n".get_lang('CourseName').' : '.$_course['name']."\n";
2284
    $content .= get_lang('WorkName').' : '.$task_title."\n";
2285
2286
    $list_users = get_list_users_without_publication($task_id);
2287
2288
    $mails_sent_to = array();
2289
    foreach ($list_users as $user) {
2290
        $name_user = api_get_person_name($user[1], $user[0], null, PERSON_NAME_EMAIL_ADDRESS);
2291
        $dear_line = get_lang('Dear')." ".api_get_person_name($user[1], $user[0]) .", \n\n";
2292
        $body      = $dear_line.$content;
2293
        MessageManager::send_message($user[3], $subject, $body);
2294
        $mails_sent_to[] = $name_user;
2295
    }
2296
    return $mails_sent_to;
2297
}
2298
2299
/**
2300
 * Sends an email to the students of a course when a homework is created
2301
 *
2302
 * @param int $courseId course_id
2303
 * @param int $sessionId session_id
2304
 * @param int $workId work_id
2305
 *
2306
 *
2307
 * @author Guillaume Viguier <[email protected]>
2308
 * @author Julio Montoya <[email protected]> Adding session support - 2011
2309
 */
2310
function send_email_on_homework_creation($courseId, $sessionId = 0, $workId)
2311
{
2312
    $courseInfo = api_get_course_info_by_id($courseId);
2313
    $courseCode = $courseInfo['code'];
2314
    // Get the students of the course
2315 View Code Duplication
    if (empty($session_id)) {
0 ignored issues
show
Bug introduced by
The variable $session_id seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
2316
        $students = CourseManager::get_student_list_from_course_code($courseCode);
2317
    } else {
2318
        $students = CourseManager::get_student_list_from_course_code($courseCode, true, $sessionId);
2319
    }
2320
    $emailsubject = '[' . api_get_setting('siteName') . '] '.get_lang('HomeworkCreated');
2321
    $currentUser = api_get_user_info(api_get_user_id());
2322
    if (!empty($students)) {
2323
        foreach($students as $student) {
2324
            $user_info = api_get_user_info($student["user_id"]);
2325
            if(!empty($user_info["mail"])) {
2326
                $name_user = api_get_person_name(
2327
                    $user_info["firstname"],
2328
                    $user_info["lastname"],
2329
                    null,
2330
                    PERSON_NAME_EMAIL_ADDRESS
2331
                );
2332
                $link = api_get_path(WEB_CODE_PATH) . 'work/work_list_all.php?' . api_get_cidreq() . '&id=' . $workId;
2333
                $emailbody = get_lang('Dear')." ".$name_user.",\n\n";
2334
                $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$courseCode.". "."\n\n".
2335
                    '<a href="'. $link . '">' . get_lang('PleaseCheckHomeworkPage') . '</a>';
2336
                $emailbody .= "\n\n".api_get_person_name($currentUser["firstname"], $currentUser["lastname"]);
2337
2338
                $additionalParameters = array(
2339
                    'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE,
2340
                    'userId' => $student["user_id"],
2341
                    'courseTitle' => $courseCode,
2342
                    'link' => $link
2343
                );
2344
2345
                api_mail_html(
2346
                    $name_user,
2347
                    $user_info["mail"],
2348
                    $emailsubject,
2349
                    $emailbody,
2350
                    api_get_person_name(
2351
                        $currentUser["firstname"],
2352
                        $currentUser["lastname"],
2353
                        null,
2354
                        PERSON_NAME_EMAIL_ADDRESS
2355
                    ),
2356
                    $currentUser["mail"],
2357
                    null,
2358
                    null,
2359
                    null,
2360
                    $additionalParameters
2361
                );
2362
            }
2363
        }
2364
    }
2365
}
2366
2367
/**
2368
 * @param string $url
2369
 * @return bool
2370
 */
2371
function is_work_exist_by_url($url)
2372
{
2373
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2374
    $url = Database::escape_string($url);
2375
    $sql = "SELECT id FROM $work_table WHERE url='$url'";
2376
    $result = Database::query($sql);
2377
    if (Database::num_rows($result)> 0) {
2378
        $row = Database::fetch_row($result);
2379
        if (empty($row)) {
2380
            return false;
2381
        } else {
2382
            return true;
2383
        }
2384
    } else {
2385
        return false;
2386
    }
2387
}
2388
2389
/**
2390
 * @param $name
2391
 * @param $values
2392
 * @param string $checked
2393
 * @return string
2394
 */
2395 View Code Duplication
function make_select($name, $values, $checked = '')
2396
{
2397
    $output = '<select name="'.$name.'" id="'.$name.'">';
2398
    foreach ($values as $key => $value) {
2399
        $output .= '<option value="'.$key.'" '.(($checked==$key) ? 'selected="selected"' : '').'>'.$value.'</option>';
2400
    }
2401
    $output .= '</select>';
2402
    return $output;
2403
}
2404
2405
/**
2406
 * @param $name
2407
 * @param string $checked
2408
 * @param null $label
2409
 * @return string
2410
 */
2411
function make_checkbox($name, $checked = '', $label = null)
2412
{
2413
    $check = '<input id ="'.$name.'" type="checkbox" value="1" name="'.$name.'" '.((!empty($checked))?'checked="checked"':'').'/>';
2414
    if (!empty($label)) {
2415
        $check .="<label for ='$name'>$label</label>";
2416
    }
2417
    return $check;
2418
}
2419
2420
/**
2421
 * @param $prefix
2422
 * @param string $default
2423
 * @return string
2424
 */
2425
function draw_date_picker($prefix, $default = '')
2426
{
2427
    if (empty($default)) {
2428
        $default = api_get_local_time();
2429
    }
2430
    $parts = explode(' ', $default);
2431
    list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
2432
    list($d_hour, $d_minute) = explode(':', $parts[1]);
2433
2434
    $minute = range(10, 59);
2435
    array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
2436
    $date_form = make_select($prefix.'_day', array_combine(range(1, 31), range(1, 31)), $d_day);
2437
    $date_form .= make_select($prefix.'_month', array_combine(range(1, 12), api_get_months_long()), $d_month);
2438
    $date_form .= make_select($prefix.'_year', array($d_year => $d_year, $d_year + 1 => $d_year + 1), $d_year).'&nbsp;&nbsp;&nbsp;&nbsp;';
2439
    $date_form .= make_select($prefix.'_hour', array_combine(range(0, 23), range(0, 23)), $d_hour).' : ';
2440
    $date_form .= make_select($prefix.'_minute', $minute, $d_minute);
2441
    return $date_form;
2442
}
2443
2444
/**
2445
 * @param string $prefix
2446
 * @param array of values
2447
 * @return string
2448
 *
2449
 */
2450 View Code Duplication
function get_date_from_select($prefix, $array = array())
2451
{
2452
    return
2453
        $array[$prefix]['year'].'-'.
2454
        two_digits($array[$prefix]['month']).'-'.
2455
        two_digits($array[$prefix]['day']).' '.
2456
        two_digits($array[$prefix]['hour']).':'.
2457
        two_digits($array[$prefix]['minute']).':00';
2458
}
2459
2460
/**
2461
 * Check if a user is the author of a work document.
2462
 * @param int $itemId
2463
 * @param int $userId
2464
 * @param int $courseId
2465
 * @param int $sessionId
2466
 * @return bool
2467
 */
2468
function user_is_author($itemId, $userId = null, $courseId = null, $sessionId = null)
2469
{
2470
    if (empty($itemId)) {
2471
        return false;
2472
    }
2473
2474
    if (empty($userId)) {
2475
        $userId = api_get_user_id();
2476
    }
2477
2478
    $isAuthor = false;
2479
    $is_allowed_to_edit = api_is_allowed_to_edit();
2480
2481
    if ($is_allowed_to_edit) {
2482
        $isAuthor = true;
2483
    } else {
2484
2485
        if (empty($courseId)) {
2486
            $courseId = api_get_course_int_id();
2487
        }
2488
        if (empty($sessionId)) {
2489
            $sessionId = api_get_session_id();
2490
        }
2491
2492
        $data = api_get_item_property_info($courseId, 'work', $itemId, $sessionId);
2493
        if ($data['insert_user_id'] == $userId) {
2494
            $isAuthor = true;
2495
        }
2496
2497
        $workData = get_work_data_by_id($itemId);
2498
        if ($workData['user_id'] == $userId) {
2499
            $isAuthor = true;
2500
        }
2501
    }
2502
2503
    if (!$isAuthor) {
2504
        return false;
2505
    }
2506
2507
    return $isAuthor;
2508
}
2509
2510
/**
2511
 * Get list of users who have not given the task
2512
 * @param int
2513
 * @param int
2514
 * @return array
2515
 * @author cvargas
2516
 * @author Julio Montoya <[email protected]> Fixing query
2517
 */
2518
function get_list_users_without_publication($task_id, $studentId = null)
2519
{
2520
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2521
    $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
2522
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2523
    $session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2524
2525
    $users = getAllUserToWork($task_id, api_get_course_int_id());
2526
    $users = array_column($users, 'user_id');
2527
2528
    // Condition for the session
2529
    $session_id = api_get_session_id();
2530
    $course_id = api_get_course_int_id();
2531
    $task_id = intval($task_id);
2532
2533
    if ($session_id == 0) {
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' AND
2544
                    session_id = '".$session_id."' AND
2545
                    active IN (0, 1)";
2546
    }
2547
2548
    $result = Database::query($sql);
2549
    $users_with_tasks = array();
2550
    while ($row = Database::fetch_array($result)) {
2551
        $users_with_tasks[] = $row['id'];
2552
    }
2553
2554
    if ($session_id == 0) {
2555
        $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
2556
                      FROM $table_course_user AS cu, $table_user AS u
2557
                      WHERE u.status != 1 and cu.c_id='".$course_id."' AND u.user_id = cu.user_id";
2558
    } else {
2559
        $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email
2560
                      FROM $session_course_rel_user AS cu, $table_user AS u
2561
                      WHERE
2562
                        u.status != 1 AND
2563
                        cu.c_id='".$course_id."' AND
2564
                        u.user_id = cu.user_id AND
2565
                        cu.session_id = '".$session_id."'";
2566
    }
2567
2568
    if (!empty($studentId)) {
2569
        $sql_users.= " AND u.user_id = ".intval($studentId);
2570
    }
2571
2572
    $group_id = api_get_group_id();
2573
2574
    $new_group_user_list = array();
2575
2576
    if ($group_id) {
2577
        $group_user_list = GroupManager::get_subscribed_users($group_id);
2578
        if (!empty($group_user_list)) {
2579
            foreach($group_user_list as $group_user) {
2580
                $new_group_user_list[] = $group_user['user_id'];
2581
            }
2582
        }
2583
    }
2584
2585
    $result_users = Database::query($sql_users);
2586
    $users_without_tasks = array();
2587
    while ($rowUsers = Database::fetch_array($result_users)) {
2588
        $userId = $rowUsers['user_id'];
2589
        if (in_array($userId, $users_with_tasks)) {
2590
            continue;
2591
        }
2592
2593
        if ($group_id && !in_array($userId, $new_group_user_list)) {
2594
            continue;
2595
        }
2596
2597
        if (!empty($users)) {
2598
            if (!in_array($userId, $users)) {
2599
                continue;
2600
            }
2601
        }
2602
2603
        $row_users = [];
2604
        $row_users[0] = $rowUsers['lastname'];
2605
        $row_users[1] = $rowUsers['firstname'];
2606
        $row_users[2] = Display::encrypted_mailto_link($rowUsers['email']);
2607
        $row_users[3] = $userId;
2608
        $users_without_tasks[] = $row_users;
2609
    }
2610
2611
    return $users_without_tasks;
2612
}
2613
2614
/**
2615
 * Display list of users who have not given the task
2616
 *
2617
 * @param int task id
2618
 * @param int $studentId
2619
 * @return array
2620
 * @author cvargas [email protected] cfasanando, [email protected]
2621
 * @author Julio Montoya <[email protected]> Fixes
2622
 */
2623
function display_list_users_without_publication($task_id, $studentId = null)
2624
{
2625
    global $origin;
2626
    $table_header[] = array(get_lang('LastName'), true);
2627
    $table_header[] = array(get_lang('FirstName'), true);
2628
    $table_header[] = array(get_lang('Email'), true);
2629
2630
    $data = get_list_users_without_publication($task_id);
2631
2632
    $sorting_options = array();
2633
    $sorting_options['column'] = 1;
2634
    $paging_options = array();
2635
    $my_params = array();
2636
2637
    if (isset($_GET['edit_dir'])) {
2638
        $my_params['edit_dir'] = Security::remove_XSS($_GET['edit_dir']);
2639
    }
2640
    if (isset($_GET['list'])) {
2641
        $my_params['list'] = Security::remove_XSS($_GET['list']);
2642
    }
2643
    $my_params['origin'] = $origin;
2644
    $my_params['id'] = intval($_GET['id']);
2645
2646
    //$column_show
2647
    $column_show[] = 1;
2648
    $column_show[] = 1;
2649
    $column_show[] = 1;
2650
    Display::display_sortable_config_table(
2651
        'work',
2652
        $table_header,
2653
        $data,
2654
        $sorting_options,
2655
        $paging_options,
2656
        $my_params,
2657
        $column_show
2658
    );
2659
}
2660
2661
/**
2662
 * @param int $documentId
2663
 * @param int $workId
2664
 * @param int $courseId
2665
 */
2666 View Code Duplication
function addDocumentToWork($documentId, $workId, $courseId)
2667
{
2668
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2669
    $params = array(
2670
        'document_id' => $documentId,
2671
        'work_id' => $workId,
2672
        'c_id' => $courseId
2673
    );
2674
    Database::insert($table, $params);
2675
}
2676
2677
/**
2678
 * @param int $documentId
2679
 * @param int $workId
2680
 * @param int $courseId
2681
 * @return array
2682
 */
2683 View Code Duplication
function getDocumentToWork($documentId, $workId, $courseId)
2684
{
2685
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2686
    $params = array(
2687
        'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
2688
    );
2689
    return Database::select('*', $table, array('where' => $params));
2690
}
2691
2692
/**
2693
 * @param int $documentId
2694
 * @param int $workId
2695
 * @param int $courseId
2696
 * @param int $sessionId
2697
 * @param int $userId
2698
 * @param int $active
2699
 * @return array
2700
 */
2701
function getDocumentToWorkPerUser($documentId, $workId, $courseId, $sessionId, $userId, $active = 1)
2702
{
2703
    $workRel = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2704
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2705
2706
    $documentId = intval($documentId);
2707
    $workId = intval($workId);
2708
    $courseId = intval($courseId);
2709
    $userId = intval($userId);
2710
    $sessionId = intval($sessionId);
2711
    $active = intval($active);
2712
2713
    $sql = "SELECT w.* FROM $work w INNER JOIN $workRel rel ON (w.parent_id = rel.work_id)
2714
            WHERE
2715
                w.document_id = $documentId AND
2716
                w.parent_id = $workId AND
2717
                w.c_id = $courseId AND
2718
                w.session_id = $sessionId AND
2719
                user_id = $userId AND
2720
                active = $active
2721
            ";
2722
2723
    $result = Database::query($sql);
2724
    $workInfo = array();
2725
    if (Database::num_rows($result)) {
2726
        $workInfo = Database::fetch_array($result, 'ASSOC');
2727
    }
2728
    return $workInfo;
2729
}
2730
2731
/**
2732
 *
2733
 * @param int $workId
2734
 * @param int $courseId
2735
 * @return array
2736
 */
2737 View Code Duplication
function getAllDocumentToWork($workId, $courseId)
2738
{
2739
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2740
    $params = array(
2741
        'work_id = ? and c_id = ?' => array($workId, $courseId)
2742
    );
2743
    return Database::select('*', $table, array('where' => $params));
2744
}
2745
2746
/**
2747
 * @param int $documentId
2748
 * @param int $workId
2749
 * @param int $courseId
2750
 */
2751 View Code Duplication
function deleteDocumentToWork($documentId, $workId, $courseId)
2752
{
2753
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
2754
    $params = array(
2755
        'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
2756
    );
2757
    Database::delete($table, $params);
2758
}
2759
2760
/**
2761
 * @param int $userId
2762
 * @param int $workId
2763
 * @param int $courseId
2764
 */
2765 View Code Duplication
function addUserToWork($userId, $workId, $courseId)
2766
{
2767
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
2768
    $params = array(
2769
        'user_id' => $userId,
2770
        'work_id' => $workId,
2771
        'c_id' => $courseId
2772
    );
2773
    Database::insert($table, $params);
2774
}
2775
2776
/**
2777
 * @param int $userId
2778
 * @param int $workId
2779
 * @param int $courseId
2780
 * @return array
2781
 */
2782 View Code Duplication
function getUserToWork($userId, $workId, $courseId)
2783
{
2784
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
2785
    $params = array(
2786
        'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
2787
    );
2788
    return Database::select('*', $table, array('where' => $params));
2789
}
2790
2791
/**
2792
 * @param int $workId
2793
 * @param int $courseId
2794
 * @param bool $getCount
2795
 * @return array
2796
 */
2797
function getAllUserToWork($workId, $courseId, $getCount = false)
2798
{
2799
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
2800
    $params = array(
2801
        'work_id = ? and c_id = ?' => array($workId, $courseId)
2802
    );
2803
    if ($getCount) {
2804
        $count = 0;
2805
        $result = Database::select(
2806
            'count(user_id) as count',
2807
            $table,
2808
            array('where' => $params),
2809
            'simple'
2810
        );
2811
        if (!empty($result)) {
2812
            $count = intval($result['count']);
2813
        }
2814
        return $count;
2815
    } else {
2816
        return Database::select('*', $table, array('where' => $params));
2817
    }
2818
}
2819
2820
/**
2821
 * @param int $userId
2822
 * @param int $workId
2823
 * @param int $courseId
2824
 */
2825 View Code Duplication
function deleteUserToWork($userId, $workId, $courseId)
2826
{
2827
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
2828
    $params = array(
2829
        'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
2830
    );
2831
    Database::delete($table, $params);
2832
}
2833
2834
/**
2835
 * @param int $userId
2836
 * @param int $workId
2837
 * @param int $courseId
2838
 * @return bool
2839
 */
2840
function userIsSubscribedToWork($userId, $workId, $courseId)
2841
{
2842
    $subscribedUsers = getAllUserToWork($workId, $courseId);
2843
2844
    if (empty($subscribedUsers)) {
2845
        return true;
2846
    } else {
2847
        $subscribedUsersList = array();
2848
        foreach ($subscribedUsers as $item) {
2849
            $subscribedUsersList[] = $item['user_id'];
2850
        }
2851
        if (in_array($userId, $subscribedUsersList)) {
2852
            return true;
2853
        }
2854
    }
2855
    return false;
2856
}
2857
2858
/**
2859
 * Get the list of students that have to submit their work
2860
 * @param integer $workId The internal ID of the assignment
2861
 * @param integer $courseId The course ID
2862
 * @param integer $groupId The group ID, if any
2863
 * @param integer $sessionId The session ID, if any
2864
 * @param bool $getCount Whether we want just the amount or the full result
2865
 * @return array|int An integer (if we just asked for the count) or an array of users
2866
 */
2867
function getStudentSubscribedToWork(
2868
    $workId,
2869
    $courseId,
2870
    $groupId = null,
2871
    $sessionId = null,
2872
    $getCount = false
2873
) {
2874
    $usersInWork = null;
2875
    $usersInCourse = null;
2876
2877
    if (empty($groupId)) {
2878
        $courseInfo = api_get_course_info_by_id($courseId);
2879
        $status = STUDENT;
2880
        if (!empty($sessionId)) {
2881
            $status = 0;
2882
        }
2883
        $usersInCourse = CourseManager::get_user_list_from_course_code(
2884
            $courseInfo['code'],
2885
            $sessionId,
2886
            null,
2887
            null,
2888
            $status,
2889
            $getCount
2890
        );
2891
    } else {
2892
        $usersInCourse = GroupManager::get_users(
2893
            $groupId,
2894
            false,
2895
            null,
2896
            null,
2897
            $getCount,
2898
            $courseId
2899
        );
2900
    }
2901
2902
    $usersInWork = getAllUserToWork($workId, $courseId, $getCount);
2903
2904
    if (empty($usersInWork)) {
2905
        return $usersInCourse;
2906
    } else {
2907
        return $usersInWork;
2908
    }
2909
2910
}
2911
2912
/**
2913
 * @param int $userId
2914
 * @param int $workId
2915
 * @param int $courseId
2916
 * @return bool
2917
 */
2918
function allowOnlySubscribedUser($userId, $workId, $courseId)
2919
{
2920
    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
2921
        return true;
2922
    }
2923
2924
    if (userIsSubscribedToWork($userId, $workId, $courseId) == false) {
2925
        api_not_allowed(true);
2926
    }
2927
}
2928
2929
/**
2930
 * @param int $workId
2931
 * @param array $courseInfo
2932
 * @param int $documentId
2933
 * @return array
2934
 */
2935
function getDocumentTemplateFromWork($workId, $courseInfo, $documentId)
2936
{
2937
    $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
2938
    if (!empty($documents)) {
2939
        foreach ($documents as $doc) {
2940
            if ($documentId != $doc['document_id']) {
2941
                continue;
2942
            }
2943
            $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
2944
            $fileInfo = pathinfo($docData['path']);
2945
            if ($fileInfo['extension'] == 'html') {
2946
                if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
2947
                    $docData['file_content'] = file_get_contents($docData['absolute_path']);
2948
                    return $docData;
2949
                }
2950
            }
2951
        }
2952
    }
2953
    return array();
2954
}
2955
2956
/**
2957
 * @param int $workId
2958
 * @param array $courseInfo
2959
 * @return string
2960
 */
2961
function getAllDocumentsFromWorkToString($workId, $courseInfo)
2962
{
2963
    $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
2964
    $content = null;
2965
    if (!empty($documents)) {
2966
        $content .= '<ul class="nav nav-list well">';
2967
        $content .= '<li class="nav-header">'.get_lang('Documents').'</li>';
2968
        foreach ($documents as $doc) {
2969
            $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
2970
            if ($docData) {
2971
                $content .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
2972
            }
2973
        }
2974
        $content .= '</ul><br />';
2975
    }
2976
    return $content;
2977
}
2978
2979
/**
2980
 * Returns fck editor toolbar
2981
 * @return array
2982
 */
2983
function getWorkDescriptionToolbar()
2984
{
2985
    return array(
2986
        'ToolbarStartExpanded' => 'true',
2987
        'ToolbarSet' => 'Work',
2988
        'Width' => '100%',
2989
        'Height' => '400'
2990
    );
2991
}
2992
2993
/**
2994
 * @param array $work
2995
 * @return array
2996
 */
2997
function getWorkComments($work)
2998
{
2999
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3000
    $userTable= Database::get_main_table(TABLE_MAIN_USER);
3001
3002
    $courseId = intval($work['c_id']);
3003
    $workId = intval($work['id']);
3004
3005
    if (empty($courseId) || empty($workId)) {
3006
        return array();
3007
    }
3008
3009
    $sql = "SELECT
3010
            c.id, c.user_id, u.firstname, u.lastname, u.username, u.picture_uri
3011
            FROM $commentTable c
3012
            INNER JOIN $userTable u ON (u.user_id = c.user_id)
3013
            WHERE c_id = $courseId AND work_id = $workId
3014
            ORDER BY sent_at
3015
            ";
3016
    $result = Database::query($sql);
3017
    $comments = Database::store_result($result, 'ASSOC');
3018
    if (!empty($comments)) {
3019
        foreach ($comments as &$comment) {
3020
            $comment['picture'] = UserManager::getUserPicture($comment['user_id']);
3021
            $commentInfo = getWorkComment($comment['id']);
3022
3023
            if (!empty($commentInfo)) {
3024
                $comment = array_merge($comment, $commentInfo);
3025
            }
3026
        }
3027
    }
3028
    return $comments;
3029
}
3030
3031
/**
3032
 * Get total score from a work list
3033
 * @param $workList
3034
 * @return int|null
3035
 */
3036
function getTotalWorkScore($workList)
3037
{
3038
    $count = 0;
3039
    foreach ($workList as $data) {
3040
        $count += $data['qualification_score'];
3041
    }
3042
    return $count;
3043
}
3044
3045
3046
/**
3047
 * Get comment count from a work list (docs sent by students)
3048
 * @param array $workList
3049
 * @param array $courseInfo
3050
 * @return int|null
3051
 */
3052
function getTotalWorkComment($workList, $courseInfo = array())
3053
{
3054
    if (empty($courseInfo)) {
3055
        $courseInfo = api_get_course_info();
3056
    }
3057
3058
    $count = 0;
3059
    foreach ($workList as $data) {
3060
        $count += getWorkCommentCount($data['id'], $courseInfo);
3061
    }
3062
    return $count;
3063
}
3064
3065
/**
3066
 * Get comment count for a specific work sent by a student.
3067
 * @param int $id
3068
 * @param array $courseInfo
3069
 * @return int
3070
 */
3071 View Code Duplication
function getWorkCommentCount($id, $courseInfo = array())
3072
{
3073
    if (empty($courseInfo)) {
3074
        $courseInfo = api_get_course_info();
3075
    }
3076
3077
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3078
    $id = intval($id);
3079
3080
    $sql = "SELECT count(*) as count
3081
            FROM $commentTable
3082
            WHERE work_id = $id AND c_id = ".$courseInfo['real_id'];
3083
3084
    $result = Database::query($sql);
3085
    if (Database::num_rows($result)) {
3086
        $comment = Database::fetch_array($result);
3087
        return $comment['count'];
3088
    }
3089
3090
    return 0;
3091
}
3092
3093
/**
3094
 * Get comment count for a specific parent
3095
 * @param int $parentId
3096
 * @param array $courseInfo
3097
 * @param int $sessionId
3098
 * @return int
3099
 */
3100 View Code Duplication
function getWorkCommentCountFromParent(
3101
    $parentId,
3102
    $courseInfo = array(),
3103
    $sessionId = 0
3104
) {
3105
    if (empty($courseInfo)) {
3106
        $courseInfo = api_get_course_info();
3107
    }
3108
3109
    if (empty($sessionId)) {
3110
        $sessionId = api_get_session_id();
3111
    } else {
3112
        $sessionId = intval($sessionId);
3113
    }
3114
3115
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3116
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3117
    $parentId = intval($parentId);
3118
3119
    $sql = "SELECT count(*) as count
3120
            FROM $commentTable c INNER JOIN $work w
3121
            ON c.c_id = w.c_id AND w.id = c.work_id
3122
            WHERE
3123
                session_id = $sessionId AND
3124
                parent_id = $parentId AND
3125
                w.c_id = ".$courseInfo['real_id'];
3126
3127
    $result = Database::query($sql);
3128
    if (Database::num_rows($result)) {
3129
        $comment = Database::fetch_array($result);
3130
        return $comment['count'];
3131
    }
3132
3133
    return 0;
3134
}
3135
3136
/**
3137
 * Get last work information from parent
3138
 * @param int $parentId
3139
 * @param array $courseInfo
3140
 * @param int $sessionId
3141
 * @return int
3142
 */
3143 View Code Duplication
function getLastWorkStudentFromParent(
3144
    $parentId,
3145
    $courseInfo = array(),
3146
    $sessionId = 0
3147
) {
3148
    if (empty($courseInfo)) {
3149
        $courseInfo = api_get_course_info();
3150
    }
3151
3152
    if (empty($sessionId)) {
3153
        $sessionId = api_get_session_id();
3154
    } else {
3155
        $sessionId = intval($sessionId);
3156
    }
3157
3158
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3159
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3160
    $parentId = intval($parentId);
3161
3162
    $sql = "SELECT w.*
3163
            FROM $commentTable c INNER JOIN $work w
3164
            ON c.c_id = w.c_id AND w.id = c.work_id
3165
            WHERE
3166
                session_id = $sessionId AND
3167
                parent_id = $parentId AND
3168
                w.c_id = ".$courseInfo['real_id']."
3169
            ORDER BY w.sent_date
3170
            LIMIT 1
3171
            ";
3172
3173
    $result = Database::query($sql);
3174
    if (Database::num_rows($result)) {
3175
        $comment = Database::fetch_array($result, 'ASSOC');
3176
        /*if (!empty($comment)) {
3177
            $comment['assignment'] = get_work_assignment_by_id(
3178
                $comment['id'],
3179
                $courseInfo['real_id']
3180
            );
3181
        }*/
3182
        return $comment;
3183
    }
3184
3185
    return array();
3186
}
3187
3188
/**
3189
 * Get last work information from parent
3190
 * @param int $parentId
3191
 * @param array $courseInfo
3192
 * @param int $sessionId
3193
 * @return int
3194
 */
3195 View Code Duplication
function getLastWorkStudentFromParentByUser(
3196
    $userId,
3197
    $parentId,
3198
    $courseInfo = array(),
3199
    $sessionId = 0
3200
) {
3201
    if (empty($courseInfo)) {
3202
        $courseInfo = api_get_course_info();
3203
    }
3204
3205
    if (empty($sessionId)) {
3206
        $sessionId = api_get_session_id();
3207
    } else {
3208
        $sessionId = intval($sessionId);
3209
    }
3210
3211
    $userId = intval($userId);
3212
    $work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3213
    $parentId = intval($parentId);
3214
3215
    $sql = "SELECT *
3216
            FROM  $work
3217
            WHERE
3218
                user_id = $userId AND
3219
                session_id = $sessionId AND
3220
                parent_id = $parentId AND
3221
                c_id = ".$courseInfo['real_id']."
3222
            ORDER BY sent_date DESC
3223
            LIMIT 1
3224
            ";
3225
    $result = Database::query($sql);
3226
    if (Database::num_rows($result)) {
3227
        $work = Database::fetch_array($result, 'ASSOC');
3228
        /*if (!empty($comment)) {
3229
            $comment['assignment'] = get_work_assignment_by_id(
3230
                $comment['id'],
3231
                $courseInfo['real_id']
3232
            );
3233
        }*/
3234
        return $work;
3235
    }
3236
3237
    return array();
3238
}
3239
3240
/**
3241
 * @param int $id comment id
3242
 * @param array $courseInfo
3243
 * @return string
3244
 */
3245
function getWorkComment($id, $courseInfo = array())
3246
{
3247
    if (empty($courseInfo)) {
3248
        $courseInfo = api_get_course_info();
3249
    }
3250
3251
    if (empty($courseInfo['real_id'])) {
3252
        return array();
3253
    }
3254
3255
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3256
    $id = intval($id);
3257
3258
    $sql = "SELECT * FROM $commentTable
3259
            WHERE id = $id AND c_id = ".$courseInfo['real_id'];
3260
    $result = Database::query($sql);
3261
    $comment = array();
3262
    if (Database::num_rows($result)) {
3263
        $comment = Database::fetch_array($result, 'ASSOC');
3264
        $filePath = null;
3265
        $fileUrl = null;
3266
        $deleteUrl = null;
3267
        $fileName = null;
3268
        if (!empty($comment['file'])) {
3269
            $work = get_work_data_by_id($comment['work_id']);
3270
            $workParent = get_work_data_by_id($work['parent_id']);
3271
            $filePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'.$workParent['url'].'/'.$comment['file'];
3272
            $fileUrl = api_get_path(WEB_CODE_PATH).'work/download_comment_file.php?comment_id='.$id.'&'.api_get_cidreq();
3273
            $deleteUrl = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$comment['work_id'].'&action=delete_attachment&comment_id='.$id;
3274
            $fileParts = explode('_', $comment['file']);
3275
            $fileName = str_replace($fileParts[0].'_'.$fileParts[1].'_', '', $comment['file']);
3276
        }
3277
        $comment['delete_file_url'] = $deleteUrl;
3278
        $comment['file_path'] = $filePath;
3279
        $comment['file_url'] = $fileUrl;
3280
        $comment['file_name_to_show'] = $fileName;
3281
    }
3282
3283
    return $comment;
3284
}
3285
3286
/**
3287
 * @param int $id
3288
 * @param array $courseInfo
3289
 */
3290
function deleteCommentFile($id, $courseInfo = array())
3291
{
3292
    $workComment = getWorkComment($id, $courseInfo);
3293
    if (isset($workComment['file']) && !empty($workComment['file'])) {
3294
        if (file_exists($workComment['file_path'])) {
3295
            $result = my_delete($workComment['file_path']);
3296
            if ($result) {
3297
                $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3298
                $params = array('file' => '');
3299
                Database::update(
3300
                    $commentTable,
3301
                    $params,
3302
                    array('id = ? AND c_id = ? ' => array($workComment['id'], $workComment['c_id']))
3303
                );
3304
            }
3305
        }
3306
    }
3307
}
3308
3309
/**
3310
 * Adds a comments to the work document
3311
 * @param array $courseInfo
3312
 * @param int $userId
3313
 * @param array $work
3314
 * @param array $data
3315
 * @return int
3316
 */
3317
function addWorkComment($courseInfo, $userId, $parentWork, $work, $data)
3318
{
3319
    $commentTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT_COMMENT);
3320
3321
    $params = array(
3322
        'work_id' => $work['id'],
3323
        'c_id' => $work['c_id'],
3324
        'user_id' => $userId,
3325
        'comment' => $data['comment'],
3326
        'sent_at' => api_get_utc_datetime()
3327
    );
3328
3329
    $commentId = Database::insert($commentTable, $params);
3330
3331
    if ($commentId) {
3332
        $sql = "UPDATE $commentTable SET id = iid WHERE iid = $commentId";
3333
        Database::query($sql);
3334
    }
3335
3336
    $userIdListToSend = array();
3337
3338
    if (api_is_allowed_to_edit()) {
3339
        if (isset($data['send_mail']) && $data['send_mail']) {
3340
            // Teacher sends a feedback
3341
            $userIdListToSend = array($work['user_id']);
3342
        }
3343
    } else {
3344
        $sessionId = api_get_session_id();
3345
        if (empty($sessionId)) {
3346
            $teachers = CourseManager::get_teacher_list_from_course_code(
3347
                $courseInfo['code']
3348
            );
3349
            if (!empty($teachers)) {
3350
                $userIdListToSend = array_keys($teachers);
3351
            }
3352
        } else {
3353
            $teachers = SessionManager::getCoachesByCourseSession(
3354
                $sessionId,
3355
                $courseInfo['code']
3356
            );
3357
3358
            if (!empty($teachers)) {
3359
                $userIdListToSend = array_values($teachers);
3360
            }
3361
        }
3362
    }
3363
3364
    $url = api_get_path(WEB_CODE_PATH).'work/view.php?'.api_get_cidreq().'&id='.$work['id'];
3365
    $subject = sprintf(get_lang('ThereIsANewWorkFeedback'), $parentWork['title']);
3366
    $content = sprintf(get_lang('ThereIsANewWorkFeedbackInWorkXHere'), $work['title'], $url);
3367
3368
    if (!empty($userIdListToSend)) {
3369
        foreach ($userIdListToSend as $userId) {
3370
            MessageManager::send_message_simple(
3371
                $userId,
3372
                $subject,
3373
                $content
3374
            );
3375
        }
3376
    }
3377
3378
    $fileData = isset($data['file']) ? $data['file'] : null;
3379
    if (!empty($commentId) && !empty($fileData)) {
3380
        $workParent = get_work_data_by_id($work['parent_id']);
3381
        if (!empty($workParent)) {
3382
            $uploadDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work'.$workParent['url'];
3383
            $newFileName = 'comment_'.$commentId.'_'.php2phps(
3384
                    api_replace_dangerous_char($fileData['name'])
3385
                );
3386
            $newFilePath = $uploadDir.'/'.$newFileName;
3387
            $result = move_uploaded_file($fileData['tmp_name'], $newFilePath);
3388
            if ($result) {
3389
                $params = array('file' => $newFileName);
3390
                Database::update(
3391
                    $commentTable,
3392
                    $params,
3393
                    array('id = ? AND c_id = ? ' => array($commentId, $work['c_id']))
3394
                );
3395
            }
3396
        }
3397
    }
3398
}
3399
3400
/**
3401
 * @param array $work
3402
 * @param string $page
3403
 * @return string
3404
 */
3405
function getWorkCommentForm($work, $page = 'view')
3406
{
3407
    $url = api_get_path(WEB_CODE_PATH).'work/view.php?id='.$work['id'].'&action=send_comment&'.api_get_cidreq().'&page='.$page;
3408
    $form = new FormValidator(
3409
        'work_comment',
3410
        'post',
3411
        $url
3412
    );
3413
3414
    $form->addElement('file', 'file', get_lang('Attachment'));
3415
    $form->addHtmlEditor('comment', get_lang('Comment'));
3416
    $form->addElement('hidden', 'id', $work['id']);
3417
    $form->addElement('hidden', 'page', $page);
3418
    if (api_is_allowed_to_edit()) {
3419
        $form->addElement('checkbox', 'send_mail', null, get_lang('SendMail'));
3420
    }
3421
    $form->addButtonSend(get_lang('Send'), 'button');
3422
3423
    return $form->returnForm();
3424
}
3425
3426
/**
3427
 * @param array $homework result of get_work_assignment_by_id()
3428
 * @return string
3429
 */
3430
function getWorkDateValidationStatus($homework)
3431
{
3432
    $message = null;
3433
    $has_expired = false;
3434
    $has_ended = false;
3435
3436
    if (!empty($homework)) {
3437
3438 View Code Duplication
        if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) {
3439
            $time_now = time();
3440
3441
            if (!empty($homework['expires_on'])) {
3442
                $time_expires   = api_strtotime($homework['expires_on'], 'UTC');
3443
                $difference     = $time_expires - $time_now;
3444
                if ($difference < 0) {
3445
                    $has_expired = true;
3446
                }
3447
            }
3448
3449
            if (empty($homework['expires_on'])) {
3450
                $has_expired = false;
3451
            }
3452
3453
            if (!empty($homework['ends_on'])) {
3454
                $time_ends = api_strtotime($homework['ends_on'], 'UTC');
3455
                $difference2 = $time_ends - $time_now;
3456
                if ($difference2 < 0) {
3457
                    $has_ended = true;
3458
                }
3459
            }
3460
3461
            $ends_on = api_convert_and_format_date($homework['ends_on']);
3462
            $expires_on = api_convert_and_format_date($homework['expires_on']);
3463
        }
3464
3465
        if ($has_ended) {
3466
            $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
3467
        } elseif ($has_expired) {
3468
            $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
3469
        } else {
3470
            if ($has_expired) {
3471
                $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
3472
            }
3473
        }
3474
    }
3475
3476
    return array(
3477
        'message' => $message,
3478
        'has_ended' => $has_ended,
3479
        'has_expired' => $has_expired
3480
    );
3481
}
3482
3483
/**
3484
 * @param FormValidator $form
3485
 * @param int $uploadFormType
3486
 */
3487
function setWorkUploadForm($form, $uploadFormType = 0)
3488
{
3489
    $form->addElement('header', get_lang('UploadADocument'));
3490
    $form->addElement('hidden', 'contains_file', 0, array('id'=>'contains_file_id'));
3491
    $form->addElement('hidden', 'active', 1);
3492
    $form->addElement('hidden', 'accepted', 1);
3493
    $form->addElement('text', 'title', get_lang('Title'), array('id' => 'file_upload'));
3494
    $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
3495
3496
    switch ($uploadFormType) {
3497
        case 0:
3498
            // File and text.
3499
            $form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
3500
            $form->add_real_progress_bar('uploadWork', 'file');
3501
            $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
3502
            break;
3503
        case 1:
3504
            // Only text.
3505
            $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
3506
            $form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
3507
            break;
3508
        case 2:
3509
            // Only file.
3510
            $form->addElement('file', 'file', get_lang('UploadADocument'), 'size="40" onchange="updateDocumentTitle(this.value)"');
3511
            $form->add_real_progress_bar('uploadWork', 'file');
3512
            $form->addRule('file', get_lang('ThisFieldIsRequired'), 'required');
3513
            break;
3514
    }
3515
3516
    $form->addButtonUpload(get_lang('Upload'), 'submitWork');
3517
}
3518
3519
/**
3520
 * @param array $my_folder_data
3521
 * @param array $_course
3522
 * @param bool $isCorrection
3523
 * @param array $workInfo
3524
 * @param array $file
3525
 *
3526
 * @return array
3527
 */
3528
function uploadWork($my_folder_data, $_course, $isCorrection = false, $workInfo = [], $file = [])
3529
{
3530
    if (isset($_FILES['file']) && !empty($_FILES['file'])) {
3531
        $file = $_FILES['file'];
3532
    }
3533
3534
    if (empty($file['size'])) {
3535
        return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
3536
    }
3537
    $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload
3538
3539
    // Try to add an extension to the file if it has'nt one
3540
    $filename = add_ext_on_mime(stripslashes($file['name']), $file['type']);
3541
3542
    // Replace dangerous characters
3543
    $filename = api_replace_dangerous_char($filename);
3544
3545
    // Transform any .php file in .phps fo security
3546
    $filename = php2phps($filename);
3547
    $filesize = filesize($file['tmp_name']);
3548
3549
    if (empty($filesize)) {
3550
        return array(
3551
            'error' => Display:: return_message(
3552
                get_lang('UplUploadFailedSizeIsZero'),
3553
                'error'
3554
            ),
3555
        );
3556
    } elseif (!filter_extension($new_file_name)) {
3557
        return array(
3558
            'error' => Display:: return_message(
3559
                get_lang('UplUnableToSaveFileFilteredExtension'),
3560
                'error'
3561
            ),
3562
        );
3563
    }
3564
3565
    $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
3566
    $course_max_space = DocumentManager::get_course_quota($_course['code']);
3567
    $total_size = $filesize + $totalSpace;
3568
3569
    if ($total_size > $course_max_space) {
3570
        return array(
3571
            'error' => Display :: return_message(get_lang('NoSpace'), 'error')
3572
        );
3573
    }
3574
3575
    // Compose a unique file name to avoid any conflict
3576
    $new_file_name = api_get_unique_id();
3577
3578
    if ($isCorrection) {
3579
        if (!empty($workInfo['url'])) {
3580
            $new_file_name = basename($workInfo['url']).'_correction';
3581
        } else {
3582
            $new_file_name = $new_file_name.'_correction';
3583
        }
3584
    }
3585
3586
    $curdirpath = basename($my_folder_data['url']);
3587
3588
    // If we come from the group tools the groupid will be saved in $work_table
3589
    if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
3590
        $result = move_uploaded_file(
3591
            $file['tmp_name'],
3592
            $updir.$curdirpath.'/'.$new_file_name
3593
        );
3594
    } else {
3595
        return array(
3596
            'error' => Display :: return_message(
3597
                get_lang('FolderDoesntExistsInFileSystem'),
3598
                'error'
3599
            )
3600
        );
3601
    }
3602
3603
    $url = null;
3604
    if ($result) {
3605
        $url = 'work/'.$curdirpath.'/'.$new_file_name;
3606
    }
3607
3608
    return array(
3609
        'url' => $url,
3610
        'filename' => $filename,
3611
        'filesize' => $filesize,
3612
        'error' => null
3613
    );
3614
}
3615
3616
/**
3617
 * Send an e-mail to users related to this work (course teachers, usually, but
3618
 * might include other group members)
3619
 * @param int $workId
3620
 * @param array $courseInfo
3621
 * @param int $session_id
3622
 */
3623
function sendAlertToUsers($workId, $courseInfo, $session_id)
3624
{
3625
    $user_list = array();
3626
    //$workData = get_work_assignment_by_id($workId, $courseInfo['real_id']);
3627
    $workData = get_work_data_by_id($workId, $courseInfo['real_id'], $session_id);
3628
    //last value is to check this is not "just" an edit
3629
    //YW Tis part serve to send a e-mail to the tutors when a new file is sent
3630
    $send = api_get_course_setting('email_alert_manager_on_new_doc');
3631
3632
    if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_TEACHERS) {
3633
        // Lets predefine some variables. Be sure to change the from address!
3634
        if (empty($session_id)) {
3635
            //Teachers
3636
            $user_list = CourseManager::get_user_list_from_course_code(
3637
                api_get_course_id(),
3638
                null,
3639
                null,
3640
                null,
3641
                COURSEMANAGER
3642
            );
3643
        } else {
3644
            // Coaches
3645
            $user_list = CourseManager::get_user_list_from_course_code(
3646
                api_get_course_id(),
3647
                $session_id,
3648
                null,
3649
                null,
3650
                2
3651
            );
3652
        }
3653
    }
3654
3655
    if ($send == SEND_EMAIL_EVERYONE || $send == SEND_EMAIL_STUDENTS) {
3656
        if (!$session_id) {
3657
            $session_id = null;
3658
        }
3659
        $student = CourseManager::get_user_list_from_course_code(
3660
            api_get_course_id(),
3661
            $session_id,
3662
            null,
3663
            null,
3664
            STUDENT,
3665
            null,
3666
            null,
3667
            null,
3668
            null,
3669
            null,
3670
            array(api_get_user_id())
3671
        );
3672
        $user_list = array_merge($user_list, $student);
3673
    }
3674
3675
    if ($send) {
3676
        $senderEmail = api_get_setting('emailAdministrator');
3677
        $senderName = api_get_person_name(
3678
            api_get_setting('administratorName'),
3679
            api_get_setting('administratorSurname'),
3680
            null,
3681
            PERSON_NAME_EMAIL_ADDRESS
3682
        );
3683
        $subject = "[" . api_get_setting('siteName') . "] ".get_lang('SendMailBody')."\n ".get_lang('CourseName').": ".$courseInfo['name']."  ";
3684
        foreach ($user_list as $user_data) {
0 ignored issues
show
Bug introduced by
The expression $user_list of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3685
            $to_user_id = $user_data['user_id'];
3686
            $user_info = api_get_user_info($to_user_id);
3687
            $message = get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$courseInfo['name']."\n";
3688
            $message .= get_lang('UserName')." : ".api_get_person_name($user_info['firstname'], $user_info['lastname'])."\n";
3689
            $message .= get_lang('DateSent')." : ".api_format_date(api_get_local_time())."\n";
3690
            $url = api_get_path(WEB_CODE_PATH)."work/work.php?cidReq=".$courseInfo['code']."&id_session=".$session_id."&id=".$workData['id'];
3691
            $message .= get_lang('WorkName')." : ".$workData['title']."\n\n".'<a href="'.$url.'">'.get_lang('DownloadLink')."</a>\n";
3692
            //$message .= $url;
3693
            MessageManager::send_message_simple($to_user_id, $subject, $message);
3694
            api_mail_html(
3695
                api_get_person_name(
3696
                    $user_info['firstname'].' '.$user_info['lastname'],
3697
                    null,
3698
                    PERSON_NAME_EMAIL_ADDRESS
3699
                ),
3700
                $user_info['email'],
3701
                $subject,
3702
                $message,
3703
                $senderName,
3704
                $senderEmail
3705
            );
3706
        }
3707
    }
3708
}
3709
3710
/**
3711
 * @param array $workInfo
3712
 * @param array $values
3713
 * @param array $courseInfo
3714
 * @param int $sessionId
3715
 * @param int $groupId
3716
 * @param int $userId
3717
 * @param array $file
3718
 *
3719
 * @return null|string
3720
 */
3721
function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, $userId, $file = [])
3722
{
3723
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
3724
3725
    $courseId = $courseInfo['real_id'];
3726
    $groupId = intval($groupId);
3727
    $sessionId = intval($sessionId);
3728
    $userId = intval($userId);
3729
3730
    $title = $values['title'];
3731
    $description = $values['description'];
3732
    $contains_file = isset($values['contains_file']) && !empty($values['contains_file']) ? intval($values['contains_file']): 0;
3733
3734
    $saveWork = true;
3735
    $message = null;
3736
    $filename = null;
3737
    $url = null;
3738
    $filesize = null;
3739
3740
    if ($values['contains_file']) {
3741
        $result = uploadWork($workInfo, $courseInfo, false, [], $file);
3742
        if (isset($result['error'])) {
3743
            $message = $result['error'];
3744
            $saveWork = false;
3745
        }
3746
        $filename = isset($result['filename']) ? $result['filename'] : null;
3747
        if (empty($title)) {
3748
            $title = isset($result['title']) && !empty($result['title']) ? $result['title'] : get_lang('Untitled');
3749
        }
3750
3751
        $filesize = isset($result['filesize']) ? $result['filesize'] : null;
3752
        $url = $result['url'];
3753
    }
3754
3755
    if (empty($title)) {
3756
        $title = get_lang('Untitled');
3757
    }
3758
3759
    $workData = [];
3760
3761
    if ($saveWork) {
3762
        $active = '1';
3763
        $params = [
3764
            'c_id' => $courseId,
3765
            'url' => $url,
3766
            'filetype' => 'file',
3767
            'title' => $title,
3768
            'description' => $description,
3769
            'contains_file' => $contains_file,
3770
            'active' => $active,
3771
            'accepted' => '1',
3772
            'qualificator_id' => 0,
3773
            'document_id' => 0,
3774
            'weight' => 0,
3775
            'allow_text_assignment' => 0,
3776
            'post_group_id' => $groupId,
3777
            'sent_date' => api_get_utc_datetime(),
3778
            'parent_id' => $workInfo['id'],
3779
            'session_id' => $sessionId,
3780
            'user_id' => $userId,
3781
            'has_properties' => 0,
3782
            'qualification' => 0
3783
3784
            //'filesize' => $filesize
3785
        ];
3786
        $workId = Database::insert($work_table, $params);
3787
3788
        if ($workId) {
3789
            $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId ";
3790
            Database::query($sql);
3791
3792
            if (array_key_exists('filename', $workInfo) && !empty($filename)) {
3793
                $filename = Database::escape_string($filename);
3794
                $sql = "UPDATE $work_table SET
3795
                            filename = '$filename'
3796
                        WHERE iid = $workId";
3797
                Database::query($sql);
3798
            }
3799
3800
            if (array_key_exists('document_id', $workInfo)) {
3801
                $documentId = isset($values['document_id']) ? intval($values['document_id']) : 0;
3802
                $sql = "UPDATE $work_table SET
3803
                            document_id = '$documentId'
3804
                        WHERE iid = $workId";
3805
                Database::query($sql);
3806
            }
3807
            api_item_property_update(
3808
                $courseInfo,
3809
                'work',
3810
                $workId,
3811
                'DocumentAdded',
3812
                $userId,
3813
                $groupId
3814
            );
3815
            sendAlertToUsers($workId, $courseInfo, $sessionId);
3816
            Event::event_upload($workId);
3817
            $workData = get_work_data_by_id($workId);
3818
            Display::addFlash(Display::return_message(get_lang('DocAdd')));
3819
        }
3820
    } else {
3821
        Display::addFlash(Display::return_message(get_lang('IsNotPosibleSaveTheDocument'), 'error'));
3822
    }
3823
3824
    return $workData;
3825
}
3826
3827
/**
3828
 * Creates a new task (directory) in the assignment tool
3829
 * @param array $params
0 ignored issues
show
Bug introduced by
There is no parameter named $params. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
3830
 * @param int $user_id
3831
 * @param array $courseInfo
3832
 * @param int $group_id
3833
 * @param int $session_id
3834
 * @return bool|int
3835
 * @note $params can have the following elements, but should at least have the 2 first ones: (
3836
 *       'new_dir' => 'some-name',
3837
 *       'description' => 'some-desc',
3838
 *       'qualification' => 20 (e.g. 20),
3839
 *       'weight' => 50 (percentage) to add to gradebook (e.g. 50),
3840
 *       'allow_text_assignment' => 0/1/2,
3841
 * @todo Rename createAssignment or createWork, or something like that
3842
 */
3843
function addDir($formValues, $user_id, $courseInfo, $group_id, $session_id)
3844
{
3845
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3846
3847
    $user_id = intval($user_id);
3848
    $group_id = intval($group_id);
3849
    $session_id = intval($session_id);
3850
3851
    $base_work_dir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work';
3852
    $course_id = $courseInfo['real_id'];
3853
3854
    $directory = api_replace_dangerous_char($formValues['new_dir']);
3855
    $directory = disable_dangerous_file($directory);
3856
    $created_dir = create_unexisting_work_directory($base_work_dir, $directory);
3857
3858
    if (!empty($created_dir)) {
3859
        $dirName = '/'.$created_dir;
3860
        $today = api_get_utc_datetime();
3861
3862
        $params = [
3863
            'c_id' => $course_id,
3864
            'url' => $dirName,
3865
            'title' => $formValues['new_dir'],
3866
            'description' => $formValues['description'],
3867
            'author' => '',
3868
            'active' => '1',
3869
            'accepted' => '1',
3870
            'filetype' => 'folder',
3871
            'post_group_id' => $group_id,
3872
            'sent_date' => $today,
3873
            'qualification' => $formValues['qualification'] != '' ? $formValues['qualification'] : 0,
3874
            'parent_id' => 0,
3875
            'qualificator_id' => 0,
3876
            'weight' => !empty($formValues['weight']) ? $formValues['weight'] : 0,
3877
            'session_id' => $session_id,
3878
            'allow_text_assignment' => $formValues['allow_text_assignment'],
3879
            'contains_file' => 0,
3880
            'user_id' => $user_id,
3881
            'has_properties' => 0,
3882
            'document_id' => 0
3883
        ];
3884
        $id = Database::insert($work_table, $params);
3885
3886
        if ($id) {
3887
3888
            $sql = "UPDATE $work_table SET id = iid WHERE iid = $id";
3889
            Database::query($sql);
3890
3891
            // Folder created
3892
            api_item_property_update(
3893
                $courseInfo,
3894
                'work',
3895
                $id,
3896
                'DirectoryCreated',
3897
                $user_id,
3898
                $group_id
3899
            );
3900
3901
            updatePublicationAssignment($id, $formValues, $courseInfo, $group_id);
3902
3903
            if (api_get_course_setting('email_alert_students_on_new_homework') == 1) {
3904
                send_email_on_homework_creation($course_id, $session_id, $id);
3905
            }
3906
3907
            return $id;
3908
        }
3909
    }
3910
    return false;
3911
}
3912
3913
/**
3914
 * @param int $workId
3915
 * @param array $courseInfo
3916
 * @return int
3917
 */
3918
function agendaExistsForWork($workId, $courseInfo)
3919
{
3920
    $workTable = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
3921
    $courseId = $courseInfo['real_id'];
3922
    $workId = intval($workId);
3923
3924
    $sql = "SELECT add_to_calendar FROM $workTable
3925
            WHERE c_id = $courseId AND publication_id = ".$workId;
3926
    $res = Database::query($sql);
3927
    if (Database::num_rows($res)) {
3928
        $row = Database::fetch_array($res, 'ASSOC');
3929
        if (!empty($row['add_to_calendar'])) {
3930
            return $row['add_to_calendar'];
3931
        }
3932
    }
3933
    return 0;
3934
}
3935
3936
/**
3937
 * Update work description, qualification, weight, allow_text_assignment
3938
 * @param int $workId
3939
 * @param array $params
3940
 * @param array $courseInfo
3941
 * @param int $sessionId
3942
 */
3943
function updateWork($workId, $params, $courseInfo, $sessionId = 0)
3944
{
3945
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3946
    $filteredParams = array(
3947
        'description' => $params['description'],
3948
        'qualification' => $params['qualification'],
3949
        'weight' => $params['weight'],
3950
        'allow_text_assignment' => $params['allow_text_assignment']
3951
    );
3952
3953
    Database::update(
3954
        $workTable,
3955
        $filteredParams,
3956
        array(
3957
            'id = ? AND c_id = ? AND session_id = ? ' => array(
3958
                $workId, $courseInfo['real_id'], $sessionId
3959
            )
3960
        )
3961
    );
3962
}
3963
3964
/**
3965
 * @param int $workId
3966
 * @param array $params
3967
 * @param array $courseInfo
3968
 * @param int $groupId
3969
 */
3970
function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
3971
{
3972
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
3973
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
3974
    $workId = intval($workId);
3975
    $time = api_get_utc_datetime();
3976
    $course_id = $courseInfo['real_id'];
3977
3978
    // Insert into agenda
3979
    $agendaId = 0;
3980
3981
    if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
3982
        require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
3983
3984
        // Setting today date
3985
        $date = $end_date = $time;
3986
3987
        if (isset($params['enableExpiryDate'])) {
3988
            $end_date = $params['expires_on'];
3989
            $date = $end_date;
3990
        }
3991
3992
        $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
3993
        $description = isset($params['description']) ? $params['description'] : '';
3994
        $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
3995
            .$params['new_dir'].'</a>'.$description;
3996
3997
        $agendaId = agendaExistsForWork($workId, $courseInfo);
3998
3999
        // Add/edit agenda
4000
        $agenda = new Agenda();
4001
        $agenda->set_course($courseInfo);
4002
        $agenda->type = 'course';
4003
4004
        if (empty($agendaId)) {
4005
            $agendaId = $agenda->addEvent(
4006
                $date,
4007
                $end_date,
4008
                'false',
4009
                $title,
4010
                $content,
4011
                array('GROUP:'.$groupId)
4012
            );
4013
        } else {
4014
            $agenda->editEvent(
4015
                $agendaId,
4016
                $end_date,
4017
                $end_date,
4018
                'false',
4019
                $title,
4020
                $content
4021
            );
4022
        }
4023
    }
4024
4025
    $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
4026
    $expiryDate = isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
4027
    $endDate = isset($params['enableEndDate']) && $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
4028
4029
    $data = get_work_assignment_by_id($workId, $course_id);
4030
4031
    if (!empty($expiryDate)) {
4032
        $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', ";
4033
    } else {
4034
        $expiryDateCondition = "expires_on = null, ";
4035
    }
4036
4037
    if (!empty($endDate)) {
4038
        $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', ";
4039
    } else {
4040
        $endOnCondition = "ends_on = null, ";
4041
    }
4042
4043
    if (empty($data)) {
4044
4045
        $sql = "INSERT INTO $table SET
4046
                c_id = $course_id ,
4047
                $expiryDateCondition
4048
                $endOnCondition
4049
                add_to_calendar = $agendaId,
4050
                enable_qualification = '$qualification',
4051
                publication_id = '$workId'";
4052
4053
        Database::query($sql);
4054
4055
        $my_last_id = Database::insert_id();
4056
        if ($my_last_id) {
4057
4058
            $sql = "UPDATE $table SET
4059
                        id = iid
4060
                    WHERE iid = $my_last_id";
4061
            Database::query($sql);
4062
4063
            $sql = "UPDATE $workTable SET
4064
                        has_properties  = $my_last_id,
4065
                        view_properties = 1
4066
                    WHERE c_id = $course_id AND id = $workId";
4067
            Database::query($sql);
4068
        }
4069
    } else {
4070
        $sql = "UPDATE $table SET
4071
                    $expiryDateCondition
4072
                    $endOnCondition
4073
                    add_to_calendar  = $agendaId,
4074
                    enable_qualification = '".$qualification."'
4075
                WHERE
4076
                    publication_id = $workId AND
4077
                    c_id = $course_id AND
4078
                    id = ".$data['id'];
4079
        Database::query($sql);
4080
    }
4081
4082
    if (!empty($params['category_id'])) {
4083
4084
        $link_info = GradebookUtils::is_resource_in_course_gradebook(
4085
            $courseInfo['code'],
4086
            LINK_STUDENTPUBLICATION,
4087
            $workId,
4088
            api_get_session_id()
4089
        );
4090
4091
        $linkId = null;
4092
        if (!empty($link_info)) {
4093
            $linkId = $link_info['id'];
4094
        }
4095
4096
        if (isset($params['make_calification']) &&
4097
            $params['make_calification'] == 1
4098
        ) {
4099
            if (empty($linkId)) {
4100
                GradebookUtils::add_resource_to_course_gradebook(
4101
                    $params['category_id'],
4102
                    $courseInfo['code'],
4103
                    LINK_STUDENTPUBLICATION,
4104
                    $workId,
4105
                    $params['new_dir'],
4106
                    (float)$params['weight'],
4107
                    (float)$params['qualification'],
4108
                    $params['description'],
4109
                    1,
4110
                    api_get_session_id()
4111
                );
4112
            } else {
4113
                GradebookUtils::update_resource_from_course_gradebook(
4114
                    $linkId,
4115
                    $courseInfo['code'],
4116
                    $params['weight']
4117
                );
4118
            }
4119
        } else {
4120
            // Delete everything of the gradebook for this $linkId
4121
            GradebookUtils::remove_resource_from_course_gradebook($linkId);
4122
        }
4123
    }
4124
}
4125
4126
/**
4127
 * Delete all work by student
4128
 * @param int $userId
4129
 * @param array $courseInfo
4130
 * @return array return deleted items
4131
 */
4132
function deleteAllWorkPerUser($userId, $courseInfo)
4133
{
4134
    $deletedItems = array();
4135
    $workPerUser = getWorkPerUser($userId);
4136
    if (!empty($workPerUser)) {
4137
        foreach ($workPerUser as $work) {
4138
            $work = $work['work'];
4139
            foreach ($work->user_results as $userResult) {
4140
                $result = deleteWorkItem($userResult['id'], $courseInfo);
4141
                if ($result) {
4142
                    $deletedItems[] = $userResult;
4143
                }
4144
            }
4145
        }
4146
    }
4147
    return $deletedItems;
4148
}
4149
4150
/**
4151
 * @param int $item_id
4152
 * @param array course info
4153
 * @return bool
4154
 */
4155
function deleteWorkItem($item_id, $courseInfo)
4156
{
4157
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
4158
    $TSTDPUBASG = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
4159
4160
    $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
4161
4162
    $is_allowed_to_edit = api_is_allowed_to_edit();
4163
    $file_deleted = false;
4164
    $item_id = intval($item_id);
4165
4166
    $is_author = user_is_author($item_id);
4167
    $work_data = get_work_data_by_id($item_id);
4168
    $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
4169
    $course_id = $courseInfo['real_id'];
4170
4171
    if (($is_allowed_to_edit && $locked == false) ||
4172
        (
4173
            $locked == false &&
4174
            $is_author &&
4175
            api_get_course_setting('student_delete_own_publication') == 1 &&
4176
            $work_data['qualificator_id'] == 0
4177
        )
4178
    ) {
4179
        // We found the current user is the author
4180
        $sql = "SELECT url, contains_file FROM $work_table
4181
                WHERE c_id = $course_id AND id = $item_id";
4182
        $result = Database::query($sql);
4183
        $row = Database::fetch_array($result);
4184
4185
        if (Database::num_rows($result) > 0) {
4186
            $sql = "UPDATE $work_table SET active = 2
4187
                    WHERE c_id = $course_id AND id = $item_id";
4188
            Database::query($sql);
4189
            $sql = "DELETE FROM $TSTDPUBASG
4190
                    WHERE c_id = $course_id AND publication_id = $item_id";
4191
            Database::query($sql);
4192
            plagiarismDeleteDoc($course_id, $item_id);     
4193
            api_item_property_update(
4194
                $courseInfo,
4195
                'work',
4196
                $item_id,
4197
                'DocumentDeleted',
4198
                api_get_user_id()
4199
            );
4200
            $work = $row['url'];
4201
4202
            if ($row['contains_file'] == 1) {
4203
                if (!empty($work)) {
4204
                    if (api_get_setting('permanently_remove_deleted_files') == 'true') {
4205
                        my_delete($currentCourseRepositorySys.'/'.$work);
4206
                        $file_deleted = true;
4207
                    } else {
4208
                        $extension = pathinfo($work, PATHINFO_EXTENSION);
4209
                        $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
4210
4211
                        if (file_exists($currentCourseRepositorySys.'/'.$work)) {
4212
                            rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
4213
                            $file_deleted = true;
4214
                        }
4215
                    }
4216
                }
4217
            } else {
4218
                $file_deleted = true;
4219
            }
4220
        }
4221
    }
4222
    return $file_deleted;
4223
}
4224
4225
/**
4226
 * @param FormValidator $form
4227
 * @param array $defaults
4228
 * @return FormValidator
4229
 */
4230
function getFormWork($form, $defaults = array())
4231
{
4232
    if (!empty($defaults)) {
4233
        if (isset($defaults['submit'])) {
4234
            unset($defaults['submit']);
4235
        }
4236
    }
4237
4238
    // Create the form that asks for the directory name
4239
    $form->addElement('text', 'new_dir', get_lang('AssignmentName'));
4240
    $form->addRule('new_dir', get_lang('ThisFieldIsRequired'), 'required');
4241
    $form->addHtmlEditor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
4242
    $form->addButtonAdvancedSettings('advanced_params', get_lang('AdvancedParameters'));
4243
4244
    if (!empty($defaults) && (isset($defaults['enableEndDate']) || isset($defaults['enableExpiryDate']))) {
4245
        $form->addElement('html', '<div id="advanced_params_options" style="display:block">');
4246
    } else {
4247
        $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
4248
    }
4249
4250
    // QualificationOfAssignment
4251
    $form->addElement('text', 'qualification', get_lang('QualificationNumeric'));
4252
4253
    if ((api_get_session_id() != 0 && Gradebook::is_active()) || api_get_session_id() == 0) {
4254
        $form->addElement(
4255
            'checkbox',
4256
            'make_calification',
4257
            null,
4258
            get_lang('MakeQualifiable'),
4259
            array(
4260
                'id' =>'make_calification_id',
4261
                'onclick' => "javascript: if(this.checked) { document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}"
4262
            )
4263
        );
4264
    } else {
4265
        // QualificationOfAssignment
4266
        $form->addElement('hidden', 'make_calification', false);
4267
    }
4268
4269
    if (!empty($defaults) && isset($defaults['category_id'])) {
4270
        $form->addElement('html', '<div id=\'option1\' style="display:block">');
4271
    } else {
4272
        $form->addElement('html', '<div id=\'option1\' style="display:none">');
4273
    }
4274
4275
    // Loading Gradebook select
4276
    GradebookUtils::load_gradebook_select_in_tool($form);
4277
4278
    $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
4279
    $form->addElement('html', '</div>');
4280
4281
    $form->addElement('checkbox', 'enableExpiryDate', null, get_lang('EnableExpiryDate'), 'id="expiry_date"');
4282
    if (isset($defaults['enableExpiryDate']) && $defaults['enableExpiryDate']) {
4283
        $form->addElement('html', '<div id="option2" style="display: block;">');
4284
    } else {
4285
        $form->addElement('html', '<div id="option2" style="display: none;">');
4286
    }
4287
4288
    $currentDate = substr(api_get_local_time(), 0, 10);
4289
4290 View Code Duplication
    if (!isset($defaults['expires_on'])) {
4291
        $date = substr($currentDate, 0, 10);
4292
        $defaults['expires_on'] = $date.' 23:59';
4293
    }
4294
4295 View Code Duplication
    if (!isset($defaults['ends_on'])) {
4296
        $date = substr($currentDate, 0, 10);
4297
        $defaults['ends_on'] = $date.' 23:59';
4298
    }
4299
4300
    $form->addElement('date_time_picker', 'expires_on', get_lang('ExpiresAt'));
4301
    $form->addElement('html', '</div>');
4302
4303
    $form->addElement('checkbox', 'enableEndDate', null, get_lang('EnableEndDate'), 'id="end_date"');
4304
4305
    if (isset($defaults['enableEndDate']) && $defaults['enableEndDate']) {
4306
        $form->addElement('html', '<div id="option3" style="display: block;">');
4307
    } else {
4308
        $form->addElement('html', '<div id="option3" style="display: none;">');
4309
    }
4310
4311
    $form->addElement('date_time_picker', 'ends_on', get_lang('EndsAt'));
4312
    $form->addElement('html', '</div>');
4313
4314
    $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
4315
    $form->addElement('select', 'allow_text_assignment', get_lang('DocumentType'), getUploadDocumentType());
4316
4317
    $form->addElement('html', '</div>');
4318
4319
    if (isset($defaults['enableExpiryDate']) && isset($defaults['enableEndDate'])) {
4320
        $form->addRule(array('expires_on', 'ends_on'), get_lang('DateExpiredNotBeLessDeadLine'), 'comparedate');
4321
    }
4322
    if (!empty($defaults)) {
4323
        $form->setDefaults($defaults);
4324
    }
4325
4326
    return $form;
4327
}
4328
4329
/**
4330
 * @return array
4331
 */
4332
function getUploadDocumentType()
4333
{
4334
    return array(
4335
        0 => get_lang('AllowFileOrText'),
4336
        1 => get_lang('AllowOnlyText'),
4337
        2 => get_lang('AllowOnlyFiles')
4338
    );
4339
}
4340
4341
/**
4342
 * @param array $courseInfo
4343
 * @param bool $showScore
4344
 * @param bool $studentDeleteOwnPublication
4345
 */
4346
function updateSettings($courseInfo, $showScore, $studentDeleteOwnPublication)
4347
{
4348
    $showScore = intval($showScore);
4349
    $courseId = api_get_course_int_id();
4350
    $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
4351
    $table_course_setting = Database :: get_course_table(TOOL_COURSE_SETTING);
4352
4353
    $query = "UPDATE ".$main_course_table." SET show_score = '".$showScore."'
4354
              WHERE id = $courseId";
4355
    Database::query($query);
4356
4357
    /**
4358
     * Course data are cached in session so we need to update both the database
4359
     * and the session data
4360
     */
4361
    $_course['show_score'] = $showScore;
4362
    Session::write('_course', $courseInfo);
4363
4364
    // changing the tool setting: is a student allowed to delete his/her own document
4365
4366
    // counting the number of occurrences of this setting (if 0 => add, if 1 => update)
4367
    $query = "SELECT * FROM " . $table_course_setting . "
4368
              WHERE c_id = $courseId AND variable = 'student_delete_own_publication'";
4369
4370
    $result = Database::query($query);
4371
    $number_of_setting = Database::num_rows($result);
4372
4373
    if ($number_of_setting == 1) {
4374
        $query = "UPDATE " . $table_course_setting . " SET
4375
                  value='" . Database::escape_string($studentDeleteOwnPublication) . "'
4376
                  WHERE variable = 'student_delete_own_publication' AND c_id = $courseId";
4377
        Database::query($query);
4378
    } else {
4379
        $params = [
4380
            'c_id' => $courseId,
4381
            'variable' => 'student_delete_own_publication',
4382
            'value' => $studentDeleteOwnPublication,
4383
            'category' => 'work'
4384
        ];
4385
        Database::insert($table_course_setting, $params);
4386
    }
4387
}
4388
4389
/**
4390
 * @param int $item_id
4391
 * @param array $course_info
4392
 */
4393
function makeVisible($item_id, $course_info)
4394
{
4395
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
4396
    $course_id = $course_info['real_id'];
4397
    $item_id = intval($item_id);
4398
4399
    $sql = "UPDATE $work_table SET accepted = 1
4400
            WHERE c_id = $course_id AND id = $item_id";
4401
    Database::query($sql);
4402
    api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
4403
}
4404
4405
/**
4406
 * @param int $item_id
4407
 * @param array $course_info
4408
 */
4409 View Code Duplication
function makeInvisible($item_id, $course_info)
4410
{
4411
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
4412
    $item_id = intval($item_id);
4413
    $course_id = $course_info['real_id'];
4414
    $sql = "UPDATE  " . $work_table . "
4415
            SET accepted = 0
4416
            WHERE c_id = $course_id AND id = '" . $item_id . "'";
4417
    Database::query($sql);
4418
    api_item_property_update(
4419
        $course_info,
4420
        'work',
4421
        $item_id,
4422
        'invisible',
4423
        api_get_user_id()
4424
    );
4425
}
4426
4427
/**
4428
 * @param int $item_id
4429
 * @param string $path
4430
 * @param array $courseInfo
4431
 * @param int $groupId
4432
 * @param int $sessionId
4433
 * @return string
4434
 */
4435
function generateMoveForm($item_id, $path, $courseInfo, $groupId, $sessionId)
4436
{
4437
    $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
4438
    $courseId = $courseInfo['real_id'];
4439
    $folders = array();
4440
    $session_id = intval($sessionId);
4441
    $groupId = intval($groupId);
4442
    $sessionCondition = empty($sessionId) ? " AND (session_id = 0 OR session_id IS NULL) " : " AND session_id='".$session_id."'";
4443
    $sql = "SELECT id, url, title
4444
            FROM $work_table
4445
            WHERE
4446
                c_id = $courseId AND
4447
                active IN (0, 1) AND
4448
                url LIKE '/%' AND
4449
                post_group_id = $groupId
4450
                $sessionCondition";
4451
    $res = Database::query($sql);
4452
    while ($folder = Database::fetch_array($res)) {
4453
        $title = empty($folder['title']) ? basename($folder['url']) : $folder['title'];
4454
        $folders[$folder['id']] = $title;
4455
    }
4456
    return build_work_move_to_selector($folders, $path, $item_id);
4457
}
4458
4459
/**
4460
 * @param int $workId
4461
 * @return string
4462
 */
4463
function showStudentList($workId)
4464
{
4465
    $columnModel = array(
4466
        array(
4467
            'name' => 'student',
4468
            'index' => 'student',
4469
            'width' => '350px',
4470
            'align' => 'left',
4471
            'sortable' => 'false',
4472
        ),
4473
        array(
4474
            'name' => 'works',
4475
            'index' => 'works',
4476
            'align' => 'center',
4477
            'sortable' => 'false',
4478
        ),
4479
    );
4480
    $token = null;
4481
4482
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student_list_overview&work_id='.$workId.'&'.api_get_cidreq();
4483
4484
    $columns = array(
4485
        get_lang('Students'),
4486
        get_lang('Works')
4487
    );
4488
4489
    $order = api_is_western_name_order() ? 'firstname' : 'lastname';
4490
    $params = array(
4491
        'autowidth' => 'true',
4492
        'height' => 'auto',
4493
        'rowNum' => 5,
4494
        'sortname' => $order,
4495
        'sortorder' => 'asc'
4496
    );
4497
4498
    $html = '<script>
4499
    $(function() {
4500
        '.Display::grid_js('studentList', $url, $columns, $columnModel, $params, array(), null, true).'
4501
        $("#workList").jqGrid(
4502
            "navGrid",
4503
            "#studentList_pager",
4504
            { edit: false, add: false, del: false },
4505
            { height:280, reloadAfterSubmit:false }, // edit options
4506
            { height:280, reloadAfterSubmit:false }, // add options
4507
            { width:500 } // search options
4508
        );
4509
    });
4510
    </script>';
4511
    $html .= Display::grid_html('studentList');
4512
    return $html;
4513
}
4514
4515
/**
4516
 * @param string $courseCode
4517
 * @param int $sessionId
4518
 * @param int $groupId
4519
 * @param int $start
4520
 * @param int $limit
4521
 * @param string $sidx
4522
 * @param string $sord
4523
 * @param $getCount
4524
 * @return array|int
4525
 */
4526
function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
4527
{
4528
    if (!empty($groupId)) {
4529
        $userList = GroupManager::get_users(
4530
            $groupId,
4531
            false,
4532
            $start,
4533
            $limit,
4534
            $getCount,
4535
            null,
4536
            $sidx,
4537
            $sord
4538
        );
4539
    } else {
4540
        $limitString = null;
4541 View Code Duplication
        if (!empty($start) && !empty($limit)) {
4542
            $start = intval($start);
4543
            $limit = intval($limit);
4544
            $limitString = " LIMIT $start, $limit";
4545
        }
4546
4547
        $orderBy = null;
4548
4549
        if (!empty($sidx) && !empty($sord)) {
4550
            if (in_array($sidx, array('firstname', 'lastname'))) {
4551
                $orderBy = "ORDER BY $sidx $sord";
4552
            }
4553
        }
4554
4555
        if (empty($sessionId)) {
4556
            $userList = CourseManager::get_user_list_from_course_code(
4557
                $courseCode,
4558
                $sessionId,
4559
                $limitString,
4560
                $orderBy ,
4561
                STUDENT,
4562
                $getCount
4563
            );
4564
        } else {
4565
            $userList = CourseManager::get_user_list_from_course_code(
4566
                $courseCode,
4567
                $sessionId,
4568
                $limitString,
4569
                $orderBy,
4570
                0,
4571
                $getCount
4572
            );
4573
        }
4574
4575
        if ($getCount == false) {
4576
            $userList = array_keys($userList);
4577
        }
4578
    }
4579
    return $userList;
4580
}
4581
4582
/**
4583
 * @param int $workId
4584
 * @param string $courseCode
4585
 * @param int $sessionId
4586
 * @param int $groupId
4587
 * @param int $start
4588
 * @param int $limit
4589
 * @param int $sidx
4590
 * @param string $sord
4591
 * @param bool $getCount
4592
 * @return array|int
4593
 */
4594
function getWorkUserListData(
4595
    $workId,
4596
    $courseCode,
4597
    $sessionId,
4598
    $groupId,
4599
    $start,
4600
    $limit,
4601
    $sidx,
4602
    $sord,
4603
    $getCount = false
4604
) {
4605
    $my_folder_data = get_work_data_by_id($workId);
4606
    $workParents = array();
4607
    if (empty($my_folder_data)) {
4608
        $workParents = getWorkList($workId, $my_folder_data, null);
4609
    }
4610
4611
    $workIdList = array();
4612
    if (!empty($workParents)) {
4613
        foreach ($workParents as $work) {
4614
            $workIdList[] = $work->id;
4615
        }
4616
    }
4617
4618
    $courseInfo = api_get_course_info($courseCode);
4619
4620
    $userList = getWorkUserList(
4621
        $courseCode,
4622
        $sessionId,
4623
        $groupId,
4624
        $start,
4625
        $limit,
4626
        $sidx,
4627
        $sord,
4628
        $getCount
4629
    );
4630
4631
    if ($getCount) {
4632
        return $userList;
4633
    }
4634
    $results = array();
4635
    if (!empty($userList)) {
4636
        foreach ($userList as $userId) {
0 ignored issues
show
Bug introduced by
The expression $userList of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4637
            $user = api_get_user_info($userId);
4638
            $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
4639
            $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
4640
            $userWorks = 0;
4641
            if (!empty($workIdList)) {
4642
                $userWorks = getUniqueStudentAttempts(
4643
                    $workIdList,
4644
                    $groupId,
4645
                    $courseInfo['real_id'],
4646
                    $sessionId,
4647
                    $user['user_id']
4648
                );
4649
            }
4650
            $works = $userWorks." / ".count($workParents);
4651
            $results[] = array(
4652
                'student' => $url,
4653
                'works' => Display::url($works, $link),
4654
            );
4655
        }
4656
    }
4657
    return $results;
4658
}
4659
4660
/**
4661
 * @param int $id
4662
 * @param array $course_info
4663
 * @param bool $isCorrection
4664
 *
4665
 * @return bool
4666
 */
4667
function downloadFile($id, $course_info, $isCorrection)
4668
{
4669
    return getFile($id, $course_info, true, $isCorrection);
4670
}
4671
4672
/**
4673
 * @param int $id
4674
 * @param array $course_info
4675
 * @param bool $download
4676
 * @param bool $isCorrection
4677
 *
4678
 * @return bool
4679
 */
4680
function getFile($id, $course_info, $download = true, $isCorrection = false)
4681
{
4682
    $file = getFileContents($id, $course_info, 0, $isCorrection);
4683
    if (!empty($file) && is_array($file)) {
4684
        return DocumentManager::file_send_for_download(
4685
            $file['path'],
4686
            $download,
4687
            $file['title']
4688
        );
4689
    }
4690
4691
    return false;
4692
}
4693
4694
4695
/**
4696
 * Get the file contents for an assigment
4697
 * @param int $id
4698
 * @param array $course_info
4699
 * @param int Session ID
4700
 * @param $correction
4701
 *
4702
 * @return array|bool
4703
 */
4704
function getFileContents($id, $course_info, $sessionId = 0, $correction = false)
4705
{
4706
    $id = intval($id);
4707
    if (empty($course_info) || empty($id)) {
4708
        return false;
4709
    }
4710
    if (empty($sessionId)) {
4711
        $sessionId = api_get_session_id();
4712
    }
4713
4714
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
4715
4716
    if (!empty($course_info['real_id'])) {
4717
        $sql = 'SELECT *
4718
                FROM '.$table.'
4719
                WHERE c_id = '.$course_info['real_id'].' AND id = "'.$id.'"';
4720
        $result = Database::query($sql);
4721
        if ($result && Database::num_rows($result)) {
4722
            $row = Database::fetch_array($result, 'ASSOC');
4723
4724
            if ($correction) {
4725
                $row['url'] = $row['url_correction'];
4726
            }
4727
4728
            if (empty($row['url'])) {
4729
                return false;
4730
            }
4731
4732
            $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
4733
4734
            $item_info = api_get_item_property_info(
4735
                api_get_course_int_id(),
4736
                'work',
4737
                $row['id'],
4738
                $sessionId
4739
            );
4740
4741
            allowOnlySubscribedUser(
4742
                api_get_user_id(),
4743
                $row['parent_id'],
4744
                $course_info['real_id']
4745
            );
4746
4747
            if (empty($item_info)) {
4748
                api_not_allowed();
4749
            }
4750
4751
            /*
4752
            field show_score in table course :
4753
                0 =>    New documents are visible for all users
4754
                1 =>    New documents are only visible for the teacher(s)
4755
            field visibility in table item_property :
4756
                0 => eye closed, invisible for all students
4757
                1 => eye open
4758
            field accepted in table c_student_publication :
4759
                0 => eye closed, invisible for all students
4760
                1 => eye open
4761
            ( We should have visibility == accepted, otherwise there is an
4762
            inconsistency in the Database)
4763
            field value in table c_course_setting :
4764
                0 => Allow learners to delete their own publications = NO
4765
                1 => Allow learners to delete their own publications = YES
4766
4767
            +------------------+-------------------------+------------------------+
4768
            |Can download work?| doc visible for all = 0 | doc visible for all = 1|
4769
            +------------------+-------------------------+------------------------+
4770
            |  visibility = 0  | editor only             | editor only            |
4771
            |                  |                         |                        |
4772
            +------------------+-------------------------+------------------------+
4773
            |  visibility = 1  | editor                  | editor                 |
4774
            |                  | + owner of the work     | + any student          |
4775
            +------------------+-------------------------+------------------------+
4776
            (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
4777
            */
4778
4779
            $work_is_visible = $item_info['visibility'] == 1 && $row['accepted'] == 1;
4780
            $doc_visible_for_all = ($course_info['show_score'] == 1);
4781
4782
            $is_editor = api_is_allowed_to_edit(true, true, true);
4783
            $student_is_owner_of_work = user_is_author($row['id'], $row['user_id']);
4784
4785
            if ($is_editor ||
4786
                ($student_is_owner_of_work) ||
4787
                ($doc_visible_for_all && $work_is_visible)
4788
            ) {
4789
                $title = $row['title'];
4790
                if ($correction) {
4791
                    $title = $row['title_correction'];
4792
                }
4793
                if (array_key_exists('filename', $row) && !empty($row['filename'])) {
4794
                    $title = $row['filename'];
4795
                }
4796
4797
                $title = str_replace(' ', '_', $title);
4798
                Event::event_download($title);
4799
                if (Security::check_abs_path(
4800
                    $full_file_name,
4801
                    api_get_path(SYS_COURSE_PATH).api_get_course_path().'/')
4802
                ) {
4803
                    return array(
4804
                        'path' => $full_file_name,
4805
                        'title' => $title,
4806
                        'title_correction' => $row['title_correction']
4807
                    );
4808
                }
4809
            }
4810
        }
4811
    }
4812
4813
    return false;
4814
}
4815
4816
/**
4817
 * @param int $userId
4818
 * @param array $courseInfo
4819
 * @param string $format
4820
 * @return bool
4821
 */
4822
function exportAllWork($userId, $courseInfo, $format = 'pdf')
4823
{
4824
    $userInfo = api_get_user_info($userId);
4825
    if (empty($userInfo) || empty($courseInfo)) {
4826
        return false;
4827
    }
4828
4829
    $workPerUser = getWorkPerUser($userId);
4830
4831
    switch ($format) {
4832
        case 'pdf':
4833
            if (!empty($workPerUser)) {
4834
                $pdf = new PDF();
4835
4836
                $content = null;
4837
                foreach ($workPerUser as $work) {
4838
                    $work = $work['work'];
4839
                    foreach ($work->user_results as $userResult) {
4840
                        //var_dump($userResult);exit;
4841
                        $content .= $userResult['title'];
4842
                        // No need to use api_get_local_time()
4843
                        $content .= $userResult['sent_date'];
4844
                        $content .= $userResult['qualification'];
4845
                        $content .= $userResult['description'];
4846
                        //$content .= getWorkComments($userResult);
4847
                    }
4848
                }
4849
4850
                if (!empty($content)) {
4851
                    $pdf->content_to_pdf(
4852
                        $content,
4853
                        null,
4854
                        api_replace_dangerous_char($userInfo['complete_name']),
4855
                        $courseInfo['code']
4856
                    );
4857
                }
4858
            }
4859
            break;
4860
    }
4861
}
4862
4863
/**
4864
 * @param int $workId
4865
 * @param array $courseInfo
4866
 * @param int $sessionId
4867
 * @param string $format
4868
 * @return bool
4869
 */
4870
function exportAllStudentWorkFromPublication(
4871
    $workId,
4872
    $courseInfo,
4873
    $sessionId,
4874
    $format = 'pdf'
4875
) {
4876
    if (empty($courseInfo)) {
4877
        return false;
4878
    }
4879
4880
    $workData = get_work_data_by_id($workId);
4881
4882
    if (empty($workData)) {
4883
        return false;
4884
    }
4885
4886
    $assignment = get_work_assignment_by_id($workId);
4887
4888
    $courseCode = $courseInfo['code'];
4889
    $header = get_lang('Course').': '.$courseInfo['title'];
4890
    $teachers = CourseManager::get_teacher_list_from_course_code_to_string(
4891
        $courseCode
4892
    );
4893
4894
    if (!empty($sessionId)) {
4895
        $sessionInfo = api_get_session_info($sessionId);
4896
        if (!empty($sessionInfo)) {
4897
            $header .= ' - ' . $sessionInfo['name'];
4898
            $header .= '<br />' . $sessionInfo['description'];
4899
            $teachers = SessionManager::getCoachesByCourseSessionToString(
4900
                $sessionId,
4901
                $courseInfo['real_id']
4902
            );
4903
        }
4904
    }
4905
4906
    $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
4907
    $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
4908
    $header .= '<br />'.get_lang('WorkName').': '.$workData['title'].'<br />';
4909
4910
    $content = null;
4911
    $expiresOn = null;
4912
4913
    if (!empty($assignment) && isset($assignment['expires_on'])) {
4914
        $content .= '<br /><strong>' . get_lang('ExpirationDate') . '</strong>: ' . api_get_local_time($assignment['expires_on']);
4915
        $expiresOn = api_get_local_time($assignment['expires_on']);
4916
    }
4917
4918
    if (!empty($workData['description'])) {
4919
        $content .= '<br /><strong>' . get_lang('Description') . '</strong>: ' . $workData['description'];
4920
    }
4921
4922
    $workList = get_work_user_list(null, null, null, null, $workId);
4923
4924
    switch ($format) {
4925
        case 'pdf':
4926
            if (!empty($workList)) {
4927
4928
                $table = new HTML_Table(array('class' => 'data_table'));
4929
                $headers = array(
4930
                    get_lang('Name'),
4931
                    get_lang('User'),
4932
                    get_lang('HandOutDateLimit'),
4933
                    get_lang('SentDate'),
4934
                    get_lang('FileName'),
4935
                    get_lang('Score'),
4936
                    get_lang('Feedback')
4937
                );
4938
4939
                $column = 0;
4940
                foreach($headers as $header) {
4941
                    $table->setHeaderContents(0, $column, $header);
4942
                    $column++;
4943
                }
4944
4945
                $row = 1;
4946
4947
                //$pdf->set_custom_header($header);
4948
                foreach ($workList as $work) {
4949
                    $content .= '<hr />';
4950
                    // getWorkComments need c_id
4951
                    $work['c_id'] = $courseInfo['real_id'];
4952
4953
                    //$content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
4954
                    $score = null;
4955
                    if (!empty($work['qualification_only'])) {
4956
                        $score = $work['qualification_only'];
4957
                    }
4958
                    //$content .= get_lang('Description').': '.$work['description'].'<br />';
4959
                    $comments = getWorkComments($work);
4960
4961
                    $feedback = null;
4962
                    if (!empty($comments)) {
4963
                        $content .= '<h4>'.get_lang('Feedback').': </h4>';
4964
                        foreach ($comments as $comment) {
4965
                            $feedback .= get_lang('User').': '.api_get_person_name(
4966
                                    $comment['firstname'],
4967
                                    $comment['lastname']
4968
                                ).'<br />';
4969
                            $feedback .= $comment['comment'].'<br />';
4970
                        }
4971
                    }
4972
4973
                    $table->setCellContents($row, 0, strip_tags($workData['title']));
4974
                    $table->setCellContents($row, 1, api_get_person_name(strip_tags($work['firstname']), strip_tags($work['lastname'])));
4975
                    $table->setCellContents($row, 2, $expiresOn);
4976
                    $table->setCellContents($row, 3, api_get_local_time($work['sent_date_from_db']));
4977
                    $table->setCellContents($row, 4, strip_tags($work['title']));
4978
                    $table->setCellContents($row, 5, $score);
4979
                    $table->setCellContents($row, 6, $feedback);
4980
4981
                    $row++;
4982
                }
4983
4984
                $content = $table->toHtml();
4985
4986
                if (!empty($content)) {
4987
                    $params = array(
4988
                        'filename' => $workData['title'] . '_' . api_get_local_time(),
4989
                        'pdf_title' => api_replace_dangerous_char($workData['title']),
4990
                        'course_code' => $courseInfo['code'],
4991
                        'add_signatures' => false
4992
                    );
4993
                    $pdf = new PDF('A4', null, $params);
4994
                    $pdf->html_to_pdf_with_template($content);
4995
                }
4996
                exit;
4997
            }
4998
            break;
4999
    }
5000
}
5001
5002
/**
5003
 * Downloads all user files per user
5004
 * @param int $userId
5005
 * @param array $courseInfo
5006
 * @return bool
5007
 */
5008
function downloadAllFilesPerUser($userId, $courseInfo)
5009
{
5010
    $userInfo = api_get_user_info($userId);
5011
5012
    if (empty($userInfo) || empty($courseInfo)) {
5013
        return false;
5014
    }
5015
5016
    $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
5017
    $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/';
5018
5019
    $zip  = new PclZip($tempZipFile);
5020
5021
    $workPerUser = getWorkPerUser($userId);
5022
5023
    if (!empty($workPerUser)) {
5024
        $files = array();
5025
        foreach ($workPerUser as $work) {
5026
            $work = $work['work'];
5027
            foreach ($work->user_results as $userResult) {
5028
                if (empty($userResult['url']) || empty($userResult['contains_file'])) {
5029
                    continue;
5030
                }
5031
                $data = getFileContents($userResult['id'], $courseInfo);
5032
                if (!empty($data) && isset($data['path'])) {
5033
                    $files[basename($data['path'])] = array(
5034
                        'title' => $data['title'],
5035
                        'path' => $data['path']
5036
                    );
5037
                }
5038
            }
5039
        }
5040
5041
        if (!empty($files)) {
5042
            Session::write('files', $files);
5043
            foreach ($files as $data) {
5044
                $zip->add(
5045
                    $data['path'],
5046
                    PCLZIP_OPT_REMOVE_PATH,
5047
                    $coursePath,
5048
                    PCLZIP_CB_PRE_ADD,
5049
                    'preAddAllWorkStudentCallback'
5050
                );
5051
            }
5052
        }
5053
5054
        // Start download of created file
5055
        $name = basename(api_replace_dangerous_char($userInfo['complete_name'])).'.zip';
5056
        Event::event_download($name.'.zip (folder)');
5057 View Code Duplication
        if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
5058
            DocumentManager::file_send_for_download($tempZipFile, true, $name);
5059
            @unlink($tempZipFile);
5060
            exit;
5061
        }
5062
    }
5063
    exit;
5064
}
5065
5066
/**
5067
 * @param $p_event
5068
 * @param array $p_header
5069
 * @return int
5070
 */
5071 View Code Duplication
function preAddAllWorkStudentCallback($p_event, &$p_header)
5072
{
5073
    $files = Session::read('files');
5074
    if (isset($files[basename($p_header['stored_filename'])])) {
5075
        $p_header['stored_filename'] = $files[basename($p_header['stored_filename'])]['title'];
5076
        return 1;
5077
    }
5078
    return 0;
5079
}
5080
5081
/**
5082
 * Get all work created by a user
5083
 * @param int $user_id
5084
 * @param int $courseId
5085
 * @param int $sessionId
5086
 * @return array
5087
 */
5088
function getWorkCreatedByUser($user_id, $courseId, $sessionId)
5089
{
5090
    $items = api_get_item_property_list_by_tool_by_user(
5091
        $user_id,
5092
        'work',
5093
        $courseId,
5094
        $sessionId
5095
    );
5096
5097
    $forumList = array();
5098 View Code Duplication
    if (!empty($items)) {
5099
        foreach ($items as $forum) {
5100
            $item = get_work_data_by_id(
5101
                $forum['ref'],
5102
                $courseId,
5103
                $sessionId
5104
            );
5105
5106
            $forumList[] = array(
5107
                $item['title'],
5108
                api_get_local_time($forum['insert_date']),
5109
                api_get_local_time($forum['lastedit_date'])
5110
            );
5111
        }
5112
    }
5113
5114
    return $forumList;
5115
}
5116
5117
/**
5118
 * @param array $courseInfo
5119
 * @param int $workId
5120
 * @return bool
5121
 */
5122
function protectWork($courseInfo, $workId)
5123
{
5124
    $userId = api_get_user_id();
5125
    $groupId = api_get_group_id();
5126
    $sessionId = api_get_session_id();
5127
    $workData = get_work_data_by_id($workId);
5128
5129
    if (empty($workData) || empty($courseInfo)) {
5130
        api_not_allowed(true);
5131
    }
5132
5133
    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
5134
        return true;
5135
    }
5136
5137
    $workId = $workData['id'];
5138
5139
    if ($workData['active'] != 1) {
5140
        api_not_allowed(true);
5141
    }
5142
5143
    $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
5144
5145
    if ($visibility != 1) {
5146
        api_not_allowed(true);
5147
    }
5148
5149
    allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
5150
5151
    if (!empty($groupId)) {
5152
        $showWork = GroupManager::user_has_access(
5153
            $userId,
5154
            $groupId,
5155
            GroupManager::GROUP_TOOL_WORK
5156
        );
5157
        if (!$showWork) {
5158
            api_not_allowed(true);
5159
        }
5160
    }
5161
}
5162
/*
5163
 * fonction for confirm the activation of plagiarism tool
5164
 * @return Bool
5165
 */
5166
function plagiarismActive()
5167
{
5168
    return (api_is_allowed_to_edit(false, true) && api_get_setting('plagiarism_use_chx') != 'false');
5169
}
5170
5171
/*
5172
 * @return string
5173
 */
5174
function plagiarismTool()
5175
{
5176
    return TOOL_COMPILATIO; 
5177
}
5178
/*
5179
 * function for delete a document of the compilatio table
5180
 */
5181
function compilatioDeleteDoc($courseId, $itemId)
5182
{
5183
    $plagiarism_table   = Database :: get_course_table(TABLE_COMPILATIO);
5184
    $queryString4   = "DELETE FROM "
5185
        . $plagiarism_table
5186
        . " WHERE c_id = "
5187
        . $courseId
5188
        . " AND id_doc= "
5189
        . $itemId;
5190
    Database::query($queryString4);
5191
}
5192
/*
5193
 * function for delete a document of the compilatio table if plagiarismTool is Compilatio
5194
 */
5195
function plagiarismDeleteDoc($courseId, $itemId)
5196
{
5197
    if (plagiarismActive()) {
5198
        if (plagiarismTool() == TOOL_COMPILATIO) {
5199
            compilatioDeleteDoc($courseId, $itemId);
5200
        }
5201
    }
5202
}
5203
/*
5204
 * function for convert the id work into  an int
5205
 */
5206
function isWorkFolder($workId)
5207
{
5208
    return intval($workId);
5209
}
5210