Passed
Push — master ( 2b8881...05b235 )
by Yannick
13:59 queued 03:52
created

CourseSelectForm   F

Complexity

Total Complexity 137

Size/Duplication

Total Lines 798
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 536
dl 0
loc 798
rs 2
c 0
b 0
f 0
wmc 137

7 Methods

Rating   Name   Duplication   Size   Complexity  
B display_hidden_scorm_directories() 0 14 7
F display_form() 0 256 22
D parseResources() 0 111 23
F get_posted_course() 0 196 67
B display_hidden_quiz_questions() 0 14 7
C display_form_session_export() 0 113 10
A getResourceTitleList() 0 27 1

How to fix   Complexity   

Complex Class

Complex classes like CourseSelectForm often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CourseSelectForm, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CourseBundle\Component\CourseCopy;
5
6
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Document;
7
use Chamilo\CourseBundle\Component\CourseCopy\Resources\Resource;
8
use Database;
9
use Display;
10
11
/**
12
 * Class to show a form to select resources.
13
 *
14
 * @author Bart Mollet <[email protected]>
15
 * @author Julio Montoya <[email protected]>
16
 *
17
 * @package chamilo.backup
18
 */
19
class CourseSelectForm
20
{
21
    /**
22
     * @return array
23
     */
24
    public static function getResourceTitleList()
25
    {
26
        $list = [];
27
        $list[RESOURCE_LEARNPATH_CATEGORY] = get_lang('Learnpath').' '.get_lang('Category');
28
        $list[RESOURCE_ASSET] = get_lang('Assets');
29
        $list[RESOURCE_GRADEBOOK] = get_lang('Gradebook');
30
        $list[RESOURCE_EVENT] = get_lang('Events');
31
        $list[RESOURCE_ANNOUNCEMENT] = get_lang('Announcements');
32
        $list[RESOURCE_DOCUMENT] = get_lang('Documents');
33
        $list[RESOURCE_LINK] = get_lang('Links');
34
        $list[RESOURCE_COURSEDESCRIPTION] = get_lang('CourseDescription');
35
        $list[RESOURCE_FORUM] = get_lang('Forums');
36
        $list[RESOURCE_FORUMCATEGORY] = get_lang('ForumCategory');
37
        $list[RESOURCE_QUIZ] = get_lang('Tests');
38
        $list[RESOURCE_TEST_CATEGORY] = get_lang('QuestionCategory');
39
        $list[RESOURCE_LEARNPATH] = get_lang('ToolLearnpath');
40
        $list[RESOURCE_LEARNPATH_CATEGORY] = get_lang('LearnpathCategory');
41
        $list[RESOURCE_SCORM] = 'SCORM';
42
        $list[RESOURCE_TOOL_INTRO] = get_lang('ToolIntro');
43
        $list[RESOURCE_SURVEY] = get_lang('Survey');
44
        $list[RESOURCE_GLOSSARY] = get_lang('Glossary');
45
        $list[RESOURCE_WIKI] = get_lang('Wiki');
46
        $list[RESOURCE_THEMATIC] = get_lang('Thematic');
47
        $list[RESOURCE_ATTENDANCE] = get_lang('Attendance');
48
        $list[RESOURCE_WORK] = get_lang('ToolStudentPublication');
49
50
        return $list;
51
    }
52
53
    /**
54
     * Display the form.
55
     *
56
     * @param array $course
57
     * @param array $hidden_fields     hidden fields to add to the form
58
     * @param bool  $avoidSerialize    the document array will be serialize.
59
     *                                 This is used in the course_copy.php file
60
     * @param bool  $avoidCourseInForm
61
     */
62
    public static function display_form(
63
        $course,
64
        $hidden_fields = null,
65
        $avoidSerialize = false,
66
        $avoidCourseInForm = false
67
    ) {
68
        global $charset; ?>
69
        <script>
70
            function exp(item) {
71
                el = document.getElementById('div_'+item);
72
                if (el.style.display == 'none') {
73
                    el.style.display = '';
74
                    $('#img_'+item).removeClass();
75
                    $('#img_'+item).addClass('fa fa-minus-square-o fa-lg');
76
77
                } else {
78
                    el.style.display = 'none';
79
                    $('#img_'+item).removeClass();
80
                    $('#img_'+item).addClass('fa fa-plus-square-o fa-lg');
81
                }
82
            }
83
84
            function setCheckboxForum(type, value, item_id) {
85
                d = document.course_select_form;
86
                for (i = 0; i < d.elements.length; i++) {
87
                    if (d.elements[i].type == "checkbox") {
88
                        var name = d.elements[i].attributes.getNamedItem('name').nodeValue;
89
                        if (name.indexOf(type) > 0 || type == 'all') {
90
                            if ($(d.elements[i]).attr('rel') == item_id) {
91
                                d.elements[i].checked = value;
92
                            }
93
                        }
94
                    }
95
                }
96
            }
97
98
            function setCheckbox(type,value) {
99
                d = document.course_select_form;
100
                for (i = 0; i < d.elements.length; i++) {
101
                    if (d.elements[i].type == "checkbox") {
102
                        var name = d.elements[i].attributes.getNamedItem('name').nodeValue;
103
                        if( name.indexOf(type) > 0 || type == 'all' ){
104
                             d.elements[i].checked = value;
105
                        }
106
                    }
107
                }
108
            }
109
110
            function checkLearnPath(message){
111
                d = document.course_select_form;
112
                for (i = 0; i < d.elements.length; i++) {
113
                    if (d.elements[i].type == "checkbox") {
114
                        var name = d.elements[i].attributes.getNamedItem('name').nodeValue;
115
                        if( name.indexOf('learnpath') > 0){
116
                            if(d.elements[i].checked){
117
                                setCheckbox('document',true);
118
                                alert(message);
119
                                break;
120
                            }
121
                        }
122
                    }
123
                }
124
            }
125
126
            function check_forum(obj) {
127
                var id = $(obj).attr('rel');
128
                var my_id = $(obj).attr('my_rel');
129
                var checked = false;
130
                if ($('#resource_forum_'+my_id).attr('checked')) {
131
                    checked = true;
132
                }
133
                setCheckboxForum('thread', checked, my_id);
134
                $('#resource_Forum_Category_'+id).attr('checked','checked');
135
            }
136
137
             function check_category(obj) {
138
                var my_id = $(obj).attr('my_rel');
139
                var checked = false;
140
                if ($('#resource_Forum_Category_'+my_id).attr('checked')) {
141
                    checked = true;
142
                }
143
                $('.resource_forum').each(function(index, value) {
144
                    if ($(value).attr('rel') == my_id) {
145
                        $(value).attr('checked', checked);
146
                    }
147
                });
148
149
                $('.resource_topic').each(function(index, value) {
150
                    if ($(value).attr('cat_id') == my_id) {
151
                        $(value).attr('checked', checked);
152
                    }
153
                });
154
            }
155
156
            function check_topic(obj) {
157
                var my_id = $(obj).attr('cat_id');
158
                var forum_id = $(obj).attr('forum_id');
159
                $('#resource_Forum_Category_'+my_id).attr('checked','checked');
160
                $('#resource_forum_'+forum_id).attr('checked','checked');
161
            }
162
        </script>
163
        <?php
164
        // get destination course title
165
        if (!empty($hidden_fields['destination_course'])) {
166
            $sessionTitle = !empty($hidden_fields['destination_session']) ? ' ('.api_get_session_name($hidden_fields['destination_session']).')' : null;
167
            $courseInfo = api_get_course_info($hidden_fields['destination_course']);
168
            echo '<h3>';
169
            echo get_lang('DestinationCourse').' : '.$courseInfo['title'].' ('.$courseInfo['code'].') '.$sessionTitle;
170
            echo '</h3>';
171
        }
172
173
        echo '<script src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/upload.js" type="text/javascript"></script>';
174
        echo '<div class="tool-backups-options">';
175
        echo '<form method="post" id="upload_form" name="course_select_form">';
176
        echo '<input type="hidden" name="action" value="course_select_form"/>';
177
178
        if (!empty($hidden_fields['destination_course']) &&
179
            !empty($hidden_fields['origin_course']) &&
180
            !empty($hidden_fields['destination_session']) &&
181
            !empty($hidden_fields['origin_session'])
182
        ) {
183
            echo '<input type="hidden" name="destination_course" value="'.$hidden_fields['destination_course'].'"/>';
184
            echo '<input type="hidden" name="origin_course" value="'.$hidden_fields['origin_course'].'"/>';
185
            echo '<input type="hidden" name="destination_session" value="'.$hidden_fields['destination_session'].'"/>';
186
            echo '<input type="hidden" name="origin_session" value="'.$hidden_fields['origin_session'].'"/>';
187
        }
188
189
        $forum_categories = [];
190
        $forums = [];
191
        $forum_topics = [];
192
193
        echo '<p>';
194
        echo get_lang('SelectResources');
195
        echo '</p>';
196
        echo Display::return_message(get_lang('DontForgetToSelectTheMediaFilesIfYourResourceNeedIt'));
197
198
        $resource_titles = self::getResourceTitleList();
199
        $element_count = self::parseResources($resource_titles, $course->resources, true, true);
200
201
        // Fixes forum order
202
        if (!empty($forum_categories)) {
203
            $type = RESOURCE_FORUMCATEGORY;
204
            echo '<div class="item-backup" onclick="javascript:exp('."'$type'".');">';
205
            echo '<em id="img_'.$type.'" class="fa fa-minus-square-o fa-lg"></em>';
206
            echo '<span class="title">'.$resource_titles[RESOURCE_FORUM].'</span></div>';
207
            echo '<div class="item-content" id="div_'.$type.'">';
208
            echo '<ul class="list-backups-options">';
209
            foreach ($forum_categories as $forum_category_id => $forum_category) {
210
                echo '<li>';
211
                echo '<label class="checkbox">';
212
                echo '<input type="checkbox" 
213
                    id="resource_'.RESOURCE_FORUMCATEGORY.'_'.$forum_category_id.'" 
214
                    my_rel="'.$forum_category_id.'" 
215
                    onclick="javascript:check_category(this);" 
216
                    name="resource['.RESOURCE_FORUMCATEGORY.']['.$forum_category_id.']" /> ';
217
                $forum_category->show();
218
                echo '</label>';
219
                echo '</li>';
220
221
                if (isset($forums[$forum_category_id])) {
222
                    $my_forums = $forums[$forum_category_id];
223
                    echo '<ul>';
224
                    foreach ($my_forums as $forum_id => $forum) {
225
                        echo '<li>';
226
                        echo '<label class="checkbox">';
227
                        echo '<input type="checkbox" 
228
                            class="resource_forum" 
229
                            id="resource_'.RESOURCE_FORUM.'_'.$forum_id.'" 
230
                            onclick="javascript:check_forum(this);" 
231
                            my_rel="'.$forum_id.'" 
232
                            rel="'.$forum_category_id.'" 
233
                            name="resource['.RESOURCE_FORUM.']['.$forum_id.']" />';
234
                        $forum->show();
235
                        echo '</label>';
236
                        echo '</li>';
237
                        if (isset($forum_topics[$forum_id])) {
238
                            $my_forum_topics = $forum_topics[$forum_id];
239
                            if (!empty($my_forum_topics)) {
240
                                echo '<ul>';
241
                                foreach ($my_forum_topics as $topic_id => $topic) {
242
                                    echo '<li>';
243
                                    echo '<label class="checkbox">';
244
                                    echo '<input 
245
                                        type="checkbox" 
246
                                        id="resource_'.RESOURCE_FORUMTOPIC.'_'.$topic_id.'" 
247
                                        onclick="javascript:check_topic(this);" class="resource_topic" 
248
                                        forum_id="'.$forum_id.'"  
249
                                        rel="'.$forum_id.'" 
250
                                        cat_id="'.$forum_category_id.'" 
251
                                        name="resource['.RESOURCE_FORUMTOPIC.']['.$topic_id.']" />';
252
                                    $topic->show();
253
                                    echo '</label>';
254
                                    echo '</li>';
255
                                }
256
                                echo '</ul>';
257
                            }
258
                        }
259
                    }
260
                    echo '</ul>';
261
                }
262
                echo '<hr/>';
263
            }
264
            echo '</ul>';
265
            echo '</div>';
266
            echo '<script language="javascript">exp('."'$type'".')</script>';
267
        }
268
269
        if ($avoidSerialize) {
270
            /*Documents are avoided due the huge amount of memory that the serialize php function "eats"
271
            (when there are directories with hundred/thousand of files) */
272
            // this is a known issue of serialize
273
            $course->resources['document'] = null;
274
        }
275
276
        if ($avoidCourseInForm === false) {
277
            /** @var Course $course */
278
            $courseSerialized = base64_encode(Course::serialize($course));
279
            echo '<input type="hidden" name="course" value="'.$courseSerialized.'"/>';
280
        }
281
282
        if (is_array($hidden_fields)) {
283
            foreach ($hidden_fields as $key => $value) {
284
                echo '<input type="hidden" name="'.$key.'" value="'.$value.'"/>';
285
            }
286
        }
287
288
        $recycleOption = isset($_POST['recycle_option']) ? true : false;
289
        if (empty($element_count)) {
290
            echo Display::return_message(get_lang('NoDataAvailable'), 'warning');
291
        } else {
292
            if (!empty($hidden_fields['destination_session'])) {
293
                echo '<br />
294
                      <button 
295
                        class="save" 
296
                        type="submit" 
297
                        onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset))."'".')) return false;" >'.
298
                    get_lang('Ok').'</button>';
299
            } else {
300
                if ($recycleOption) {
301
                    echo '<br /><button class="save" type="submit">'.get_lang('Ok').'</button>';
302
                } else {
303
                    echo '<br />
304
                          <button 
305
                                class="save btn btn-primary" 
306
                                type="submit" 
307
                                onclick="checkLearnPath(\''.addslashes(get_lang('DocumentsWillBeAddedToo')).'\')">'.
308
                    get_lang('Ok').'</button>';
309
                }
310
            }
311
        }
312
313
        self::display_hidden_quiz_questions($course);
314
        self::display_hidden_scorm_directories($course);
315
        echo '</form>';
316
        echo '</div>';
317
        echo '<div id="dynamic_div" style="display:block;margin-left:40%;margin-top:10px;height:50px;"></div>';
318
    }
319
320
    /**
321
     * @param array $resource_titles
322
     * @param array $resourceList
323
     * @param bool  $showHeader
324
     * @param bool  $showItems
325
     *
326
     * @return int
327
     */
328
    public static function parseResources(
329
        $resource_titles,
330
        $resourceList,
331
        $showHeader = true,
332
        $showItems = true
333
    ) {
334
        $element_count = 0;
335
        foreach ($resourceList as $type => $resources) {
336
            if (count($resources) > 0) {
337
                switch ($type) {
338
                    // Resources to avoid
339
                    case RESOURCE_FORUMCATEGORY:
340
                        foreach ($resources as $id => $resource) {
341
                            $forum_categories[$id] = $resource;
342
                        }
343
                        $element_count++;
344
                        break;
345
                    case RESOURCE_FORUM:
346
                        foreach ($resources as $id => $resource) {
347
                            $forums[$resource->obj->forum_category][$id] = $resource;
348
                        }
349
                        $element_count++;
350
                        break;
351
                    case RESOURCE_FORUMTOPIC:
352
                        foreach ($resources as $id => $resource) {
353
                            $forum_topics[$resource->obj->forum_id][$id] = $resource;
354
                        }
355
                        $element_count++;
356
                        break;
357
                    case RESOURCE_LINKCATEGORY:
358
                    case RESOURCE_FORUMPOST:
359
                    case RESOURCE_QUIZQUESTION:
360
                    case RESOURCE_SURVEYQUESTION:
361
                    case RESOURCE_SURVEYINVITATION:
362
                    case RESOURCE_SCORM:
363
                        break;
364
                    default:
365
                        if ($showHeader) {
366
                            echo '<div class="item-backup" onclick="javascript:exp('."'$type'".');">';
367
                            echo '<em id="img_'.$type.'" class="fa fa-plus-square-o fa-lg"></em>';
368
                            echo '<span class="title">'.$resource_titles[$type].'</span>';
369
                            echo '</div>';
370
                            echo '<div class="item-content" id="div_'.$type.'">';
371
                        }
372
373
                        if ($type == RESOURCE_LEARNPATH) {
374
                            echo Display::return_message(
375
                                get_lang(
376
                                    'ToExportLearnpathWithQuizYouHaveToSelectQuiz'
377
                                ),
378
                                'warning'
379
                            );
380
                            echo Display::return_message(
381
                                get_lang(
382
                                    'IfYourLPsHaveAudioFilesIncludedYouShouldSelectThemFromTheDocuments'
383
                                ),
384
                                'warning'
385
                            );
386
                        }
387
388
                        if ($type == RESOURCE_DOCUMENT) {
389
                            if (api_get_setting('show_glossary_in_documents') != 'none') {
390
                                echo Display::return_message(
391
                                    get_lang(
392
                                        'ToExportDocumentsWithGlossaryYouHaveToSelectGlossary'
393
                                    ),
394
                                    'warning'
395
                                );
396
                            }
397
                        }
398
399
                        if ($showItems) {
400
                            echo '<div class="well">';
401
                            echo '<div class="btn-group">';
402
                            echo "<a class=\"btn btn-default\" 
403
                                        href=\"javascript: void(0);\" 
404
                                        onclick=\"javascript: setCheckbox('$type',true);\" >".get_lang('All')."</a>";
405
                            echo "<a class=\"btn btn-default\" 
406
                                        href=\"javascript: void(0);\" 
407
                                        onclick=\"javascript:setCheckbox('$type',false);\" >".get_lang('None')."</a>";
408
                            echo '</div>';
409
                            echo '<ul class="list-backups-options">';
410
                            foreach ($resources as $id => $resource) {
411
                                if ($resource) {
412
                                    echo '<li>';
413
                                    // Event obj in 1.9.x in 1.10.x the class is CalendarEvent
414
                                    Resource::setClassType($resource);
415
                                    echo '<label class="checkbox">';
416
                                    echo '<input 
417
                                        type="checkbox" 
418
                                        name="resource['.$type.']['.$id.']"  
419
                                        id="resource['.$type.']['.$id.']" />';
420
                                    $resource->show();
421
                                    echo '</label>';
422
                                    echo '</li>';
423
                                }
424
                            }
425
                            echo '</ul>';
426
                            echo '</div>';
427
                        }
428
429
                        if ($showHeader) {
430
                            echo '</div>';
431
                            echo '<script language="javascript">exp('."'$type'".')</script>';
432
                        }
433
                        $element_count++;
434
                }
435
            }
436
        }
437
438
        return $element_count;
439
    }
440
441
    /**
442
     * @param $course
443
     */
444
    public static function display_hidden_quiz_questions($course)
445
    {
446
        if (is_array($course->resources)) {
447
            foreach ($course->resources as $type => $resources) {
448
                if (!empty($resources) && count($resources) > 0) {
449
                    switch ($type) {
450
                        case RESOURCE_QUIZQUESTION:
451
                            foreach ($resources as $id => $resource) {
452
                                echo '<input 
453
                                    type="hidden" 
454
                                    name="resource['.RESOURCE_QUIZQUESTION.']['.$id.']" 
455
                                    id="resource['.RESOURCE_QUIZQUESTION.']['.$id.']" value="On" />';
456
                            }
457
                            break;
458
                    }
459
                }
460
            }
461
        }
462
    }
463
464
    /**
465
     * @param $course
466
     */
467
    public static function display_hidden_scorm_directories($course)
468
    {
469
        if (is_array($course->resources)) {
470
            foreach ($course->resources as $type => $resources) {
471
                if (!empty($resources) && count($resources) > 0) {
472
                    switch ($type) {
473
                        case RESOURCE_SCORM:
474
                            foreach ($resources as $id => $resource) {
475
                                echo '<input 
476
                                    type="hidden" 
477
                                    name="resource['.RESOURCE_SCORM.']['.$id.']" 
478
                                    id="resource['.RESOURCE_SCORM.']['.$id.']" value="On" />';
479
                            }
480
                            break;
481
                    }
482
                }
483
            }
484
        }
485
    }
486
487
    /**
488
     * Get the posted course.
489
     *
490
     * @param string $from         who calls the function?
491
     *                             It can be copy_course, create_backup, import_backup or recycle_course
492
     * @param int    $session_id
493
     * @param string $course_code
494
     * @param Course $postedCourse
495
     *
496
     * @return Course The course-object with all resources selected by the user
497
     *                in the form given by display_form(...)
498
     */
499
    public static function get_posted_course($from = '', $session_id = 0, $course_code = '', $postedCourse = null)
500
    {
501
        $course = $postedCourse;
502
        if (empty($postedCourse)) {
503
            $cb = new CourseBuilder();
504
            $postResource = isset($_POST['resource']) ? $_POST['resource'] : [];
505
            $course = $cb->build(0, null, false, array_keys($postResource), $postResource);
506
        }
507
508
        if (empty($course)) {
509
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type Chamilo\CourseBundle\Component\CourseCopy\Course.
Loading history...
510
        }
511
512
        // Create the resource DOCUMENT objects
513
        // Loading the results from the checkboxes of ethe javascript
514
        $resource = isset($_POST['resource'][RESOURCE_DOCUMENT]) ? $_POST['resource'][RESOURCE_DOCUMENT] : null;
515
516
        $course_info = api_get_course_info($course_code);
517
        $table_doc = Database::get_course_table(TABLE_DOCUMENT);
518
        $table_prop = Database::get_course_table(TABLE_ITEM_PROPERTY);
519
        $course_id = $course_info['real_id'];
520
521
        /* Searching the documents resource that have been set to null because
522
        $avoidSerialize is true in the display_form() function*/
523
        if ($from === 'copy_course') {
524
            if (is_array($resource)) {
525
                $resource = array_keys($resource);
526
                foreach ($resource as $resource_item) {
527
                    $conditionSession = '';
528
                    if (!empty($session_id)) {
529
                        $session_id = (int) $session_id;
530
                        $conditionSession = ' AND d.session_id ='.$session_id;
531
                    }
532
533
                    $sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size
534
                            FROM '.$table_doc.' d 
535
                            INNER JOIN '.$table_prop.' p
536
                            ON (d.c_id = p.c_id)
537
                            WHERE
538
                                d.c_id = '.$course_id.' AND
539
                                p.c_id = '.$course_id.' AND
540
                                tool = \''.TOOL_DOCUMENT.'\' AND
541
                                p.ref = d.id AND p.visibility != 2 AND
542
                                d.id = '.$resource_item.$conditionSession.'
543
                            ORDER BY path';
544
                    $db_result = Database::query($sql);
545
                    while ($obj = Database::fetch_object($db_result)) {
546
                        $doc = new Document(
547
                            $obj->id,
548
                            $obj->path,
549
                            $obj->comment,
550
                            $obj->title,
551
                            $obj->filetype,
552
                            $obj->size
553
                        );
554
                        if ($doc) {
555
                            $course->add_resource($doc);
556
                            // adding item property
557
                            $sql = "SELECT * FROM $table_prop
558
                                    WHERE
559
                                        c_id = $course_id AND
560
                                        tool = '".RESOURCE_DOCUMENT."' AND
561
                                        ref = $resource_item ";
562
                            $res = Database::query($sql);
563
                            $all_properties = [];
564
                            while ($item_property = Database::fetch_array($res, 'ASSOC')) {
565
                                $all_properties[] = $item_property;
566
                            }
567
                            $course->resources[RESOURCE_DOCUMENT][$resource_item]->item_properties = $all_properties;
568
                        }
569
                    }
570
                }
571
            }
572
        }
573
574
        if (is_array($course->resources)) {
575
            foreach ($course->resources as $type => $resources) {
576
                switch ($type) {
577
                    case RESOURCE_SURVEYQUESTION:
578
                        foreach ($resources as $id => $obj) {
579
                            if (isset($_POST['resource'][RESOURCE_SURVEY]) &&
580
                                is_array($_POST['resource'][RESOURCE_SURVEY]) &&
581
                                !in_array($obj->survey_id, array_keys($_POST['resource'][RESOURCE_SURVEY]))
582
                            ) {
583
                                unset($course->resources[$type][$id]);
584
                            }
585
                        }
586
                        break;
587
                    case RESOURCE_FORUMTOPIC:
588
                    case RESOURCE_FORUMPOST:
589
                       //Add post from topic
590
                        if ($type == RESOURCE_FORUMTOPIC) {
591
                            $posts_to_save = [];
592
                            $posts = $course->resources[RESOURCE_FORUMPOST];
593
                            foreach ($resources as $thread_id => $obj) {
594
                                if (!isset($_POST['resource'][RESOURCE_FORUMTOPIC][$thread_id])) {
595
                                    unset($course->resources[RESOURCE_FORUMTOPIC][$thread_id]);
596
                                    continue;
597
                                }
598
                                $forum_id = $obj->obj->forum_id;
599
                                $title = $obj->obj->thread_title;
600
                                foreach ($posts as $post_id => $post) {
601
                                    if ($post->obj->thread_id == $thread_id &&
602
                                        $forum_id == $post->obj->forum_id &&
603
                                        $title == $post->obj->post_title
604
                                    ) {
605
                                        $posts_to_save[] = $post_id;
606
                                    }
607
                                }
608
                            }
609
                            if (!empty($posts)) {
610
                                foreach ($posts as $post_id => $post) {
611
                                    if (!in_array($post_id, $posts_to_save)) {
612
                                        unset($course->resources[RESOURCE_FORUMPOST][$post_id]);
613
                                    }
614
                                }
615
                            }
616
                        }
617
                        break;
618
                    case RESOURCE_LEARNPATH:
619
                        $lps = isset($_POST['resource'][RESOURCE_LEARNPATH]) ? $_POST['resource'][RESOURCE_LEARNPATH] : null;
620
621
                        if (!empty($lps)) {
622
                            foreach ($lps as $id => $obj) {
623
                                $lp_resource = $course->resources[RESOURCE_LEARNPATH][$id];
624
625
                                if (isset($lp_resource) && !empty($lp_resource) && isset($lp_resource->items)) {
626
                                    foreach ($lp_resource->items as $item) {
627
                                        switch ($item['item_type']) {
628
                                            //Add links added in a LP see #5760
629
                                            case 'link':
630
                                                $_POST['resource'][RESOURCE_LINK][$item['path']] = 1;
631
                                                break;
632
                                        }
633
                                    }
634
                                }
635
                            }
636
                        }
637
                        // no break
638
                    case RESOURCE_LINKCATEGORY:
639
                    case RESOURCE_FORUMCATEGORY:
640
                    case RESOURCE_QUIZQUESTION:
641
                    case RESOURCE_DOCUMENT:
642
                        // Mark folders to import which are not selected by the user to import,
643
                        // but in which a document was selected.
644
                        $documents = isset($_POST['resource'][RESOURCE_DOCUMENT]) ? $_POST['resource'][RESOURCE_DOCUMENT] : null;
645
                        if (!empty($resources) && is_array($resources)) {
646
                            foreach ($resources as $id => $obj) {
647
                                if (isset($obj->file_type) && $obj->file_type === 'folder' &&
648
                                    !isset($_POST['resource'][RESOURCE_DOCUMENT][$id]) &&
649
                                    is_array($documents)
650
                                ) {
651
                                    foreach ($documents as $id_to_check => $post_value) {
652
                                        if (isset($resources[$id_to_check])) {
653
                                            $obj_to_check = $resources[$id_to_check];
654
                                            $shared_path_part = substr(
655
                                                $obj_to_check->path,
656
                                                0,
657
                                                strlen($obj->path)
658
                                            );
659
                                            if ($id_to_check != $id && $obj->path == $shared_path_part) {
660
                                                $_POST['resource'][RESOURCE_DOCUMENT][$id] = 1;
661
                                                break;
662
                                            }
663
                                        }
664
                                    }
665
                                }
666
                            }
667
                        }
668
                        // no break
669
                    default:
670
                        if (!empty($resources) && is_array($resources)) {
671
                            foreach ($resources as $id => $obj) {
672
                                $resource_is_used_elsewhere = $course->is_linked_resource($obj);
673
                                // check if document is in a quiz (audio/video)
674
                                if ($type == RESOURCE_DOCUMENT && $course->has_resources(RESOURCE_QUIZ)) {
675
                                    foreach ($course->resources[RESOURCE_QUIZ] as $quiz) {
676
                                        $quiz = $quiz->obj;
677
                                        if (isset($quiz->media) && $quiz->media == $id) {
678
                                            $resource_is_used_elsewhere = true;
679
                                        }
680
                                    }
681
                                }
682
                                // quiz question can be, not attached to an exercise
683
                                if ($type != RESOURCE_QUIZQUESTION) {
684
                                    if (!isset($_POST['resource'][$type][$id]) && !$resource_is_used_elsewhere) {
685
                                        unset($course->resources[$type][$id]);
686
                                    }
687
                                }
688
                            }
689
                        }
690
                }
691
            }
692
        }
693
694
        return $course;
695
    }
696
697
    /**
698
     * Display the form session export.
699
     *
700
     * @param array $list_course
701
     * @param array $hidden_fields  hidden fields to add to the form
702
     * @param bool  $avoidSerialize the document array will be serialize. This is used in the course_copy.php file
703
     */
704
    public static function display_form_session_export(
705
        $list_course,
706
        $hidden_fields = null,
707
        $avoidSerialize = false
708
    ) {
709
        ?>
710
        <script>
711
            function exp(item) {
712
                el = document.getElementById('div_'+item);
713
                if (el.style.display == 'none') {
714
                    el.style.display = '';
715
                    if (document.getElementById('img_'+item).length)
716
                    document.getElementById('img_'+item).className('fa fa-minus-square-o fa-lg');
717
                } else {
718
                    el.style.display = 'none';
719
                    if (document.getElementById('img_'+item).length)
720
                    document.getElementById('img_'+item).className('fa fa-plus-square-o fa-lg');
721
                }
722
            }
723
724
            function setCheckbox(type,value) {
725
                d = document.course_select_form;
726
                for (i = 0; i < d.elements.length; i++) {
727
                    if (d.elements[i].type == "checkbox") {
728
                        var name = d.elements[i].attributes.getNamedItem('name').nodeValue;
729
                        if( name.indexOf(type) > 0 || type == 'all' ){
730
                             d.elements[i].checked = value;
731
                        }
732
                    }
733
                }
734
            }
735
            function checkLearnPath(message){
736
                d = document.course_select_form;
737
                for (i = 0; i < d.elements.length; i++) {
738
                    if (d.elements[i].type == "checkbox") {
739
                        var name = d.elements[i].attributes.getNamedItem('name').nodeValue;
740
                        if( name.indexOf('learnpath') > 0){
741
                            if(d.elements[i].checked){
742
                                setCheckbox('document',true);
743
                                alert(message);
744
                                break;
745
                            }
746
                        }
747
                    }
748
                }
749
            }
750
        </script>
751
        <?php
752
753
        //get destination course title
754
        if (!empty($hidden_fields['destination_course'])) {
755
            $sessionTitle = null;
756
            if (!empty($hidden_fields['destination_session'])) {
757
                $sessionTitle = ' ('.api_get_session_name($hidden_fields['destination_session']).')';
758
            }
759
            $courseInfo = api_get_course_info($hidden_fields['destination_course']);
760
            echo '<h3>';
761
            echo get_lang('DestinationCourse').' : '.$courseInfo['title'].$sessionTitle;
762
            echo '</h3>';
763
        }
764
765
        echo '<script src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/upload.js" type="text/javascript"></script>';
766
        $icon = Display::returnIconPath('progress_bar.gif');
767
        echo '<div class="tool-backups-options">';
768
        echo '<form method="post" id="upload_form" name="course_select_form">';
769
        echo '<input type="hidden" name="action" value="course_select_form"/>';
770
        foreach ($list_course as $course) {
771
            foreach ($course->resources as $type => $resources) {
772
                if (count($resources) > 0) {
773
                    echo '<div class="item-backup" onclick="javascript:exp('."'$course->code'".');">';
774
                    echo '<em id="img_'.$course->code.'" class="fa fa-minus-square-o fa-lg"></em>';
775
                    echo '<span class="title"> '.$course->code.'</span></div>';
776
                    echo '<div class="item-content" id="div_'.$course->code.'">';
777
                    echo '<blockquote>';
778
779
                    echo '<div class="btn-group">';
780
                    echo "<a class=\"btn\" href=\"#\" onclick=\"javascript:setCheckbox('".$course->code."',true);\" >".get_lang('All')."</a>";
781
                    echo "<a class=\"btn\" href=\"#\" onclick=\"javascript:setCheckbox('".$course->code."',false);\" >".get_lang('None')."</a>";
782
                    echo '</div>';
783
784
                    foreach ($resources as $id => $resource) {
785
                        echo '<label class="checkbox" for="resource['.$course->code.']['.$id.']">';
786
                        echo '<input type="checkbox" name="resource['.$course->code.']['.$id.']" id="resource['.$course->code.']['.$id.']"/>';
787
                        $resource->show();
788
                        echo '</label>';
789
                    }
790
                    echo '</blockquote>';
791
                    echo '</div>';
792
                    echo '<script type="text/javascript">exp('."'$course->code'".')</script>';
793
                }
794
            }
795
        }
796
        if ($avoidSerialize) {
797
            // Documents are avoided due the huge amount of memory that the serialize php
798
            // function "eats" (when there are directories with hundred/thousand of files)
799
            // this is a known issue of serialize
800
            $course->resources['document'] = null;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $course seems to be defined by a foreach iteration on line 770. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
801
        }
802
        echo '<input type="hidden" name="course" value="'.base64_encode(Course::serialize($course)).'"/>';
803
        if (is_array($hidden_fields)) {
804
            foreach ($hidden_fields as $key => $value) {
805
                echo "\n";
806
                echo '<input type="hidden" name="'.$key.'" value="'.$value.'"/>';
807
            }
808
        }
809
        echo '<br /><button class="save" type="submit" 
810
            onclick="checkLearnPath(\''.addslashes(get_lang('DocumentsWillBeAddedToo')).'\')">'.
811
            get_lang('Ok').'</button>';
812
        self::display_hidden_quiz_questions($course);
813
        self::display_hidden_scorm_directories($course);
814
        echo '</form>';
815
        echo '</div>';
816
        echo '<div id="dynamic_div" style="display:block;margin-left:40%;margin-top:10px;height:50px;"></div>';
817
    }
818
}
819