Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

getWorkListTeacher()   C

Complexity

Conditions 14
Paths 128

Size

Total Lines 129
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 14
eloc 73
c 3
b 0
f 0
nc 128
nop 7
dl 0
loc 129
rs 5.4157

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CStudentPublication;
6
use ChamiloSession as Session;
7
use Doctrine\DBAL\Driver\Statement;
8
9
/**
10
 *  @author Thomas, Hugues, Christophe - original version
11
 *  @author Patrick Cool <[email protected]>, Ghent University -
12
 * ability for course admins to specify wether uploaded documents are visible or invisible by default.
13
 *  @author Roan Embrechts, code refactoring and virtual course support
14
 *  @author Frederic Vauthier, directories management
15
 *  @author Julio Montoya <[email protected]> BeezNest 2011 LOTS of bug fixes
16
 *
17
 *  @todo   this lib should be convert in a static class and moved to main/inc/lib
18
 */
19
20
/**
21
 * Displays action links (for admins, authorized groups members and authorized students).
22
 *
23
 * @param   int Whether to show tool options
24
 * @param   int Whether to show upload form option
25
 * @param bool $isTutor
26
 */
27
function displayWorkActionLinks($id, $action, $isTutor)
28
{
29
    $id = $my_back_id = (int) $id;
30
    if ('list' === $action) {
31
        $my_back_id = 0;
32
    }
33
34
    $output = '';
35
    $origin = api_get_origin();
36
    if (!empty($id)) {
37
        $output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&id='.$my_back_id.'">'.
38
            Display::return_icon('back.png', get_lang('BackToWorksList'), '', ICON_SIZE_MEDIUM).
39
            '</a>';
40
    }
41
42
    if (($isTutor || api_is_allowed_to_edit(null, true)) &&
43
        'learnpath' !== $origin
44
    ) {
45
        // Create dir
46
        if (empty($id)) {
47
            $output .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=create_dir">';
48
            $output .= Display::return_icon(
49
                'new_work.png',
50
                get_lang('CreateAssignment'),
51
                '',
52
                ICON_SIZE_MEDIUM
53
            );
54
            $output .= '</a>';
55
        }
56
    }
57
58
    if (api_is_allowed_to_edit(null, true) && $origin !== 'learnpath' && $action === 'list') {
59
        $output .= '<a id="open-view-list" href="#">'.
60
            Display::return_icon(
61
                'listwork.png',
62
                get_lang('ViewStudents'),
63
                '',
64
                ICON_SIZE_MEDIUM
65
            ).
66
            '</a>';
67
    }
68
69
    if ('' != $output) {
70
        echo '<div class="actions">';
71
        echo $output;
72
        echo '</div>';
73
    }
74
}
75
76
/**
77
 * @param string $path
78
 * @param int    $courseId
79
 *
80
 * @return array
81
 */
82
function get_work_data_by_path($path, $courseId = 0)
83
{
84
    $path = Database::escape_string($path);
85
    $courseId = (int) $courseId;
86
    if (empty($courseId)) {
87
        $courseId = api_get_course_int_id();
88
    }
89
90
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
91
    $sql = "SELECT *  FROM $table
92
            WHERE url = '$path' AND c_id = $courseId ";
93
    $result = Database::query($sql);
94
    $return = [];
95
    if (Database::num_rows($result)) {
96
        $return = Database::fetch_array($result, 'ASSOC');
97
    }
98
99
    return $return;
100
}
101
102
/**
103
 * @param int $id
104
 * @param int $courseId
105
 * @param int $sessionId
106
 *
107
 * @return array
108
 */
109
function get_work_data_by_id($id, $courseId = 0, $sessionId = 0)
110
{
111
    $id = (int) $id;
112
    $courseId = ((int) $courseId) ?: api_get_course_int_id();
113
    $course = api_get_course_entity($courseId);
114
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
115
116
    $sessionCondition = '';
117
    if (!empty($sessionId)) {
118
        $sessionCondition = api_get_session_condition($sessionId, true);
119
    }
120
121
    $webCodePath = api_get_path(WEB_CODE_PATH);
122
123
    $sql = "SELECT * FROM $table
124
            WHERE
125
                id = $id AND c_id = $courseId
126
                $sessionCondition";
127
    $result = Database::query($sql);
128
    $work = [];
129
    if (Database::num_rows($result)) {
130
        $work = Database::fetch_array($result, 'ASSOC');
131
        if (empty($work['title'])) {
132
            $work['title'] = basename($work['url']);
133
        }
134
        $work['download_url'] = $webCodePath.'work/download.php?id='.$work['id'].'&'.api_get_cidreq();
135
        $work['view_url'] = $webCodePath.'work/view.php?id='.$work['id'].'&'.api_get_cidreq();
136
        $work['show_url'] = $webCodePath.'work/show_file.php?id='.$work['id'].'&'.api_get_cidreq();
137
        $work['show_content'] = '';
138
        if ($work['contains_file']) {
139
            $fileType = '';
140
            $file = api_get_path(SYS_COURSE_PATH).$course->getDirectory().'/'.$work['url'];
141
            if (file_exists($file)) {
142
                $fileType = mime_content_type($file);
143
            }
144
145
            if (in_array($fileType, ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
146
                $work['show_content'] = Display::img($work['show_url'], $work['title'], null, false);
147
            } elseif (false !== strpos($fileType, 'video/')) {
148
                $work['show_content'] = Display::tag(
149
                    'video',
150
                    get_lang('FileFormatNotSupported'),
151
                    ['src' => $work['show_url']]
152
                );
153
            }
154
        }
155
156
        $fieldValue = new ExtraFieldValue('work');
157
        $work['extra'] = $fieldValue->getAllValuesForAnItem($id, true);
158
    }
159
160
    return $work;
161
}
162
163
/**
164
 * @param int $user_id
165
 * @param int $work_id
166
 *
167
 * @return int
168
 */
169
function get_work_count_by_student($user_id, $work_id)
170
{
171
    $user_id = (int) $user_id;
172
    $work_id = (int) $work_id;
173
    $course_id = api_get_course_int_id();
174
    $session_id = api_get_session_id();
175
    $sessionCondition = api_get_session_condition($session_id);
176
177
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
178
    $sql = "SELECT COUNT(*) as count
179
            FROM  $table
180
            WHERE
181
                c_id = $course_id AND
182
                parent_id = $work_id AND
183
                user_id = $user_id AND
184
                active IN (0, 1)
185
                $sessionCondition";
186
    $result = Database::query($sql);
187
    $return = 0;
188
    if (Database::num_rows($result)) {
189
        $return = Database::fetch_row($result, 'ASSOC');
190
        $return = (int) ($return[0]);
191
    }
192
193
    return $return;
194
}
195
196
/**
197
 * @param int $id
198
 * @param int $courseId
199
 *
200
 * @return array
201
 */
202
function get_work_assignment_by_id($id, $courseId = 0)
203
{
204
    $courseId = (int) $courseId;
205
    if (empty($courseId)) {
206
        $courseId = api_get_course_int_id();
207
    }
208
    $id = (int) $id;
209
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
210
    $sql = "SELECT * FROM $table
211
            WHERE c_id = $courseId AND publication_id = $id";
212
    $result = Database::query($sql);
213
    $return = [];
214
    if (Database::num_rows($result)) {
215
        $return = Database::fetch_array($result, 'ASSOC');
216
    }
217
218
    return $return;
219
}
220
221
/**
222
 * @param int    $id
223
 * @param array  $my_folder_data
224
 * @param string $add_in_where_query
225
 * @param int    $course_id
226
 * @param int    $session_id
227
 *
228
 * @return array
229
 */
230
function getWorkList($id, $my_folder_data, $add_in_where_query = null, $course_id = 0, $session_id = 0)
231
{
232
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
233
234
    $course_id = $course_id ? $course_id : api_get_course_int_id();
235
    $session_id = $session_id ? $session_id : api_get_session_id();
236
    $condition_session = api_get_session_condition($session_id);
237
    $group_id = api_get_group_id();
238
239
    $groupIid = 0;
240
    if ($group_id) {
241
        $groupInfo = GroupManager::get_group_properties($group_id);
242
        if ($groupInfo) {
243
            $groupIid = $groupInfo['iid'];
244
        }
245
    }
246
247
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
248
    $linkInfo = GradebookUtils::isResourceInCourseGradebook(
249
        api_get_course_id(),
250
        3,
251
        $id,
252
        api_get_session_id()
253
    );
254
255
    if ($linkInfo) {
256
        $workInGradeBookLinkId = $linkInfo['id'];
257
        if ($workInGradeBookLinkId) {
258
            if ($is_allowed_to_edit) {
259
                if (intval($my_folder_data['qualification']) == 0) {
260
                    echo Display::return_message(
261
                        get_lang('MaxWeightNeedToBeProvided'),
262
                        'warning'
263
                    );
264
                }
265
            }
266
        }
267
    }
268
269
    $contains_file_query = '';
270
    // Get list from database
271
    if ($is_allowed_to_edit) {
272
        $active_condition = ' active IN (0, 1)';
273
        $sql = "SELECT * FROM $work_table
274
                WHERE
275
                    c_id = $course_id
276
                    $add_in_where_query
277
                    $condition_session AND
278
                    $active_condition AND
279
                    (parent_id = 0)
280
                    $contains_file_query AND
281
                    post_group_id = $groupIid
282
                ORDER BY sent_date DESC";
283
    } else {
284
        if (!empty($group_id)) {
285
            // set to select only messages posted by the user's group
286
            $group_query = " WHERE c_id = $course_id AND post_group_id = $groupIid";
287
            $subdirs_query = ' AND parent_id = 0';
288
        } else {
289
            $group_query = " WHERE c_id = $course_id AND (post_group_id = '0' OR post_group_id is NULL) ";
290
            $subdirs_query = ' AND parent_id = 0';
291
        }
292
        //@todo how we can active or not an assignment?
293
        $active_condition = ' AND active IN (1, 0)';
294
        $sql = "SELECT * FROM  $work_table
295
                $group_query
296
                $subdirs_query
297
                $add_in_where_query
298
                $active_condition
299
                $condition_session
300
                ORDER BY title";
301
    }
302
303
    $work_parents = [];
304
305
    $sql_result = Database::query($sql);
306
    if (Database::num_rows($sql_result)) {
307
        while ($work = Database::fetch_object($sql_result)) {
308
            if (0 == $work->parent_id) {
309
                $work_parents[] = $work;
310
            }
311
        }
312
    }
313
314
    return $work_parents;
315
}
316
317
/**
318
 * @param int $userId
319
 * @param int $courseId
320
 * @param int $sessionId
321
 *
322
 * @return array
323
 */
324
function getWorkPerUser($userId, $courseId = 0, $sessionId = 0)
325
{
326
    $works = getWorkList(null, null, null, $courseId, $sessionId);
327
    $result = [];
328
    if (!empty($works)) {
329
        foreach ($works as $workData) {
330
            $workId = $workData->id;
331
            $result[$workId]['work'] = $workData;
332
            $result[$workId]['work']->user_results = get_work_user_list(
333
                0,
334
                100,
335
                null,
336
                null,
337
                $workId,
338
                null,
339
                $userId,
340
                false,
341
                $courseId,
342
                $sessionId
343
            );
344
        }
345
    }
346
347
    return $result;
348
}
349
350
/**
351
 * @param int $workId
352
 * @param int $groupId
353
 * @param int $course_id
354
 * @param int $sessionId
355
 */
356
function getUniqueStudentAttemptsTotal($workId, $groupId, $course_id, $sessionId)
357
{
358
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
359
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
360
    $course_id = (int) $course_id;
361
    $workId = (int) $workId;
362
    $sessionId = (int) $sessionId;
363
    $groupId = (int) $groupId;
364
    $sessionCondition = api_get_session_condition(
365
        $sessionId,
366
        true,
367
        false,
368
        'w.session_id'
369
    );
370
371
    $groupIid = 0;
372
    if ($groupId) {
373
        $groupInfo = GroupManager::get_group_properties($groupId);
374
        $groupIid = $groupInfo['iid'];
375
    }
376
377
    $sql = "SELECT count(DISTINCT u.user_id)
378
            FROM $work_table w
379
            INNER JOIN $user_table u
380
            ON w.user_id = u.user_id
381
            WHERE
382
                w.c_id = $course_id
383
                $sessionCondition AND
384
                w.parent_id = $workId AND
385
                w.post_group_id = $groupIid AND
386
                w.active IN (0, 1)
387
            ";
388
389
    $res_document = Database::query($sql);
390
    $rowCount = Database::fetch_row($res_document);
391
392
    return $rowCount[0];
393
}
394
395
/**
396
 * @param mixed $workId
397
 * @param int   $groupId
398
 * @param int   $course_id
399
 * @param int   $sessionId
400
 * @param int   $userId       user id to filter
401
 * @param array $onlyUserList only parse this user list
402
 *
403
 * @return mixed
404
 */
405
function getUniqueStudentAttempts(
406
    $workId,
407
    $groupId,
408
    $course_id,
409
    $sessionId,
410
    $userId = null,
411
    $onlyUserList = []
412
) {
413
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
414
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
415
416
    $course_id = (int) $course_id;
417
    $workCondition = null;
418
    if (is_array($workId)) {
419
        $workId = array_map('intval', $workId);
420
        $workId = implode("','", $workId);
421
        $workCondition = " w.parent_id IN ('".$workId."') AND";
422
    } else {
423
        $workId = (int) $workId;
424
        $workCondition = ' w.parent_id = '.$workId.' AND';
425
    }
426
427
    $sessionId = (int) $sessionId;
428
    $groupId = (int) $groupId;
429
    $studentCondition = null;
430
431
    if (!empty($onlyUserList)) {
432
        $onlyUserList = array_map('intval', $onlyUserList);
433
        $studentCondition = "AND u.user_id IN ('".implode("', '", $onlyUserList)."') ";
434
    } else {
435
        if (empty($userId)) {
436
            return 0;
437
        }
438
    }
439
440
    $groupIid = 0;
441
    if ($groupId) {
442
        $groupInfo = GroupManager::get_group_properties($groupId);
443
        $groupIid = $groupInfo['iid'];
444
    }
445
446
    $sessionCondition = api_get_session_condition(
447
        $sessionId,
448
        true,
449
        false,
450
        'w.session_id'
451
    );
452
453
    $sql = "SELECT count(*) FROM (
454
                SELECT count(*), w.parent_id
455
                FROM $work_table w
456
                INNER JOIN $user_table u
457
                ON w.user_id = u.user_id
458
                WHERE
459
                    w.filetype = 'file' AND
460
                    w.c_id = $course_id
461
                    $sessionCondition AND
462
                    $workCondition
463
                    w.post_group_id = $groupIid AND
464
                    w.active IN (0, 1) $studentCondition
465
                ";
466
    if (!empty($userId)) {
467
        $userId = (int) $userId;
468
        $sql .= ' AND u.user_id = '.$userId;
469
    }
470
    $sql .= ' GROUP BY u.user_id, w.parent_id) as t';
471
    $result = Database::query($sql);
472
    $row = Database::fetch_row($result);
473
474
    return $row[0];
475
}
476
477
/**
478
 * Shows the work list (student view).
479
 *
480
 * @return string
481
 */
482
function showStudentWorkGrid()
483
{
484
    $courseInfo = api_get_course_info();
485
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_student&'.api_get_cidreq();
486
487
    $columns = [
488
        get_lang('Type'),
489
        get_lang('Title'),
490
        get_lang('HandOutDateLimit'),
491
        get_lang('Feedback'),
492
        get_lang('LastUpload'),
493
    ];
494
495
    $columnModel = [
496
        ['name' => 'type', 'index' => 'type', 'width' => '30', 'align' => 'center', 'sortable' => 'false'],
497
        ['name' => 'title', 'index' => 'title', 'width' => '250', 'align' => 'left'],
498
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '80', 'align' => 'center', 'sortable' => 'false'],
499
        ['name' => 'feedback', 'index' => 'feedback', 'width' => '80', 'align' => 'center', 'sortable' => 'false'],
500
        ['name' => 'last_upload', 'index' => 'feedback', 'width' => '125', 'align' => 'center', 'sortable' => 'false'],
501
    ];
502
503
    if ($courseInfo['show_score'] == 0) {
504
        $columnModel[] = [
505
            'name' => 'others',
506
            'index' => 'others',
507
            'width' => '80',
508
            'align' => 'left',
509
            'sortable' => 'false',
510
        ];
511
        $columns[] = get_lang('Others');
512
    }
513
514
    $params = [
515
        'autowidth' => 'true',
516
        'height' => 'auto',
517
    ];
518
519
    $html = '<script>
520
        $(function() {
521
            '.Display::grid_js('workList', $url, $columns, $columnModel, $params, [], null, true).'
522
        });
523
    </script>';
524
525
    $html .= Display::grid_html('workList');
526
527
    return $html;
528
}
529
530
/**
531
 * Shows the work list (student view).
532
 *
533
 * @return string
534
 */
535
function showStudentAllWorkGrid($withResults = 1)
536
{
537
    $withResults = (int) $withResults;
538
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_all_work_student&with_results='.$withResults;
539
540
    $columns = [
541
        get_lang('Type'),
542
        get_lang('Title'),
543
        get_lang('HandOutDateLimit'),
544
    ];
545
546
    $id = 'workList';
547
    if ($withResults) {
548
        $id = 'workListWithResults';
549
        $columns[] = get_lang('Feedback');
550
        $columns[] = get_lang('LastUpload');
551
    }
552
553
    $columnModel = [
554
        ['name' => 'type', 'index' => 'type', 'width' => '50', 'align' => 'center', 'sortable' => 'false'],
555
        ['name' => 'title', 'index' => 'title', 'width' => '600', 'align' => 'left'],
556
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '125', 'align' => 'center', 'sortable' => 'false'],
557
    ];
558
559
    if ($withResults) {
560
        $columnModel[] = [
561
            'name' => 'feedback',
562
            'index' => 'feedback',
563
            'width' => '150',
564
            'align' => 'center',
565
            'sortable' => 'false',
566
        ];
567
        $columnModel[] = [
568
            'name' => 'last_upload',
569
            'index' => 'last_upload',
570
            'width' => '150',
571
            'align' => 'center',
572
            'sortable' => 'false',
573
        ];
574
    }
575
576
    $params = [
577
        'autowidth' => 'true',
578
        'height' => 'auto',
579
    ];
580
581
    $html = '<script>
582
        $(function() {
583
            '.Display::grid_js($id, $url, $columns, $columnModel, $params, [], null, true).'
584
        });
585
    </script>';
586
587
    $html .= Display::grid_html($id);
588
589
    return $html;
590
}
591
592
/**
593
 * Shows the work list (teacher view).
594
 *
595
 * @return string
596
 */
597
function showTeacherWorkGrid()
598
{
599
    $columnModel = [
600
        ['name' => 'type', 'index' => 'type', 'width' => '35', 'align' => 'center', 'sortable' => 'false'],
601
        ['name' => 'title', 'index' => 'title', 'width' => '300', 'align' => 'left', 'wrap_cell' => "true"],
602
        ['name' => 'sent_date', 'index' => 'sent_date', 'width' => '125', 'align' => 'center'],
603
        ['name' => 'expires_on', 'index' => 'expires_on', 'width' => '125', 'align' => 'center'],
604
        ['name' => 'amount', 'index' => 'amount', 'width' => '110', 'align' => 'center', 'sortable' => 'false'],
605
        ['name' => 'actions', 'index' => 'actions', 'width' => '110', 'align' => 'left', 'sortable' => 'false'],
606
    ];
607
    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_teacher&'.api_get_cidreq();
608
    $deleteUrl = api_get_path(WEB_AJAX_PATH).'work.ajax.php?a=delete_work&'.api_get_cidreq();
609
610
    $columns = [
611
        get_lang('Type'),
612
        get_lang('Title'),
613
        get_lang('SentDate'),
614
        get_lang('HandOutDateLimit'),
615
        get_lang('AmountSubmitted'),
616
        get_lang('Actions'),
617
    ];
618
619
    $params = [
620
        'multiselect' => true,
621
        'autowidth' => 'true',
622
        'height' => 'auto',
623
        'sortname' => 'sent_date',
624
        'sortorder' => 'asc',
625
    ];
626
627
    $html = '<script>
628
    $(function() {
629
        '.Display::grid_js('workList', $url, $columns, $columnModel, $params, [], null, true).'
630
        $("#workList").jqGrid(
631
            "navGrid",
632
            "#workList_pager",
633
            { edit: false, add: false, del: true },
634
            { height:280, reloadAfterSubmit:false }, // edit options
635
            { height:280, reloadAfterSubmit:false }, // add options
636
            { reloadAfterSubmit:false, url: "'.$deleteUrl.'" }, // del options
637
            { width:500 } // search options
638
        );
639
    });
640
    </script>';
641
    $html .= Display::grid_html('workList');
642
643
    return $html;
644
}
645
646
/**
647
 * Builds the form that enables the user to
648
 * move a document from one directory to another
649
 * This function has been copied from the document/document.inc.php library.
650
 *
651
 * @param array  $folders
652
 * @param string $curdirpath
653
 * @param string $move_file
654
 * @param string $group_dir
655
 *
656
 * @return string html form
657
 */
658
function build_work_move_to_selector($folders, $curdirpath, $move_file, $group_dir = '')
659
{
660
    $course_id = api_get_course_int_id();
661
    $move_file = (int) $move_file;
662
    $tbl_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
663
    $sql = "SELECT title, url FROM $tbl_work
664
            WHERE c_id = $course_id AND id ='".$move_file."'";
665
    $result = Database::query($sql);
666
    $row = Database::fetch_array($result, 'ASSOC');
667
    $title = empty($row['title']) ? basename($row['url']) : $row['title'];
668
669
    $form = new FormValidator(
670
        'move_to_form',
671
        'post',
672
        api_get_self().'?'.api_get_cidreq().'&curdirpath='.Security::remove_XSS($curdirpath)
673
    );
674
675
    $form->addHeader(get_lang('MoveFile').' - '.Security::remove_XSS($title));
676
    $form->addHidden('item_id', $move_file);
677
    $form->addHidden('action', 'move_to');
678
679
    // Group documents cannot be uploaded in the root
680
    if ($group_dir == '') {
681
        if (is_array($folders)) {
682
            foreach ($folders as $fid => $folder) {
683
                //you cannot move a file to:
684
                //1. current directory
685
                //2. inside the folder you want to move
686
                //3. inside a subfolder of the folder you want to move
687
                if (($curdirpath != $folder) &&
688
                    ($folder != $move_file) &&
689
                    (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
690
                ) {
691
                    $options[$fid] = $folder;
692
                }
693
            }
694
        }
695
    } else {
696
        if ($curdirpath != '/') {
697
            $form .= '<option value="0">/ ('.get_lang('Root').')</option>';
698
        }
699
        foreach ($folders as $fid => $folder) {
700
            if (($curdirpath != $folder) && ($folder != $move_file) &&
701
                (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')
702
            ) {
703
                //cannot copy dir into his own subdir
704
                $display_folder = substr($folder, strlen($group_dir));
705
                $display_folder = ($display_folder == '') ? '/ ('.get_lang('Root').')' : $display_folder;
706
                //$form .= '<option value="'.$fid.'">'.$display_folder.'</option>'."\n";
707
                $options[$fid] = $display_folder;
708
            }
709
        }
710
    }
711
712
    $form->addSelect('move_to_id', get_lang('Select'), $options);
713
    $form->addButtonSend(get_lang('MoveFile'), 'move_file_submit');
714
715
    return $form->returnForm();
716
}
717
718
/**
719
 * creates a new directory trying to find a directory name
720
 * that doesn't already exist.
721
 *
722
 * @author Hugues Peeters <[email protected]>
723
 * @author Bert Vanderkimpen
724
 * @author Yannick Warnier <[email protected]> Adaptation for work tool
725
 *
726
 * @param string $workDir        Base work dir (.../work)
727
 * @param string $desiredDirName complete path of the desired name
728
 *
729
 * @return string actual directory name if it succeeds, boolean false otherwise
730
 */
731
function create_unexisting_work_directory($workDir, $desiredDirName)
732
{
733
    $counter = 0;
734
    $workDir = (substr($workDir, -1, 1) == '/' ? $workDir : $workDir.'/');
735
    $checkDirName = $desiredDirName;
736
    while (file_exists($workDir.$checkDirName)) {
737
        $counter++;
738
        $checkDirName = $desiredDirName.$counter;
739
    }
740
741
    if (@mkdir($workDir.$checkDirName, api_get_permissions_for_new_directories())) {
742
        return $checkDirName;
743
    } else {
744
        return false;
745
    }
746
}
747
748
/**
749
 * Delete a work-tool directory.
750
 *
751
 * @param int $id work directory id to delete
752
 *
753
 * @return int -1 on error
754
 */
755
function deleteDirWork($id)
756
{
757
    $locked = api_resource_is_locked_by_gradebook($id, LINK_STUDENTPUBLICATION);
758
759
    if ($locked == true) {
760
        echo Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
761
762
        return false;
763
    }
764
765
    $_course = api_get_course_info();
766
    $id = (int) $id;
767
    $work_data = get_work_data_by_id($id);
768
769
    if (empty($work_data)) {
770
        return false;
771
    }
772
773
    $base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work';
774
    $work_data_url = $base_work_dir.$work_data['url'];
775
    $check = Security::check_abs_path($work_data_url.'/', $base_work_dir.'/');
776
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
777
    $TSTDPUBASG = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
778
    $t_agenda = Database::get_course_table(TABLE_AGENDA);
779
    $course_id = api_get_course_int_id();
780
    $sessionId = api_get_session_id();
781
782
    if (!empty($work_data['url'])) {
783
        if ($check) {
784
            $consideredWorkingTime = api_get_configuration_value('considered_working_time');
785
            if (!empty($consideredWorkingTime)) {
786
                $fieldValue = new ExtraFieldValue('work');
787
                $resultExtra = $fieldValue->getAllValuesForAnItem(
788
                    $work_data['id'],
789
                    true
790
                );
791
792
                $workingTime = null;
793
                foreach ($resultExtra as $field) {
794
                    $field = $field['value'];
795
                    if ($consideredWorkingTime == $field->getField()->getVariable()) {
796
                        $workingTime = $field->getValue();
797
798
                        break;
799
                    }
800
                }
801
802
                $courseUsers = CourseManager::get_user_list_from_course_code($_course['code'], $sessionId);
803
                if (!empty($workingTime)) {
804
                    foreach ($courseUsers as $user) {
805
                        $userWorks = get_work_user_list(
806
                            0,
807
                            100,
808
                            null,
809
                            null,
810
                            $work_data['id'],
811
                            null,
812
                            $user['user_id'],
813
                            false,
814
                            $course_id,
815
                            $sessionId
816
                        );
817
818
                        if (count($userWorks) != 1) {
819
                            continue;
820
                        }
821
                        Event::eventRemoveVirtualCourseTime(
822
                            $course_id,
823
                            $user['user_id'],
824
                            $sessionId,
825
                            $workingTime,
826
                            $work_data['iid']
827
                        );
828
                    }
829
                }
830
            }
831
832
            // Deleting all contents inside the folder
833
            $sql = "UPDATE $table SET active = 2
834
                    WHERE c_id = $course_id AND filetype = 'folder' AND id = $id";
835
            Database::query($sql);
836
837
            $sql = "UPDATE $table SET active = 2
838
                    WHERE c_id = $course_id AND parent_id = $id";
839
            Database::query($sql);
840
841
            $new_dir = $work_data_url.'_DELETED_'.$id;
842
843
            if (api_get_setting('permanently_remove_deleted_files') == 'true') {
844
                my_delete($work_data_url);
845
            } else {
846
                if (file_exists($work_data_url)) {
847
                    rename($work_data_url, $new_dir);
848
                }
849
            }
850
851
            // Gets calendar_id from student_publication_assigment
852
            $sql = "SELECT add_to_calendar FROM $TSTDPUBASG
853
                    WHERE c_id = $course_id AND publication_id = $id";
854
            $res = Database::query($sql);
855
            $calendar_id = Database::fetch_row($res);
856
857
            // delete from agenda if it exists
858
            if (!empty($calendar_id[0])) {
859
                $sql = "DELETE FROM $t_agenda
860
                        WHERE c_id = $course_id AND id = '".$calendar_id[0]."'";
861
                Database::query($sql);
862
            }
863
            $sql = "DELETE FROM $TSTDPUBASG
864
                    WHERE c_id = $course_id AND publication_id = $id";
865
            Database::query($sql);
866
867
            Skill::deleteSkillsFromItem($id, ITEM_TYPE_STUDENT_PUBLICATION);
868
869
            Event::addEvent(
870
                LOG_WORK_DIR_DELETE,
871
                LOG_WORK_DATA,
872
                [
873
                    'id' => $work_data['id'],
874
                    'url' => $work_data['url'],
875
                    'title' => $work_data['title'],
876
                ],
877
                null,
878
                api_get_user_id(),
879
                api_get_course_int_id(),
880
                $sessionId
881
            );
882
883
            $linkInfo = GradebookUtils::isResourceInCourseGradebook(
884
                api_get_course_id(),
885
                3,
886
                $id,
887
                api_get_session_id()
888
            );
889
            $link_id = $linkInfo['id'];
890
            if ($linkInfo !== false) {
891
                GradebookUtils::remove_resource_from_course_gradebook($link_id);
892
            }
893
894
            return true;
895
        }
896
    }
897
}
898
899
/**
900
 * Get the path of a document in the student_publication table (path relative to the course directory).
901
 *
902
 * @param int $id
903
 *
904
 * @return string Path (or -1 on error)
905
 */
906
function get_work_path($id)
907
{
908
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
909
    $course_id = api_get_course_int_id();
910
    $sql = 'SELECT url FROM '.$table.'
911
            WHERE c_id = '.$course_id.' AND id='.(int) $id;
912
    $res = Database::query($sql);
913
    if (Database::num_rows($res)) {
914
        $row = Database::fetch_array($res);
915
916
        return $row['url'];
917
    }
918
919
    return -1;
920
}
921
922
/**
923
 * Update the url of a work in the student_publication table.
924
 *
925
 * @param int    $id        of the work to update
926
 * @param string $new_path  Destination directory where the work has been moved (must end with a '/')
927
 * @param int    $parent_id
928
 *
929
 * @return mixed Int -1 on error, sql query result on success
930
 */
931
function updateWorkUrl($id, $new_path, $parent_id)
932
{
933
    if (empty($id)) {
934
        return -1;
935
    }
936
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
937
    $course_id = api_get_course_int_id();
938
    $id = (int) $id;
939
    $parent_id = (int) $parent_id;
940
941
    $sql = "SELECT * FROM $table
942
            WHERE c_id = $course_id AND id = $id";
943
    $res = Database::query($sql);
944
    if (Database::num_rows($res) != 1) {
945
        return -1;
946
    } else {
947
        $row = Database::fetch_array($res);
948
        $filename = basename($row['url']);
949
        $new_url = $new_path.$filename;
950
        $new_url = Database::escape_string($new_url);
951
952
        $sql = "UPDATE $table SET
953
                   url = '$new_url',
954
                   parent_id = '$parent_id'
955
                WHERE c_id = $course_id AND id = $id";
956
957
        return Database::query($sql);
958
    }
959
}
960
961
/**
962
 * Update the url of a dir in the student_publication table.
963
 *
964
 * @param array  $work_data work original data
965
 * @param string $newPath   Example: "folder1"
966
 *
967
 * @return bool
968
 */
969
function updateDirName($work_data, $newPath)
970
{
971
    $course_id = $work_data['c_id'];
972
    $work_id = (int) ($work_data['iid']);
973
    $oldPath = $work_data['url'];
974
    $originalNewPath = Database::escape_string($newPath);
975
    $newPath = Database::escape_string($newPath);
976
    $newPath = api_replace_dangerous_char($newPath);
977
    $newPath = disable_dangerous_file($newPath);
978
979
    if ($oldPath == '/'.$newPath) {
980
        return true;
981
    }
982
983
    if (!empty($newPath)) {
984
        $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
985
        $sql = "UPDATE $table SET
986
                    title = '".$originalNewPath."'
987
                WHERE
988
                    c_id = $course_id AND
989
                    iid = $work_id";
990
        Database::query($sql);
991
    }
992
}
993
994
/**
995
 * returns all the javascript that is required for easily
996
 * validation when you create a work
997
 * this goes into the $htmlHeadXtra[] array.
998
 */
999
function to_javascript_work()
1000
{
1001
    return '<script>
1002
        function updateDocumentTitle(value) {
1003
            var temp = value.indexOf("/");
1004
            //linux path
1005
            if(temp != -1){
1006
                temp=value.split("/");
1007
            } else {
1008
                temp=value.split("\\\");
1009
            }
1010
1011
            var fullFilename = temp[temp.length - 1];
1012
            var baseFilename = fullFilename;
1013
1014
            // get file extension
1015
            var fileExtension = "";
1016
            if (fullFilename.match(/\..+/)) {
1017
                fileInfo = fullFilename.match(/(.*)\.([^.]+)$/);
1018
                if (fileInfo.length > 1) {
1019
                    fileExtension = "."+fileInfo[fileInfo.length - 1];
1020
                    baseFilename = fileInfo[fileInfo.length - 2];
1021
                }
1022
            }
1023
1024
            document.getElementById("file_upload").value = baseFilename;
1025
            document.getElementById("file_extension").value = fileExtension;
1026
            $("#contains_file_id").attr("value", 1);
1027
        }
1028
        function setFocus() {
1029
            $("#work_title").focus();
1030
        }
1031
1032
        $(function() {
1033
            setFocus();
1034
            var checked = $("#expiry_date").attr("checked");
1035
            if (checked) {
1036
                $("#option2").show();
1037
            } else {
1038
                $("#option2").hide();
1039
            }
1040
1041
            var checkedEndDate = $("#end_date").attr("checked");
1042
            if (checkedEndDate) {
1043
                $("#option3").show();
1044
                $("#ends_on").attr("checked", true);
1045
            } else {
1046
                $("#option3").hide();
1047
                $("#ends_on").attr("checked", false);
1048
            }
1049
1050
            $("#expiry_date").click(function() {
1051
                $("#option2").toggle();
1052
            });
1053
1054
            $("#end_date").click(function() {
1055
                $("#option3").toggle();
1056
            });
1057
        });
1058
    </script>';
1059
}
1060
1061
/**
1062
 * Gets the id of a student publication with a given path.
1063
 *
1064
 * @param string $path
1065
 *
1066
 * @return true if is found / false if not found
1067
 */
1068
// TODO: The name of this function does not fit with the kind of information it returns.
1069
// Maybe check_work_id() or is_work_id()?
1070
function get_work_id($path)
1071
{
1072
    $TBL_STUDENT_PUBLICATION = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1073
    $TBL_PROP_TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
1074
    $course_id = api_get_course_int_id();
1075
    $path = Database::escape_string($path);
1076
1077
    if (api_is_allowed_to_edit()) {
1078
        $sql = "SELECT work.id
1079
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1080
                WHERE
1081
                    props.c_id = $course_id AND
1082
                    work.c_id = $course_id AND
1083
                    props.tool='work' AND
1084
                    work.id=props.ref AND
1085
                    work.url LIKE 'work/".$path."%' AND
1086
                    work.filetype='file' AND
1087
                    props.visibility<>'2'";
1088
    } else {
1089
        $sql = "SELECT work.id
1090
                FROM $TBL_STUDENT_PUBLICATION AS work, $TBL_PROP_TABLE AS props
1091
                WHERE
1092
                    props.c_id = $course_id AND
1093
                    work.c_id = $course_id AND
1094
                    props.tool='work' AND
1095
                    work.id=props.ref AND
1096
                    work.url LIKE 'work/".$path."%' AND
1097
                    work.filetype='file' AND
1098
                    props.visibility<>'2' AND
1099
                    props.lastedit_user_id = '".api_get_user_id()."'";
1100
    }
1101
    $result = Database::query($sql);
1102
    $num_rows = Database::num_rows($result);
1103
1104
    if ($result && $num_rows > 0) {
1105
        return true;
1106
    } else {
1107
        return false;
1108
    }
1109
}
1110
1111
/**
1112
 * @param int $work_id
1113
 * @param int $onlyMeUserId show only my works
1114
 * @param int $notMeUserId  show works from everyone except me
1115
 *
1116
 * @return int
1117
 */
1118
function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null)
1119
{
1120
    $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1121
    $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1122
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
1123
1124
    $is_allowed_to_edit = api_is_allowed_to_edit(null, true) || api_is_coach();
1125
    $session_id = api_get_session_id();
1126
    $condition_session = api_get_session_condition(
1127
        $session_id,
1128
        true,
1129
        false,
1130
        'work.session_id'
1131
    );
1132
1133
    $group_id = api_get_group_id();
1134
    $course_info = api_get_course_info();
1135
    $course_id = $course_info['real_id'];
1136
    $work_id = (int) $work_id;
1137
1138
    $groupIid = 0;
1139
    if ($group_id) {
1140
        $groupInfo = GroupManager::get_group_properties($group_id);
1141
        if ($groupInfo && isset($groupInfo['iid'])) {
1142
            $groupIid = (int) $groupInfo['iid'];
1143
        }
1144
    }
1145
1146
    if (!empty($group_id)) {
1147
        // set to select only messages posted by the user's group
1148
        $extra_conditions = " work.post_group_id = '".$groupIid."' ";
1149
    } else {
1150
        $extra_conditions = " (work.post_group_id = '0' or work.post_group_id IS NULL) ";
1151
    }
1152
1153
    if ($is_allowed_to_edit) {
1154
        $extra_conditions .= ' AND work.active IN (0, 1) ';
1155
    } else {
1156
        $extra_conditions .= ' AND work.active IN (0, 1) AND accepted = 1';
1157
        if (isset($course_info['show_score']) && $course_info['show_score'] == 1) {
1158
            $extra_conditions .= " AND work.user_id = ".api_get_user_id()." ";
1159
        } else {
1160
            $extra_conditions .= '';
1161
        }
1162
    }
1163
1164
    $extra_conditions .= " AND parent_id  = ".$work_id."  ";
1165
    $where_condition = null;
1166
    if (!empty($notMeUserId)) {
1167
        $where_condition .= " AND u.user_id <> ".intval($notMeUserId);
1168
    }
1169
1170
    if (!empty($onlyMeUserId)) {
1171
        $where_condition .= " AND u.user_id =  ".intval($onlyMeUserId);
1172
    }
1173
1174
    $sql = "SELECT count(*) as count
1175
            FROM $iprop_table prop
1176
            INNER JOIN $work_table work
1177
            ON (
1178
                prop.ref = work.id AND
1179
                prop.c_id = $course_id AND
1180
                prop.tool='work' AND
1181
                prop.visibility <> 2 AND
1182
                work.c_id = $course_id
1183
            )
1184
            INNER JOIN $user_table u
1185
            ON (work.user_id = u.user_id)
1186
            WHERE $extra_conditions $where_condition $condition_session";
1187
1188
    $result = Database::query($sql);
1189
1190
    $users_with_work = 0;
1191
    if (Database::num_rows($result)) {
1192
        $result = Database::fetch_array($result);
1193
        $users_with_work = $result['count'];