Issues (2128)

main/glossary/index.php (3 issues)

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
7
/**
8
 * @author Christian Fasanando, initial version
9
 * @author Bas Wijnen import/export to CSV
10
 */
11
require_once __DIR__.'/../inc/global.inc.php';
12
13
$current_course_tool = TOOL_GLOSSARY;
14
15
// The section (tabs).
16
$this_section = SECTION_COURSES;
17
18
// Notification for unauthorized people.
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
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
function sorter($item1, $item2)
61
{
62
    if ($item1[2] == $item2[2]) {
63
        return 0;
64
    }
65
66
    return $item1[2] < $item2[2] ? -1 : 1;
67
}
68
69
// Displaying the header
70
$action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
71
$currentUrl = api_get_self().'?'.api_get_cidreq();
72
$interbreadcrumb[] = ['url' => 'index.php?'.api_get_cidreq(), 'name' => get_lang('Glossary')];
73
74
$content = '';
75
$tool_name = '';
76
switch ($action) {
77
    case 'addglossary':
78
        if (!api_is_allowed_to_edit(null, true)) {
79
            api_not_allowed(true);
80
        }
81
        $tool_name = get_lang('Add');
82
        $form = new FormValidator(
83
            'glossary',
84
            'post',
85
            api_get_self().'?action=addglossary&'.api_get_cidreq()
86
        );
87
        // Setting the form elements
88
        $form->addElement('header', get_lang('TermAddNew'));
89
        if (api_get_configuration_value('save_titles_as_html')) {
90
            $form->addHtmlEditor(
91
                'name',
92
                get_lang('TermName'),
93
                true,
94
                false,
95
                ['ToolbarSet' => 'TitleAsHtml']
96
            );
97
        } else {
98
            $form->addText('name', get_lang('TermName'), true, ['id' => 'glossary_title']);
99
        }
100
101
        $form->addHtmlEditor(
102
            'description',
103
            get_lang('TermDefinition'),
104
            false,
105
            false,
106
            ['ToolbarSet' => 'Glossary', 'Height' => '300']
107
        );
108
        $form->addButtonCreate(get_lang('TermAddButton'), 'SubmitGlossary');
109
        // setting the rules
110
        // The validation or display
111
        if ($form->validate()) {
112
            $check = Security::check_token('post');
113
            if ($check) {
114
                $values = $form->exportValues();
115
                GlossaryManager::save_glossary($values);
116
            }
117
            Security::clear_token();
118
            header('Location: '.$currentUrl);
119
            exit;
120
        } else {
121
            $token = Security::get_token();
122
            $form->addElement('hidden', 'sec_token');
123
            $form->setConstants(['sec_token' => $token]);
124
            $content = Display::toolbarAction(
125
                'add_glossary',
126
                [
127
                    Display::url(
128
                        Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
129
                        api_get_self().'?'.api_get_cidreq()
130
                    ),
131
                ]
132
            );
133
            $content .= $form->returnForm();
134
        }
135
        break;
136
    case 'edit_glossary':
137
        if (!api_is_allowed_to_edit(null, true)) {
138
            api_not_allowed(true);
139
        }
140
        $tool_name = get_lang('Edit');
141
        $glossaryId = isset($_GET['glossary_id']) ? (int) $_GET['glossary_id'] : 0;
142
        if (!empty($glossaryId)) {
143
            // initiate the object
144
            $form = new FormValidator(
145
                'glossary',
146
                'post',
147
                api_get_self().'?action=edit_glossary&glossary_id='.$glossaryId.'&'.api_get_cidreq()
148
            );
149
            // Setting the form elements
150
            $form->addElement('header', get_lang('TermEdit'));
151
            $form->addElement('hidden', 'glossary_id');
152
            if (api_get_configuration_value('save_titles_as_html')) {
153
                $form->addHtmlEditor(
154
                    'name',
155
                    get_lang('TermName'),
156
                    true,
157
                    false,
158
                    ['ToolbarSet' => 'TitleAsHtml']
159
                );
160
            } else {
161
                $form->addText('name', get_lang('TermName'), true, ['id' => 'glossary_title']);
162
            }
163
164
            $form->addHtmlEditor(
165
                'description',
166
                get_lang('TermDefinition'),
167
                false,
168
                false,
169
                ['ToolbarSet' => 'Glossary', 'Height' => '300']
170
            );
171
172
            // setting the defaults
173
            $glossary_data = GlossaryManager::get_glossary_information($glossaryId);
174
175
            // Date treatment for timezones
176
            if (!empty($glossary_data['insert_date'])) {
177
                $glossary_data['insert_date'] = Display::dateToStringAgoAndLongDate($glossary_data['insert_date']);
178
            } else {
179
                $glossary_data['insert_date'] = '';
180
            }
181
182
            if (!empty($glossary_data['update_date'])) {
183
                $glossary_data['update_date'] = Display::dateToStringAgoAndLongDate($glossary_data['update_date']);
184
            } else {
185
                $glossary_data['update_date'] = '';
186
            }
187
188
            $form->addLabel(get_lang('CreationDate'), $glossary_data['insert_date']);
189
            $form->addLabel(get_lang('UpdateDate'), $glossary_data['update_date']);
190
191
            $form->addButtonUpdate(get_lang('TermUpdateButton'), 'SubmitGlossary');
192
            $form->setDefaults($glossary_data);
193
194
            // The validation or display
195
            if ($form->validate()) {
196
                $check = Security::check_token('post');
197
                if ($check) {
198
                    $values = $form->exportValues();
199
                    GlossaryManager::update_glossary($values);
200
                }
201
                Security::clear_token();
202
                header('Location: '.$currentUrl);
203
                exit;
204
            } else {
205
                $token = Security::get_token();
206
                $form->addElement('hidden', 'sec_token');
207
                $form->setConstants(['sec_token' => $token]);
208
                $content = Display::toolbarAction(
209
                    'edit_glossary',
210
                    [
211
                        Display::url(
212
                            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
213
                            api_get_self().'?'.api_get_cidreq()
214
                        ),
215
                    ]
216
                );
217
                $content .= $form->returnForm();
218
            }
219
        }
220
        break;
221
    case 'delete_glossary':
222
        if (!api_is_allowed_to_edit(null, true)) {
223
            api_not_allowed(true);
224
        }
225
        GlossaryManager::delete_glossary($_GET['glossary_id']);
226
        Security::clear_token();
227
        header('Location: '.$currentUrl);
228
        exit;
229
        break;
230
    case 'moveup':
231
        //GlossaryManager::move_glossary('up',$_GET['glossary_id']); //actions not available
232
        GlossaryManager::display_glossary();
233
        break;
234
    case 'movedown':
235
        //GlossaryManager::move_glossary('down',$_GET['glossary_id']); //actions not available
236
        GlossaryManager::display_glossary();
237
        break;
238
    case 'import':
239
        if (!api_is_allowed_to_edit(null, true)) {
240
            api_not_allowed(true);
241
        }
242
        $tool_name = get_lang('ImportGlossary');
243
        $form = new FormValidator(
244
            'glossary',
245
            'post',
246
            api_get_self().'?action=import&'.api_get_cidreq()
247
        );
248
        $form->addHeader(get_lang('ImportGlossary'));
249
        $form->addElement('file', 'file', get_lang('File'));
250
        $group = [];
251
        $group[] = $form->createElement(
252
            'radio',
253
            'file_type',
254
            '',
255
            'CSV',
256
            'csv'
257
        );
258
        $group[] = $form->createElement(
259
            'radio',
260
            'file_type',
261
            '',
262
            'XLS',
263
            'xls'
264
        );
265
        $form->addGroup($group, '', get_lang('FileType'), null);
266
        $form->addElement('checkbox', 'replace', null, get_lang('DeleteAllGlossaryTerms'));
267
        $form->addElement('checkbox', 'update', null, get_lang('UpdateExistingGlossaryTerms'));
268
        $form->addButtonImport(get_lang('Import'), 'SubmitImport');
269
        $form->setDefaults(['file_type' => 'csv']);
270
        $content = $form->returnForm();
271
272
        $content .= get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')';
273
        $content .= '<pre>
274
                <strong>term</strong>;<strong>definition</strong>;
275
                "Hello";"Hola";
276
                "Goodbye";"Adiós";
277
        </pre>';
278
279
        if ($form->validate()) {
280
            $values = $form->getSubmitValues();
281
282
            $termsDeleted = [];
283
            //this is a bad idea //jm
284
            if (isset($_POST['replace']) && $_POST['replace']) {
285
                foreach (GlossaryManager::get_glossary_terms() as $term) {
286
                    if (!GlossaryManager::delete_glossary($term['id'], false)) {
287
                        Display::addFlash(
288
                            Display::return_message(get_lang('CannotDeleteGlossary').':'.$term['id'], 'error')
289
                        );
290
                    } else {
291
                        $termsDeleted[] = $term['name'];
292
                    }
293
                }
294
            }
295
296
            $updateTerms = isset($_POST['update']) && $_POST['update'] ? true : false;
297
298
            $format = $values['file_type'];
299
            switch ($format) {
300
                case 'csv':
301
                    $data = Import::csvToArray($_FILES['file']['tmp_name']);
302
                    break;
303
                case 'xls':
304
                    $data = Import::xlsToArray($_FILES['file']['tmp_name']);
305
                    break;
306
            }
307
308
            $goodList = [];
309
            $updatedList = [];
310
            $addedList = [];
311
            $badList = [];
312
            $doubles = [];
313
            $added = [];
314
            $termsPerKey = [];
315
316
            if ($data) {
317
                $termsToAdd = [];
318
                foreach ($data as $item) {
319
                    if (!isset($item['term'])) {
320
                        continue;
321
                    }
322
                    $items = [
323
                        'name' => $item['term'],
324
                        'description' => $item['definition'],
325
                    ];
326
                    $termsToAdd[] = $items;
327
                    $termsPerKey[$item['term']] = $items;
328
                }
329
330
                if (empty($termsToAdd)) {
331
                    Display::addFlash(
332
                        Display::return_message(get_lang('NothingToAdd'), 'warning')
333
                    );
334
                    header('Location: '.$currentUrl);
335
                    exit;
336
                }
337
338
                $repeatItems = array_count_values(array_column($termsToAdd, 'name'));
339
                foreach ($repeatItems as $item => $count) {
340
                    if ($count > 1) {
341
                        $doubles[] = $item;
342
                    }
343
                }
344
345
                $uniqueTerms = array_unique(array_keys($repeatItems));
346
347
                foreach ($uniqueTerms as $itemTerm) {
348
                    $item = $termsPerKey[$itemTerm];
349
350
                    if ($updateTerms) {
351
                        $glossaryInfo = GlossaryManager::get_glossary_term_by_glossary_name($item['name']);
352
353
                        if (!empty($glossaryInfo)) {
354
                            $glossaryInfo['description'] = $item['description'];
355
                            GlossaryManager::update_glossary($glossaryInfo, false);
356
                            $updatedList[] = $item['name'];
357
                        } else {
358
                            $result = GlossaryManager::save_glossary($item, false);
359
                            if ($result) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $result of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
360
                                $addedList[] = $item['name'];
361
                            } else {
362
                                $badList[] = $item['name'];
363
                            }
364
                        }
365
                    } else {
366
                        $result = GlossaryManager::save_glossary($item, false);
367
                        if ($result) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $result of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
368
                            $addedList[] = $item['name'];
369
                        } else {
370
                            $badList[] = $item['name'];
371
                        }
372
                    }
373
                }
374
            }
375
376
            if (count($termsDeleted) > 0) {
377
                Display::addFlash(
378
                    Display::return_message(get_lang('TermDeleted').': '.implode(', ', $termsDeleted))
379
                );
380
            }
381
382
            if (count($updatedList) > 0) {
383
                Display::addFlash(
384
                    Display::return_message(get_lang('TermsUpdated').': '.implode(', ', $updatedList))
385
                );
386
            }
387
388
            if (count($addedList) > 0) {
389
                Display::addFlash(
390
                    Display::return_message(get_lang('TermsAdded').': '.implode(', ', $addedList))
391
                );
392
            }
393
394
            if (count($badList) > 0) {
395
                Display::addFlash(
396
                    Display::return_message(
397
                        get_lang('GlossaryTermAlreadyExists').': '.implode(', ', $badList),
398
                        'error'
399
                    )
400
                );
401
            }
402
403
            if (count($doubles) > 0) {
404
                Display::addFlash(
405
                    Display::return_message(
406
                        get_lang('TermsDuplicatedInFile').': '.implode(', ', $doubles),
407
                        'warning'
408
                    )
409
                );
410
            }
411
412
            header('Location: '.$currentUrl);
413
            exit;
414
        }
415
        break;
416
    case 'export':
417
        if (!api_is_allowed_to_edit(null, true)) {
418
            api_not_allowed(true);
419
        }
420
        $format = isset($_GET['export_format']) ? $_GET['export_format'] : 'csv';
421
        GlossaryManager::exportToFormat($format);
422
        break;
423
    case 'changeview':
424
        if (in_array($_GET['view'], ['list', 'table'])) {
425
            Session::write('glossary_view', $_GET['view']);
426
        } else {
427
            $view = Session::read('glossary_view');
428
            $defaultView = api_get_configuration_value('default_glossary_view');
429
            if (empty($defaultView)) {
430
                $defaultView = 'table';
431
            }
432
            if (empty($view)) {
433
                Session::write('glossary_view', $defaultView);
434
            }
435
        }
436
        header('Location: '.$currentUrl);
437
        exit;
438
        break;
439
    case 'export_documents':
440
        GlossaryManager::movePdfToDocuments();
441
        header('Location: '.$currentUrl);
442
        exit;
443
        break;
444
    default:
445
        $tool_name = get_lang('List');
446
        $htmlHeadXtra[] = '<script
447
            type="text/javascript"
448
            src="'.api_get_path(WEB_CODE_PATH).'glossary/glossary.js.php?add_ready=1&'.api_get_cidreq().'"></script>';
449
        $htmlHeadXtra[] = api_get_js('jquery.highlight.js');
450
        $content = GlossaryManager::display_glossary();
451
        break;
452
}
453
454
Display::display_header($tool_name);
455
Display::display_introduction_section(TOOL_GLOSSARY);
456
457
echo $content;
458
459
$extra = '<div id="dialog-confirm" title="'.get_lang('ConfirmYourChoice').'">';
460
$form = new FormValidator(
461
    'report',
462
    'post',
463
    api_get_self().'?'.api_get_cidreq(),
464
    null,
465
    ['class' => 'form-vertical']
466
);
467
$form->addElement(
468
    'radio',
469
    'export_format',
470
    null,
471
    get_lang('ExportAsCSV'),
472
    'csv',
473
    ['id' => 'export_format_csv_label']
474
);
475
$form->addElement(
476
    'radio',
477
    'export_format',
478
    null,
479
    get_lang('ExportAsXLS'),
480
    'xls',
481
    ['id' => 'export_format_xls_label']
482
);
483
$form->addElement(
484
    'radio',
485
    'export_format',
486
    null,
487
    get_lang('ExportToPDF'),
488
    'pdf',
489
    ['id' => 'export_format_pdf_label']
490
);
491
492
$form->setDefaults(['export_format' => 'csv']);
493
$extra .= $form->returnForm();
494
$extra .= '</div>';
495
496
echo $extra;
497
498
Display::display_footer();
499