Issues (1798)

public/main/glossary/index.php (1 issue)

Labels
Severity
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
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
9
10
/**
11
 * @author Christian Fasanando, initial version
12
 * @author Bas Wijnen import/export to CSV
13
 */
14
require_once __DIR__.'/../inc/global.inc.php';
15
16
$current_course_tool = TOOL_GLOSSARY;
17
18
// Notification for unauthorized people.
19
$this_section = SECTION_COURSES;
20
api_protect_course_script(true);
21
22
// Additional javascripts.
23
$htmlHeadXtra[] = GlossaryManager::javascript_glossary();
24
$htmlHeadXtra[] = '<script>
25
function setFocus(){
26
    $("#glossary_title").focus();
27
}
28
29
$(function() {
30
    setFocus();
31
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
32
    $( "#dialog-confirm" ).dialog({
33
        autoOpen: false,
34
        show: "blind",
35
        resizable: false,
36
        height:300,
37
        modal: true
38
    });
39
    $("#export_opener").click(function() {
40
        var targetUrl = $(this).attr("href");
41
        $( "#dialog-confirm" ).dialog({
42
            width:400,
43
            height:300,
44
            buttons: {
45
                "'.addslashes(get_lang('Download')).'": function() {
46
                    var export_format = $("input[name=export_format]:checked").val();
47
                    location.href = targetUrl+"&export_format="+export_format;
48
                    $( this ).dialog( "close" );
49
                }
50
            }
51
        });
52
        $( "#dialog-confirm" ).dialog("open");
53
        return false;
54
    });
55
});
56
</script>';
57
58
// Tracking
59
Event::event_access_tool(TOOL_GLOSSARY);
0 ignored issues
show
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

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