Passed
Push — master ( 4bcd7f...0f4d24 )
by Julito
10:45 queued 10s
created

sorter()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CGlossary;
7
use ChamiloSession as Session;
8
9
/**
10
 * @author Christian Fasanando, initial version
11
 * @author Bas Wijnen import/export to CSV
12
 */
13
require_once __DIR__.'/../inc/global.inc.php';
14
15
$current_course_tool = TOOL_GLOSSARY;
16
17
// Notification for unauthorized people.
18
$this_section = SECTION_COURSES;
19
api_protect_course_script(true);
20
21
// Additional javascripts.
22
$htmlHeadXtra[] = GlossaryManager::javascript_glossary();
23
$htmlHeadXtra[] = '<script>
24
function setFocus(){
25
    $("#glossary_title").focus();
26
}
27
28
$(function() {
29
    setFocus();
30
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
31
    $( "#dialog-confirm" ).dialog({
32
        autoOpen: false,
33
        show: "blind",
34
        resizable: false,
35
        height:300,
36
        modal: true
37
    });
38
    $("#export_opener").click(function() {
39
        var targetUrl = $(this).attr("href");
40
        $( "#dialog-confirm" ).dialog({
41
            width:400,
42
            height:300,
43
            buttons: {
44
                "'.addslashes(get_lang('Download')).'": function() {
45
                    var export_format = $("input[name=export_format]:checked").val();
46
                    location.href = targetUrl+"&export_format="+export_format;
47
                    $( this ).dialog( "close" );
48
                }
49
            }
50
        });
51
        $( "#dialog-confirm" ).dialog("open");
52
        return false;
53
    });
54
});
55
</script>';
56
57
// Tracking
58
Event::event_access_tool(TOOL_GLOSSARY);
0 ignored issues
show
Bug introduced by
The method event_access_tool() does not exist on Event. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

58
Event::/** @scrutinizer ignore-call */ 
59
       event_access_tool(TOOL_GLOSSARY);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
59
60
/*
61
function sorter($item1, $item2)
62
{
63
    if ($item1[2] == $item2[2]) {
64
        return 0;
65
    }
66
67
    return $item1[2] < $item2[2] ? -1 : 1;
68
}
69
*/
70
// Displaying the header
71
$action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
72
$currentUrl = api_get_self().'?'.api_get_cidreq();
73
$interbreadcrumb[] = ['url' => 'index.php?'.api_get_cidreq(), 'name' => get_lang('Glossary')];
74
75
$content = '';
76
$tool_name = '';
77
switch ($action) {
78
    case 'addglossary':
79
        if (!api_is_allowed_to_edit(null, true)) {
80
            api_not_allowed(true);
81
        }
82
        $tool_name = get_lang('Add');
83
        $form = new FormValidator(
84
            'glossary',
85
            'post',
86
            api_get_self().'?action=addglossary&'.api_get_cidreq()
87
        );
88
        // Setting the form elements
89
        $form->addElement('header', get_lang('Add new glossary term'));
90
        if (api_get_configuration_value('save_titles_as_html')) {
91
            $form->addHtmlEditor(
92
                'name',
93
                get_lang('Term'),
94
                false,
95
                false,
96
                ['ToolbarSet' => 'TitleAsHtml']
97
            );
98
        } else {
99
            $form->addElement('text', 'name', get_lang('Term'), ['id' => 'glossary_title']);
100
        }
101
102
        $form->addElement(
103
            'html_editor',
104
            'description',
105
            get_lang('Term definition'),
106
            null,
107
            ['ToolbarSet' => 'Glossary', 'Height' => '300']
108
        );
109
        $form->addButtonCreate(get_lang('Save term'), 'SubmitGlossary');
110
        // setting the rules
111
        $form->addRule('name', get_lang('Required field'), 'required');
112
        // The validation or display
113
        if ($form->validate()) {
114
            $check = Security::check_token('post');
115
            if ($check) {
116
                $values = $form->exportValues();
117
                GlossaryManager::save_glossary($values);
118
            }
119
            Security::clear_token();
120
            header('Location: '.$currentUrl);
121
            exit;
122
        } else {
123
            $token = Security::get_token();
124
            $form->addElement('hidden', 'sec_token');
125
            $form->setConstants(['sec_token' => $token]);
126
            $content = Display::toolbarAction(
127
                'add_glossary',
128
                [
129
                    Display::url(
130
                        Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
131
                        api_get_self().'?'.api_get_cidreq()
132
                    ),
133
                ]
134
            );
135
            $content .= $form->returnForm();
136
        }
137
138
        break;
139
    case 'edit_glossary':
140
        if (!api_is_allowed_to_edit(null, true)) {
141
            api_not_allowed(true);
142
        }
143
        $tool_name = get_lang('Edit');
144
        $glossaryId = isset($_GET['glossary_id']) ? (int) $_GET['glossary_id'] : 0;
145
        if (!empty($glossaryId)) {
146
            // initiate the object
147
            $form = new FormValidator(
148
                'glossary',
149
                'post',
150
                api_get_self().'?action=edit_glossary&glossary_id='.$glossaryId.'&'.api_get_cidreq()
151
            );
152
            // Setting the form elements
153
            $form->addElement('header', get_lang('Edit term'));
154
            $form->addElement('hidden', 'glossary_id');
155
            if (api_get_configuration_value('save_titles_as_html')) {
156
                $form->addHtmlEditor(
157
                    'name',
158
                    get_lang('Term'),
159
                    false,
160
                    false,
161
                    ['ToolbarSet' => 'TitleAsHtml']
162
                );
163
            } else {
164
                $form->addElement('text', 'name', get_lang('Term'), ['id' => 'glossary_title']);
165
            }
166
167
            $form->addElement(
168
                'html_editor',
169
                'description',
170
                get_lang('Term definition'),
171
                null,
172
                ['ToolbarSet' => 'Glossary', 'Height' => '300']
173
            );
174
175
            $repo = Container::getGlossaryRepository();
176
            /** @var CGlossary $glossaryData */
177
            $glossaryData = $repo->find($glossaryId);
178
            /*
179
            // setting the defaults
180
            $glossary_data = GlossaryManager::get_glossary_information($glossaryId);
181
182
            // Date treatment for timezones
183
            if (!empty($glossary_data['insert_date'])) {
184
                $glossary_data['insert_date'] = Display::dateToStringAgoAndLongDate($glossary_data['insert_date']);
185
            } else {
186
                $glossary_data['insert_date'] = '';
187
            }
188
189
            if (!empty($glossary_data['update_date'])) {
190
                $glossary_data['update_date'] = Display::dateToStringAgoAndLongDate($glossary_data['update_date']);
191
            } else {
192
                $glossary_data['update_date'] = '';
193
            }
194
195
            $form->addLabel(get_lang('Creation date'), $glossary_data['insert_date']);
196
            $form->addLabel(get_lang('Updated'), $glossary_data['update_date']);
197
198
            */
199
            $form->addButtonUpdate(get_lang('Update term'), 'SubmitGlossary');
200
            $default = [
201
                'glossary_id' => $glossaryData->getIid(),
202
                'name' => $glossaryData->getName(),
203
                'description' => $glossaryData->getDescription(),
204
            ];
205
            $form->setDefaults($default);
206
207
            // setting the rules
208
            $form->addRule('name', get_lang('Required field'), 'required');
209
210
            // The validation or display
211
            if ($form->validate()) {
212
                $check = Security::check_token('post');
213
                if ($check) {
214
                    $values = $form->exportValues();
215
                    GlossaryManager::update_glossary($values);
216
                }
217
                Security::clear_token();
218
                header('Location: '.$currentUrl);
219
                exit;
220
            } else {
221
                $token = Security::get_token();
222
                $form->addElement('hidden', 'sec_token');
223
                $form->setConstants(['sec_token' => $token]);
224
                $content = Display::toolbarAction(
225
                    'edit_glossary',
226
                    [
227
                        Display::url(
228
                            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
229
                            api_get_self().'?'.api_get_cidreq()
230
                        ),
231
                    ]
232
                );
233
                $content .= $form->returnForm();
234
            }
235
        }
236
237
        break;
238
    case 'delete_glossary':
239
        if (!api_is_allowed_to_edit(null, true)) {
240
            api_not_allowed(true);
241
        }
242
        GlossaryManager::delete_glossary($_GET['glossary_id']);
243
        Security::clear_token();
244
        header('Location: '.$currentUrl);
245
        exit;
246
247
        break;
248
    case 'moveup':
249
        //GlossaryManager::move_glossary('up',$_GET['glossary_id']); //actions not available
250
        GlossaryManager::display_glossary();
251
252
        break;
253
    case 'movedown':
254
        //GlossaryManager::move_glossary('down',$_GET['glossary_id']); //actions not available
255
        GlossaryManager::display_glossary();
256
257
        break;
258
    case 'import':
259
        if (!api_is_allowed_to_edit(null, true)) {
260
            api_not_allowed(true);
261
        }
262
        $tool_name = get_lang('Import glossary');
263
        $form = new FormValidator(
264
            'glossary',
265
            'post',
266
            api_get_self().'?action=import&'.api_get_cidreq()
267
        );
268
        $form->addHeader(get_lang('Import glossary'));
269
        $form->addElement('file', 'file', get_lang('File'));
270
        $group = [];
271
        $group[] = $form->createElement(
272
            'radio',
273
            'file_type',
274
            '',
275
            'CSV',
276
            'csv'
277
        );
278
        $group[] = $form->createElement(
279
            'radio',
280
            'file_type',
281
            '',
282
            'XLS',
283
            'xls'
284
        );
285
        $form->addGroup($group, '', get_lang('File type'), null);
286
        $form->addElement('checkbox', 'replace', null, get_lang('Delete all terms before import.'));
287
        $form->addElement('checkbox', 'update', null, get_lang('Update existing terms.'));
288
        $form->addButtonImport(get_lang('Import'), 'SubmitImport');
289
        $form->setDefaults(['file_type' => 'csv']);
290
        $content = $form->returnForm();
291
292
        $content .= get_lang('The CSV file must look like this').' ('.get_lang('Fields in <strong>bold</strong> are mandatory.').')';
293
        $content .= '<pre>
294
                <strong>term</strong>;<strong>definition</strong>;
295
                "Hello";"Hola";
296
                "Goodbye";"Adiós";
297
        </pre>';
298
299
        if ($form->validate()) {
300
            $values = $form->getSubmitValues();
301
302
            $termsDeleted = [];
303
            //this is a bad idea //jm
304
            if (isset($_POST['replace']) && $_POST['replace']) {
305
                foreach (GlossaryManager::get_glossary_terms() as $term) {
306
                    if (!GlossaryManager::delete_glossary($term['id'], false)) {
307
                        Display::addFlash(
308
                            Display::return_message(get_lang('Cannot delete glossary').':'.$term['id'], 'error')
309
                        );
310
                    } else {
311
                        $termsDeleted[] = $term['name'];
312
                    }
313
                }
314
            }
315
316
            $updateTerms = isset($_POST['update']) && $_POST['update'] ? true : false;
317
318
            $format = $values['file_type'];
319
            switch ($format) {
320
                case 'csv':
321
                    $data = Import::csvToArray($_FILES['file']['tmp_name']);
322
323
                    break;
324
                case 'xls':
325
                    $data = Import::xlsToArray($_FILES['file']['tmp_name']);
326
327
                    break;
328
            }
329
330
            $updatedList = [];
331
            $addedList = [];
332
            $badList = [];
333
            $doubles = [];
334
            $termsPerKey = [];
335
336
            if ($data) {
337
                $termsToAdd = [];
338
                foreach ($data as $item) {
339
                    if (!isset($item['term'])) {
340
                        continue;
341
                    }
342
                    $items = [
343
                        'name' => $item['term'],
344
                        'description' => $item['definition'],
345
                    ];
346
                    $termsToAdd[] = $items;
347
                    $termsPerKey[$item['term']] = $items;
348
                }
349
350
                if (empty($termsToAdd)) {
351
                    Display::addFlash(
352
                        Display::return_message(get_lang('Nothing to add'), 'warning')
353
                    );
354
                    header('Location: '.$currentUrl);
355
                    exit;
356
                }
357
358
                $repeatItems = array_count_values(array_column($termsToAdd, 'name'));
359
                foreach ($repeatItems as $item => $count) {
360
                    if ($count > 1) {
361
                        $doubles[] = $item;
362
                    }
363
                }
364
365
                $uniqueTerms = array_unique(array_keys($repeatItems));
366
367
                foreach ($uniqueTerms as $itemTerm) {
368
                    $item = $termsPerKey[$itemTerm];
369
370
                    if ($updateTerms) {
371
                        $glossaryInfo = GlossaryManager::get_glossary_term_by_glossary_name($item['name']);
372
373
                        if (!empty($glossaryInfo)) {
374
                            $glossaryInfo['description'] = $item['description'];
375
                            GlossaryManager::update_glossary($glossaryInfo, false);
376
                            $updatedList[] = $item['name'];
377
                        } else {
378
                            $result = GlossaryManager::save_glossary($item, false);
379
                            if ($result) {
380
                                $addedList[] = $item['name'];
381
                            } else {
382
                                $badList[] = $item['name'];
383
                            }
384
                        }
385
                    } else {
386
                        $result = GlossaryManager::save_glossary($item, false);
387
                        if ($result) {
388
                            $addedList[] = $item['name'];
389
                        } else {
390
                            $badList[] = $item['name'];
391
                        }
392
                    }
393
                }
394
            }
395
396
            if (count($termsDeleted) > 0) {
397
                Display::addFlash(
398
                    Display::return_message(get_lang('Term removed').': '.implode(', ', $termsDeleted))
399
                );
400
            }
401
402
            if (count($updatedList) > 0) {
403
                Display::addFlash(
404
                    Display::return_message(get_lang('Terms updated').': '.implode(', ', $updatedList))
405
                );
406
            }
407
408
            if (count($addedList) > 0) {
409
                Display::addFlash(
410
                    Display::return_message(get_lang('Terms added').': '.implode(', ', $addedList))
411
                );
412
            }
413
414
            if (count($badList) > 0) {
415
                Display::addFlash(
416
                    Display::return_message(
417
                        get_lang('Term already exists').': '.implode(', ', $badList),
418
                        'error'
419
                    )
420
                );
421
            }
422
423
            if (count($doubles) > 0) {
424
                Display::addFlash(
425
                    Display::return_message(
426
                        get_lang('Terms duplicated in file').': '.implode(', ', $doubles),
427
                        'warning'
428
                    )
429
                );
430
            }
431
432
            header('Location: '.$currentUrl);
433
            exit;
434
        }
435
436
        break;
437
    case 'export':
438
        if (!api_is_allowed_to_edit(null, true)) {
439
            api_not_allowed(true);
440
        }
441
        $format = isset($_GET['export_format']) ? $_GET['export_format'] : 'csv';
442
        GlossaryManager::exportToFormat($format);
443
444
        break;
445
    case 'changeview':
446
        if (in_array($_GET['view'], ['list', 'table'])) {
447
            Session::write('glossary_view', $_GET['view']);
448
        } else {
449
            $view = Session::read('glossary_view');
450
            $defaultView = api_get_configuration_value('default_glossary_view');
451
            if (empty($defaultView)) {
452
                $defaultView = 'table';
453
            }
454
            if (empty($view)) {
455
                Session::write('glossary_view', $defaultView);
456
            }
457
        }
458
        header('Location: '.$currentUrl);
459
        exit;
460
461
        break;
462
    case 'export_documents':
463
        GlossaryManager::movePdfToDocuments();
464
        header('Location: '.$currentUrl);
465
        exit;
466
467
        break;
468
    default:
469
        $tool_name = get_lang('List');
470
        $htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_CODE_PATH).'glossary/glossary.js.php?add_ready=1&'.api_get_cidreq().'"></script>';
471
        $htmlHeadXtra[] = api_get_js('jquery.highlight.js');
472
        $content = GlossaryManager::display_glossary();
473
474
        break;
475
}
476
477
Display::display_header($tool_name);
478
479
Display::display_introduction_section(TOOL_GLOSSARY);
480
481
echo $content;
482
483
$extra = '<div id="dialog-confirm" title="'.get_lang('Please confirm your choice').'">';
484
$form = new FormValidator(
485
    'report',
486
    'post',
487
    api_get_self().'?'.api_get_cidreq(),
488
    null,
489
    ['class' => 'form-vertical']
490
);
491
$form->addElement(
492
    'radio',
493
    'export_format',
494
    null,
495
    get_lang('CSV export'),
496
    'csv',
497
    ['id' => 'export_format_csv_label']
498
);
499
$form->addElement(
500
    'radio',
501
    'export_format',
502
    null,
503
    get_lang('Excel export'),
504
    'xls',
505
    ['id' => 'export_format_xls_label']
506
);
507
$form->addElement(
508
    'radio',
509
    'export_format',
510
    null,
511
    get_lang('Export to PDF'),
512
    'pdf',
513
    ['id' => 'export_format_pdf_label']
514
);
515
516
$form->setDefaults(['export_format' => 'csv']);
517
$extra .= $form->returnForm();
518
$extra .= '</div>';
519
520
echo $extra;
521
522
Display::display_footer();
523