Completed
Push — master ( 7bef58...5c053f )
by Julito
25:30
created

GlossaryManager   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 826
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 826
rs 1.263
wmc 86

21 Methods

Rating   Name   Duplication   Size   Complexity  
A get_glossary_terms() 0 17 2
A get_glossary_term_by_glossary_name() 0 18 2
B save_glossary() 0 57 7
A getGlossaryView() 0 12 3
A glossary_exists() 0 19 3
A get_glossary_term_by_glossary_id() 0 14 2
B get_glossary_information() 0 30 4
B update_glossary() 0 46 5
A get_max_glossary_item() 0 17 3
B delete_glossary() 0 41 5
A javascript_glossary() 0 5 1
B get_number_glossary_terms() 0 25 4
A displayGlossaryList() 0 13 3
B move_glossary() 0 39 6
A actions_filter() 0 17 3
D get_glossary_data() 0 82 11
D display_glossary() 0 81 11
A export_to_pdf() 0 16 1
A reorder_glossary() 0 16 2
B exportToFormat() 0 36 6
B movePdfToDocuments() 0 39 2

How to fix   Complexity   

Complex Class

Complex classes like GlossaryManager 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 GlossaryManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class GlossaryManager
8
 * This library provides functions for the glossary tool.
9
 * Include/require it in your code to use its functionality.
10
 *
11
 * @author Julio Montoya
12
 * @author Christian Fasanando
13
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium januari 2009, dokeos 1.8.6
14
 *
15
 * @package chamilo.library
16
 */
17
class GlossaryManager
18
{
19
    /**
20
     * Get all glossary terms.
21
     *
22
     * @author Isaac Flores <[email protected]>
23
     *
24
     * @return array Contain glossary terms
25
     */
26
    public static function get_glossary_terms()
27
    {
28
        $glossary_data = [];
29
        $table = Database::get_course_table(TABLE_GLOSSARY);
30
        $session_id = api_get_session_id();
31
        $sql_filter = api_get_session_condition($session_id);
32
        $course_id = api_get_course_int_id();
33
34
        $sql = "SELECT glossary_id as id, name, description
35
		        FROM $table
36
		        WHERE c_id = $course_id $sql_filter";
37
        $rs = Database::query($sql);
38
        while ($row = Database::fetch_array($rs)) {
39
            $glossary_data[] = $row;
40
        }
41
42
        return $glossary_data;
43
    }
44
45
    /**
46
     * Get glossary term by glossary id.
47
     *
48
     * @author Isaac Flores <[email protected]>
49
     *
50
     * @param int $glossary_id
51
     *
52
     * @return string The glossary description
53
     */
54
    public static function get_glossary_term_by_glossary_id($glossary_id)
55
    {
56
        $table = Database::get_course_table(TABLE_GLOSSARY);
57
        $course_id = api_get_course_int_id();
58
        $sql = "SELECT description 
59
                FROM $table
60
                WHERE c_id = $course_id  AND glossary_id =".intval($glossary_id);
61
        $rs = Database::query($sql);
62
        if (Database::num_rows($rs) > 0) {
63
            $row = Database::fetch_array($rs);
64
65
            return $row['description'];
66
        } else {
67
            return '';
68
        }
69
    }
70
71
    /**
72
     * Get glossary term by glossary id.
73
     *
74
     * @author Isaac Flores <[email protected]>
75
     *
76
     * @param string $glossary_name The glossary term name
77
     *
78
     * @return array The glossary info
79
     */
80
    public static function get_glossary_term_by_glossary_name($glossary_name)
81
    {
82
        $table = Database::get_course_table(TABLE_GLOSSARY);
83
        $session_id = api_get_session_id();
84
        $course_id = api_get_course_int_id();
85
        $sql_filter = api_get_session_condition($session_id);
86
        $sql = 'SELECT * FROM '.$table.'
87
		        WHERE
88
		            c_id = '.$course_id.' AND
89
		            name LIKE trim("'.Database::escape_string($glossary_name).'")'.$sql_filter;
90
        $rs = Database::query($sql);
91
        if (Database::num_rows($rs) > 0) {
92
            $row = Database::fetch_array($rs, 'ASSOC');
93
94
            return $row;
95
        }
96
97
        return [];
98
    }
99
100
    /**
101
     * This functions stores the glossary in the database.
102
     *
103
     * @param array $values Array of title + description (name => $title, description => $comment)
104
     *
105
     * @return mixed Term id on success, false on failure
106
     */
107
    public static function save_glossary($values, $showMessage = true)
108
    {
109
        if (!is_array($values) || !isset($values['name'])) {
110
            return false;
111
        }
112
113
        // Database table definition
114
        $table = Database::get_course_table(TABLE_GLOSSARY);
115
116
        // get the maximum display order of all the glossary items
117
        $max_glossary_item = self::get_max_glossary_item();
118
119
        // session_id
120
        $session_id = api_get_session_id();
121
122
        // check if the glossary term already exists
123
        if (self::glossary_exists($values['name'])) {
124
            // display the feedback message
125
            if ($showMessage) {
126
                Display::addFlash(
127
                    Display::return_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'), 'error')
128
                );
129
            }
130
131
            return false;
132
        } else {
133
            $params = [
134
                'glossary_id' => 0,
135
                'c_id' => api_get_course_int_id(),
136
                'name' => $values['name'],
137
                'description' => $values['description'],
138
                'display_order' => $max_glossary_item + 1,
139
                'session_id' => $session_id,
140
            ];
141
            $id = Database::insert($table, $params);
142
143
            if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|false 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...
144
                $sql = "UPDATE $table SET glossary_id = $id WHERE iid = $id";
145
                Database::query($sql);
146
147
                //insert into item_property
148
                api_item_property_update(
149
                    api_get_course_info(),
150
                    TOOL_GLOSSARY,
151
                    $id,
152
                    'GlossaryAdded',
153
                    api_get_user_id()
154
                );
155
            }
156
            // display the feedback message
157
            if ($showMessage) {
158
                Display::addFlash(
159
                    Display::return_message(get_lang('TermAdded'))
160
                );
161
            }
162
163
            return $id;
164
        }
165
    }
166
167
    /**
168
     * update the information of a glossary term in the database.
169
     *
170
     * @param array $values an array containing all the form elements
171
     *
172
     * @return bool True on success, false on failure
173
     */
174
    public static function update_glossary($values, $showMessage = true)
175
    {
176
        // Database table definition
177
        $table = Database::get_course_table(TABLE_GLOSSARY);
178
        $course_id = api_get_course_int_id();
179
180
        // check if the glossary term already exists
181
        if (self::glossary_exists($values['name'], $values['glossary_id'])) {
182
            // display the feedback message
183
            if ($showMessage) {
184
                Display::addFlash(
185
                    Display::return_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'), 'error')
186
                );
187
            }
188
189
            return false;
190
        } else {
191
            $sql = "UPDATE $table SET
192
                        name = '".Database::escape_string($values['name'])."',
193
                        description	= '".Database::escape_string($values['description'])."'
194
					WHERE
195
					    c_id = $course_id AND
196
					    glossary_id = ".intval($values['glossary_id']);
197
            $result = Database::query($sql);
198
            if ($result === false) {
199
                return false;
200
            }
201
202
            //update glossary into item_property
203
            api_item_property_update(
204
                api_get_course_info(),
205
                TOOL_GLOSSARY,
206
                intval($values['glossary_id']),
207
                'GlossaryUpdated',
208
                api_get_user_id()
209
            );
210
211
            if ($showMessage) {
212
                // display the feedback message
213
                Display::addFlash(
214
                    Display::return_message(get_lang('TermUpdated'))
215
                );
216
            }
217
        }
218
219
        return true;
220
    }
221
222
    /**
223
     * Get the maximum display order of the glossary item.
224
     *
225
     * @return int Maximum glossary display order
226
     */
227
    public static function get_max_glossary_item()
228
    {
229
        // Database table definition
230
        $table = Database::get_course_table(TABLE_GLOSSARY);
231
        $course_id = api_get_course_int_id();
232
        $get_max = "SELECT MAX(display_order) FROM $table
233
                    WHERE c_id = $course_id ";
234
        $res_max = Database::query($get_max);
235
        if (Database::num_rows($res_max) == 0) {
236
            return 0;
237
        }
238
        $row = Database::fetch_array($res_max);
239
        if (!empty($row[0])) {
240
            return $row[0];
241
        }
242
243
        return 0;
244
    }
245
246
    /**
247
     * check if the glossary term exists or not.
248
     *
249
     * @param string $term   Term to look for
250
     * @param int    $not_id ID to counter-check if the term exists with this ID as well (optional)
251
     *
252
     * @return bool True if term exists
253
     */
254
    public static function glossary_exists($term, $not_id = '')
255
    {
256
        // Database table definition
257
        $table = Database::get_course_table(TABLE_GLOSSARY);
258
        $course_id = api_get_course_int_id();
259
260
        $sql = "SELECT name FROM $table
261
                WHERE
262
                    c_id = $course_id AND
263
                    name = '".Database::escape_string($term)."'";
264
        if ($not_id != '') {
265
            $sql .= " AND glossary_id <> '".intval($not_id)."'";
266
        }
267
        $result = Database::query($sql);
268
        $count = Database::num_rows($result);
269
        if ($count > 0) {
270
            return true;
271
        } else {
272
            return false;
273
        }
274
    }
275
276
    /**
277
     * Get one specific glossary term data.
278
     *
279
     * @param int $glossary_id ID of the flossary term
280
     *
281
     * @return mixed Array(glossary_id,name,description,glossary_display_order) or false on error
282
     */
283
    public static function get_glossary_information($glossary_id)
284
    {
285
        // Database table definition
286
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
287
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
288
        if (empty($glossary_id)) {
289
            return false;
290
        }
291
        $sql = "SELECT
292
                    g.glossary_id 		as glossary_id,
293
                    g.name 				as name,
294
                    g.description 		as description,
295
                    g.display_order		as glossary_display_order,
296
                    ip.insert_date      as insert_date,
297
                    ip.lastedit_date    as update_date,
298
                    g.session_id
299
                FROM $t_glossary g, $t_item_propery ip
300
                WHERE
301
                    g.glossary_id = ip.ref AND
302
                    tool = '".TOOL_GLOSSARY."' AND
303
                    g.glossary_id = '".intval($glossary_id)."' AND
304
                    g.c_id = ".api_get_course_int_id()." AND
305
                    ip.c_id = ".api_get_course_int_id();
306
307
        $result = Database::query($sql);
308
        if ($result === false || Database::num_rows($result) != 1) {
309
            return false;
310
        }
311
312
        return Database::fetch_array($result);
313
    }
314
315
    /**
316
     * Delete a glossary term (and re-order all the others).
317
     *
318
     * @param int  $glossary_id
319
     * @param bool $showMessage
320
     *
321
     * @return bool True on success, false on failure
322
     */
323
    public static function delete_glossary($glossary_id, $showMessage = true)
324
    {
325
        // Database table definition
326
        $table = Database::get_course_table(TABLE_GLOSSARY);
327
        $course_id = api_get_course_int_id();
328
        $glossaryInfo = self::get_glossary_information($glossary_id);
329
330
        if (empty($glossaryInfo)) {
331
            return false;
332
        }
333
334
        $glossary_id = (int) $glossary_id;
335
336
        $sql = "DELETE FROM $table 
337
                WHERE 
338
                    c_id = $course_id AND 
339
                    glossary_id='".$glossary_id."'";
340
        $result = Database::query($sql);
341
        if ($result === false || Database::affected_rows($result) < 1) {
342
            return false;
343
        }
344
345
        // update item_property (delete)
346
        api_item_property_update(
347
            api_get_course_info(),
348
            TOOL_GLOSSARY,
349
            $glossary_id,
350
            'delete',
351
            api_get_user_id()
352
        );
353
354
        // reorder the remaining terms
355
        self::reorder_glossary();
356
357
        if ($showMessage) {
358
            Display::addFlash(
359
                Display::return_message(get_lang('TermDeleted').': '.$glossaryInfo['name'])
360
            );
361
        }
362
363
        return true;
364
    }
365
366
    /**
367
     * @return string
368
     */
369
    public static function getGlossaryView()
370
    {
371
        $view = Session::read('glossary_view');
372
        if (empty($view)) {
373
            $defaultView = api_get_configuration_value('default_glossary_view');
374
            if (empty($defaultView)) {
375
                $defaultView = 'table';
376
            }
377
378
            return $defaultView;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $defaultView also could return the type boolean which is incompatible with the documented return type string.
Loading history...
379
        } else {
380
            return $view;
381
        }
382
    }
383
384
    /**
385
     * This is the main function that displays the list or the table with all
386
     * the glossary terms
387
     * Defaults to 'table' and prefers glossary_view from the session by default.
388
     *
389
     * @return string
390
     */
391
    public static function display_glossary()
392
    {
393
        // This function should always be called with the corresponding
394
        // parameter for view type. Meanwhile, use this cheap trick.
395
        $view = self::getGlossaryView();
396
        // action links
397
        $actionsLeft = '';
398
        if (api_is_allowed_to_edit(null, true)) {
399
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=addglossary&msg=add?'.api_get_cidreq().'">'.
400
                Display::return_icon('new_glossary_term.png', get_lang('TermAddNew'), '', ICON_SIZE_MEDIUM).'</a>';
401
        }
402
403
        if (api_is_allowed_to_edit(null, true)) {
404
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=import">'.
405
                Display::return_icon('import.png', get_lang('ImportGlossary'), '', ICON_SIZE_MEDIUM).'</a>';
406
        }
407
408
        if (!api_is_anonymous()) {
409
            $actionsLeft .= '<a id="export_opener" href="'.api_get_self().'?'.api_get_cidreq().'&action=export">'.
410
                Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
411
        }
412
413
        if (($view == 'table') || (!isset($view))) {
414
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=list">'.
415
                Display::return_icon('view_detailed.png', get_lang('ListView'), '', ICON_SIZE_MEDIUM).'</a>';
416
        } else {
417
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=table">'.
418
                Display::return_icon('view_text.png', get_lang('TableView'), '', ICON_SIZE_MEDIUM).'</a>';
419
        }
420
421
        if (!api_is_anonymous()) {
422
            $actionsLeft .= Display::url(
423
                Display::return_icon('export_to_documents.png', get_lang('ExportToDocArea'), [], ICON_SIZE_MEDIUM),
424
                api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['action' => 'export_documents'])
425
            );
426
        }
427
428
        /* BUILD SEARCH FORM */
429
        $form = new FormValidator(
430
            'search',
431
            'get',
432
            api_get_self().'?'.api_get_cidreq(),
433
            '',
434
            [],
435
            FormValidator::LAYOUT_INLINE
436
        );
437
        $form->addText('keyword', '', false, ['class' => 'col-md-2']);
438
        $form->addElement('hidden', 'cidReq', api_get_course_id());
439
        $form->addElement('hidden', 'id_session', api_get_session_id());
440
        $form->addButtonSearch(get_lang('Search'));
441
        $actionsRight = $form->returnForm();
442
443
        $toolbar = Display::toolbarAction(
444
            'toolbar-document',
445
            [$actionsLeft, $actionsRight]
446
        );
447
448
        $content = $toolbar;
449
450
        if (!$view || $view === 'table') {
451
            $table = new SortableTable(
452
                'glossary',
453
                ['GlossaryManager', 'get_number_glossary_terms'],
454
                ['GlossaryManager', 'get_glossary_data'],
455
                0
456
            );
457
            //$table->set_header(0, '', false);
458
            $table->set_header(0, get_lang('TermName'), true);
459
            $table->set_header(1, get_lang('TermDefinition'), true);
460
            if (api_is_allowed_to_edit(null, true)) {
461
                $table->set_header(2, get_lang('Actions'), false, 'width=90px', ['class' => 'td_actions']);
462
                $table->set_column_filter(2, ['GlossaryManager', 'actions_filter']);
463
            }
464
            $content .= $table->return_table();
465
        }
466
467
        if ($view === 'list') {
468
            $content .= self::displayGlossaryList();
469
        }
470
471
        return $content;
472
    }
473
474
    /**
475
     * Display the glossary terms in a list.
476
     *
477
     * @return bool true
478
     */
479
    public static function displayGlossaryList()
480
    {
481
        $glossaryList = self::get_glossary_data(0, 1000, 0, 'ASC');
482
        $content = '';
483
        foreach ($glossaryList as $key => $glossary_item) {
484
            $actions = '';
485
            if (api_is_allowed_to_edit(null, true)) {
486
                $actions = '<div class="pull-right">'.self::actions_filter($glossary_item[2], '', $glossary_item).'</div>';
487
            }
488
            $content .= Display::panel($glossary_item[1], $glossary_item[0].' '.$actions);
489
        }
490
491
        return $content;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $content returns the type string which is incompatible with the documented return type boolean.
Loading history...
492
    }
493
494
    /**
495
     * Get the number of glossary terms in the course (or course+session).
496
     *
497
     * @param  int     Session ID filter (optional)
498
     *
499
     * @return int Count of glossary terms
500
     */
501
    public static function get_number_glossary_terms($session_id = 0)
502
    {
503
        // Database table definition
504
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
505
        $course_id = api_get_course_int_id();
506
        $session_id = intval($session_id);
507
        $sql_filter = api_get_session_condition($session_id, true, true);
508
509
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
510
        $keywordCondition = '';
511
        if (!empty($keyword)) {
512
            $keywordCondition = "AND (name LIKE '%$keyword%' OR description LIKE '%$keyword%')";
513
        }
514
515
        $sql = "SELECT count(glossary_id) as total
516
                FROM $t_glossary
517
                WHERE c_id = $course_id $sql_filter
518
                $keywordCondition ";
519
        $res = Database::query($sql);
520
        if ($res === false) {
521
            return 0;
522
        }
523
        $obj = Database::fetch_object($res);
524
525
        return $obj->total;
526
    }
527
528
    /**
529
     * Get all the data of a glossary.
530
     *
531
     * @param int    $from            From which item
532
     * @param int    $number_of_items Number of items to collect
533
     * @param string $column          Name of column on which to order
534
     * @param string $direction       Whether to sort in ascending (ASC) or descending (DESC)
535
     *
536
     * @return array
537
     */
538
    public static function get_glossary_data(
539
        $from,
540
        $number_of_items,
541
        $column,
542
        $direction
543
    ) {
544
        $_user = api_get_user_info();
545
        $view = self::getGlossaryView();
546
547
        // Database table definition
548
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
549
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
550
551
        if (api_is_allowed_to_edit(null, true)) {
552
            $col2 = " glossary.glossary_id	as col2, ";
553
        } else {
554
            $col2 = ' ';
555
        }
556
557
        //condition for the session
558
        $session_id = api_get_session_id();
559
        $condition_session = api_get_session_condition(
560
            $session_id,
561
            true,
562
            true,
563
            'glossary.session_id'
564
        );
565
566
        $column = intval($column);
567
        if (!in_array($direction, ['DESC', 'ASC'])) {
568
            $direction = 'ASC';
569
        }
570
        $from = intval($from);
571
        $number_of_items = intval($number_of_items);
572
573
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
574
        $keywordCondition = '';
575
        if (!empty($keyword)) {
576
            $keywordCondition = "AND (glossary.name LIKE '%$keyword%' OR glossary.description LIKE '%$keyword%')";
577
        }
578
        $sql = "SELECT
579
                    glossary.name as col0,
580
					glossary.description as col1,
581
					$col2
582
					glossary.session_id
583
				FROM $t_glossary glossary 
584
				INNER JOIN $t_item_propery ip
585
				ON (glossary.glossary_id = ip.ref AND glossary.c_id = ip.c_id)
586
				WHERE				    
587
					tool = '".TOOL_GLOSSARY."' 
588
					$condition_session AND
589
					glossary.c_id = ".api_get_course_int_id()." AND
590
					ip.c_id = ".api_get_course_int_id()."
591
					$keywordCondition
592
		        ORDER BY col$column $direction
593
		        LIMIT $from,$number_of_items";
594
        $res = Database::query($sql);
595
596
        $return = [];
597
        $array = [];
598
        while ($data = Database::fetch_array($res)) {
599
            // Validation when belongs to a session
600
            $session_img = api_get_session_image($data['session_id'], $_user['status']);
601
            $array[0] = $data[0].$session_img;
602
603
            if (!$view || $view === 'table') {
604
                $array[1] = str_replace(['<p>', '</p>'], ['', '<br />'], $data[1]);
605
            } else {
606
                $array[1] = $data[1];
607
            }
608
609
            if (isset($_GET['action']) && $_GET['action'] == 'export') {
610
                $array[1] = api_html_entity_decode($data[1]);
611
            }
612
613
            if (api_is_allowed_to_edit(null, true)) {
614
                $array[2] = $data[2];
615
            }
616
            $return[] = $array;
617
        }
618
619
        return $return;
620
    }
621
622
    /**
623
     * Update action icons column.
624
     *
625
     * @param int   $glossary_id
626
     * @param array $url_params  Parameters to use to affect links
627
     * @param array $row         The line of results from a query on the glossary table
628
     *
629
     * @return string HTML string for the action icons columns
630
     */
631
    public static function actions_filter($glossary_id, $url_params, $row)
632
    {
633
        $glossary_id = $row[2];
634
        $return = '<a href="'.api_get_self().'?action=edit_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'&msg=edit">'.
635
            Display::return_icon('edit.png', get_lang('Edit'), '', 22).'</a>';
636
        $glossary_data = self::get_glossary_information($glossary_id);
637
        $glossary_term = $glossary_data['name'];
638
        if (api_is_allowed_to_edit(null, true)) {
639
            if ($glossary_data['session_id'] == api_get_session_id()) {
640
                $return .= '<a href="'.api_get_self().'?action=delete_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'" onclick="return confirmation(\''.$glossary_term.'\');">'.
641
                    Display::return_icon('delete.png', get_lang('Delete'), '', 22).'</a>';
642
            } else {
643
                $return = get_lang('EditionNotAvailableFromSession');
644
            }
645
        }
646
647
        return $return;
648
    }
649
650
    /**
651
     * a little bit of javascript to display a prettier warning when deleting a term.
652
     *
653
     * @return string HTML string including JavaScript
654
     */
655
    public static function javascript_glossary()
656
    {
657
        return "<script>
658
            function confirmation (name) {
659
                if (confirm(\" ".get_lang("TermConfirmDelete")." \"+ name + \" ?\")) {
660
                    return true;
661
                } else {
662
                    return false;
663
                }
664
            }
665
        </script>";
666
    }
667
668
    /**
669
     * Re-order glossary.
670
     */
671
    public static function reorder_glossary()
672
    {
673
        // Database table definition
674
        $table = Database::get_course_table(TABLE_GLOSSARY);
675
        $course_id = api_get_course_int_id();
676
        $sql = "SELECT * FROM $table
677
                WHERE c_id = $course_id
678
                ORDER by display_order ASC";
679
        $res = Database::query($sql);
680
681
        $i = 1;
682
        while ($data = Database::fetch_array($res)) {
683
            $sql = "UPDATE $table SET display_order = $i
684
                    WHERE c_id = $course_id AND glossary_id = '".intval($data['glossary_id'])."'";
685
            Database::query($sql);
686
            $i++;
687
        }
688
    }
689
690
    /**
691
     * Move a glossary term.
692
     *
693
     * @param string $direction
694
     * @param string $glossary_id
695
     */
696
    public static function move_glossary($direction, $glossary_id)
697
    {
698
        // Database table definition
699
        $table = Database::get_course_table(TABLE_GLOSSARY);
700
701
        // sort direction
702
        if ($direction === 'up') {
703
            $sortorder = 'DESC';
704
        } else {
705
            $sortorder = 'ASC';
706
        }
707
        $course_id = api_get_course_int_id();
708
709
        $sql = "SELECT * FROM $table
710
                WHERE c_id = $course_id
711
                ORDER BY display_order $sortorder";
712
        $res = Database::query($sql);
713
        $found = false;
714
        while ($row = Database::fetch_array($res)) {
715
            if ($found && empty($next_id)) {
716
                $next_id = $row['glossary_id'];
717
                $next_display_order = $row['display_order'];
718
            }
719
720
            if ($row['glossary_id'] == $glossary_id) {
721
                $current_id = $glossary_id;
722
                $current_display_order = $row['display_order'];
723
                $found = true;
724
            }
725
        }
726
727
        $sql1 = "UPDATE $table SET display_order = '".Database::escape_string($next_display_order)."'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $next_display_order does not seem to be defined for all execution paths leading up to this point.
Loading history...
728
                 WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($current_id)."'";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
729
        $sql2 = "UPDATE $table SET display_order = '".Database::escape_string($current_display_order)."'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_display_order does not seem to be defined for all execution paths leading up to this point.
Loading history...
730
                 WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($next_id)."'";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $next_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
731
        Database::query($sql1);
732
        Database::query($sql2);
733
734
        Display::addFlash(Display::return_message(get_lang('TermMoved')));
735
    }
736
737
    /**
738
     * Export to pdf.
739
     */
740
    public static function export_to_pdf()
741
    {
742
        $data = self::get_glossary_data(
743
            0,
744
            self::get_number_glossary_terms(api_get_session_id()),
745
            0,
746
            'ASC'
747
        );
748
        $template = new Template('', false, false, false, true, false, false);
749
        $layout = $template->get_template('glossary/export_pdf.tpl');
750
        $template->assign('items', $data);
751
752
        $html = $template->fetch($layout);
753
        $courseCode = api_get_course_id();
754
        $pdf = new PDF();
755
        $pdf->content_to_pdf($html, '', get_lang('Glossary').'_'.$courseCode, $courseCode);
756
    }
757
758
    /**
759
     * Generate a PDF with all glossary terms and move file to documents.
760
     *
761
     * @return bool false if there's nothing in the glossary
762
     */
763
    public static function movePdfToDocuments()
764
    {
765
        $sessionId = api_get_session_id();
766
        $courseId = api_get_course_int_id();
767
        $data = self::get_glossary_data(
768
            0,
769
            self::get_number_glossary_terms($sessionId),
770
            0,
771
            'ASC'
772
        );
773
774
        if (!empty($data)) {
775
            $template = new Template('', false, false, false, true, false, false);
776
            $layout = $template->get_template('glossary/export_pdf.tpl');
777
            $template->assign('items', $data);
778
            $fileName = get_lang('Glossary').'-'.api_get_local_time();
779
            $signatures = ['Drh', 'Teacher', 'Date'];
780
781
            $pdf = new PDF(
782
                'A4-P',
783
                'P',
784
                [
785
                    'filename' => $fileName,
786
                    'pdf_title' => $fileName,
787
                    'add_signatures' => $signatures,
788
                ]
789
            );
790
            $pdf->exportFromHtmlToDocumentsArea(
791
                $template->fetch($layout),
792
                $fileName,
793
                $courseId
794
            );
795
796
            return true;
797
        } else {
798
            Display::addFlash(Display::return_message(get_lang('NothingToAdd')));
799
        }
800
801
        return false;
802
    }
803
804
    /**
805
     * @param string $format
806
     */
807
    public static function exportToFormat($format)
808
    {
809
        if ($format == 'pdf') {
810
            self::export_to_pdf();
811
812
            return;
813
        }
814
815
        $data = GlossaryManager::get_glossary_data(
816
            0,
817
            GlossaryManager::get_number_glossary_terms(api_get_session_id()),
818
            0,
819
            'ASC'
820
        );
821
        usort($data, 'sorter');
822
        $list = [];
823
        $list[] = ['term', 'definition'];
824
        $allowStrip = api_get_configuration_value('allow_remove_tags_in_glossary_export');
825
        foreach ($data as $line) {
826
            $definition = $line[1];
827
            if ($allowStrip) {
828
                // htmlspecialchars_decode replace &#39 to '
829
                // strip_tags remove HTML tags
830
                $definition = htmlspecialchars_decode(strip_tags($definition), ENT_QUOTES);
831
            }
832
            $list[] = [$line[0], $definition];
833
        }
834
        $filename = 'glossary_course_'.api_get_course_id();
835
836
        switch ($format) {
837
            case 'csv':
838
                Export::arrayToCsv($list, $filename);
839
                break;
840
            case 'xls':
841
                Export::arrayToXls($list, $filename);
842
                break;
843
        }
844
    }
845
}
846