Test Setup Failed
Push — master ( 4e700f...c7183e )
by Julito
63:12
created

GlossaryManager   F

Complexity

Total Complexity 73

Size/Duplication

Total Lines 702
Duplicated Lines 8.55 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
dl 60
loc 702
rs 3.4716
c 0
b 0
f 0
wmc 73
lcom 2
cbo 6

18 Methods

Rating   Name   Duplication   Size   Complexity  
A get_glossary_terms() 18 18 2
A get_glossary_term_by_glossary_name() 0 19 2
A get_max_glossary_item() 0 18 3
A glossary_exists() 0 21 3
B get_glossary_information() 0 31 4
A displayGlossaryList() 0 13 3
B get_number_glossary_terms() 0 26 4
C get_glossary_data() 0 73 9
A javascript_glossary() 0 12 1
A reorder_glossary() 0 18 2
B move_glossary() 0 39 6
A export_to_pdf() 0 20 2
B save_glossary() 14 58 7
B update_glossary() 0 47 5
B delete_glossary() 0 42 5
A get_glossary_term_by_glossary_id() 15 15 2
C display_glossary() 8 79 10
A actions_filter() 5 18 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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
     * @author Isaac Flores <[email protected]>
22
     * @return array Contain glossary terms
23
     */
24 View Code Duplication
    public static function get_glossary_terms()
25
    {
26
        $glossary_data  = array();
27
        $glossary_table = Database::get_course_table(TABLE_GLOSSARY);
28
        $session_id = api_get_session_id();
29
        $sql_filter = api_get_session_condition($session_id);
30
        $course_id = api_get_course_int_id();
31
32
        $sql = "SELECT glossary_id as id, name, description
33
		        FROM $glossary_table
34
		        WHERE c_id = $course_id $sql_filter";
35
        $rs = Database::query($sql);
36
        while ($row = Database::fetch_array($rs)) {
37
            $glossary_data[] = $row;
38
        }
39
40
        return $glossary_data;
41
    }
42
43
    /**
44
     * Get glossary term by glossary id
45
     * @author Isaac Flores <[email protected]>
46
     * @param int $glossary_id
47
     *
48
     * @return string The glossary description
49
     */
50 View Code Duplication
    public static function get_glossary_term_by_glossary_id($glossary_id)
51
    {
52
        $glossary_table = Database::get_course_table(TABLE_GLOSSARY);
53
        $course_id = api_get_course_int_id();
54
        $sql = "SELECT description FROM $glossary_table
55
                WHERE c_id = $course_id  AND glossary_id =".intval($glossary_id);
56
        $rs = Database::query($sql);
57
        if (Database::num_rows($rs) > 0) {
58
            $row = Database::fetch_array($rs);
59
60
            return $row['description'];
61
        } else {
62
            return '';
63
        }
64
    }
65
66
    /**
67
     * Get glossary term by glossary id
68
     * @author Isaac Flores <[email protected]>
69
     * @param string $glossary_name The glossary term name
70
     *
71
     * @return array The glossary info
72
     */
73
    public static function get_glossary_term_by_glossary_name($glossary_name)
74
    {
75
        $glossary_table = Database::get_course_table(TABLE_GLOSSARY);
76
        $session_id = api_get_session_id();
77
        $course_id = api_get_course_int_id();
78
        $sql_filter = api_get_session_condition($session_id);
79
        $sql = 'SELECT * FROM '.$glossary_table.'
80
		        WHERE
81
		            c_id = '.$course_id.' AND
82
		            name LIKE trim("'.Database::escape_string($glossary_name).'")'.$sql_filter;
83
        $rs = Database::query($sql);
84
        if (Database::num_rows($rs) > 0) {
85
            $row = Database::fetch_array($rs, 'ASSOC');
86
87
            return $row;
88
        }
89
90
        return [];
91
    }
92
93
    /**
94
     * This functions stores the glossary in the database
95
     *
96
     * @param array  $values  Array of title + description (name => $title, description => $comment)
97
     *
98
     * @return mixed   Term id on success, false on failure
99
     *
100
     */
101
    public static function save_glossary($values, $showMessage = true)
102
    {
103
        if (!is_array($values) || !isset($values['name'])) {
104
            return false;
105
        }
106
107
        // Database table definition
108
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
109
110
        // get the maximum display order of all the glossary items
111
        $max_glossary_item = self::get_max_glossary_item();
112
113
        // session_id
114
        $session_id = api_get_session_id();
115
116
        // check if the glossary term already exists
117
        if (self::glossary_exists($values['name'])) {
118
            // display the feedback message
119
            if ($showMessage) {
120
                Display::addFlash(
121
                    Display::return_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'), 'error')
122
                );
123
            }
124
            return false;
125
        } else {
126
            $params = [
127
                'glossary_id' => 0,
128
                'c_id' => api_get_course_int_id(),
129
                'name' => $values['name'],
130
                'description' => $values['description'],
131
                'display_order' => $max_glossary_item + 1,
132
                'session_id' => $session_id,
133
            ];
134
            $id = Database::insert($t_glossary, $params);
135
136 View Code Duplication
            if ($id) {
137
                $sql = "UPDATE $t_glossary SET glossary_id = $id WHERE iid = $id";
138
                Database::query($sql);
139
140
                //insert into item_property
141
                api_item_property_update(
142
                    api_get_course_info(),
143
                    TOOL_GLOSSARY,
144
                    $id,
145
                    'GlossaryAdded',
146
                    api_get_user_id()
147
                );
148
            }
149
            // display the feedback message
150
            if ($showMessage) {
151
                Display::addFlash(
152
                    Display::return_message(get_lang('TermAdded'))
153
                );
154
            }
155
156
            return $id;
157
        }
158
    }
159
160
    /**
161
     * update the information of a glossary term in the database
162
     *
163
     * @param array $values an array containing all the form elements
164
     * @return boolean True on success, false on failure
165
     */
166
    public static function update_glossary($values, $showMessage = true)
167
    {
168
        // Database table definition
169
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
170
        $course_id = api_get_course_int_id();
171
172
        // check if the glossary term already exists
173
        if (self::glossary_exists($values['name'], $values['glossary_id'])) {
174
            // display the feedback message
175
            if ($showMessage) {
176
                Display::addFlash(
177
                    Display::return_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'), 'error')
178
                );
179
            }
180
181
            return false;
182
        } else {
183
            $sql = "UPDATE $t_glossary SET
184
                        name = '".Database::escape_string($values['name'])."',
185
                        description	= '".Database::escape_string($values['description'])."'
186
					WHERE
187
					    c_id = $course_id AND
188
					    glossary_id = ".intval($values['glossary_id']);
189
            $result = Database::query($sql);
190
            if ($result === false) {
191
                return false;
192
            }
193
194
            //update glossary into item_property
195
            api_item_property_update(
196
                api_get_course_info(),
197
                TOOL_GLOSSARY,
198
                intval($values['glossary_id']),
199
                'GlossaryUpdated',
200
                api_get_user_id()
201
            );
202
203
            if ($showMessage) {
204
                // display the feedback message
205
                Display::addFlash(
206
                    Display::return_message(get_lang('TermUpdated'))
207
                );
208
            }
209
        }
210
211
        return true;
212
    }
213
214
    /**
215
     * Get the maximum display order of the glossary item
216
     * @return integer Maximum glossary display order
217
     */
218
    public static function get_max_glossary_item()
219
    {
220
        // Database table definition
221
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
222
        $course_id = api_get_course_int_id();
223
        $get_max = "SELECT MAX(display_order) FROM $t_glossary
224
                    WHERE c_id = $course_id ";
225
        $res_max = Database::query($get_max);
226
        if (Database::num_rows($res_max) == 0) {
227
            return 0;
228
        }
229
        $row = Database::fetch_array($res_max);
230
        if (!empty($row[0])) {
231
            return $row[0];
232
        }
233
234
        return 0;
235
    }
236
237
    /**
238
     * check if the glossary term exists or not
239
     *
240
     * @param string  $term Term to look for
241
     * @param integer  $not_id ID to counter-check if the term exists with this ID as well (optional)
242
     * @return bool    True if term exists
243
     *
244
     */
245
    public static function glossary_exists($term, $not_id = '')
246
    {
247
        // Database table definition
248
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
249
        $course_id = api_get_course_int_id();
250
251
        $sql = "SELECT name FROM $t_glossary
252
                WHERE
253
                    c_id = $course_id AND
254
                    name = '".Database::escape_string($term)."'";
255
        if ($not_id <> '') {
256
            $sql .= " AND glossary_id <> '".intval($not_id)."'";
257
        }
258
        $result = Database::query($sql);
259
        $count = Database::num_rows($result);
260
        if ($count > 0) {
261
            return true;
262
        } else {
263
            return false;
264
        }
265
    }
266
267
    /**
268
     * Get one specific glossary term data
269
     *
270
     * @param integer $glossary_id ID of the flossary term
271
     * @return mixed   Array(glossary_id,name,description,glossary_display_order) or false on error
272
     *
273
     */
274
    public static function get_glossary_information($glossary_id)
275
    {
276
        // Database table definition
277
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
278
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
279
        if (empty($glossary_id)) {
280
            return false;
281
        }
282
        $sql = "SELECT
283
                    g.glossary_id 		as glossary_id,
284
                    g.name 				as name,
285
                    g.description 		as description,
286
                    g.display_order		as glossary_display_order,
287
                    ip.insert_date      as insert_date,
288
                    ip.lastedit_date    as update_date,
289
                    g.session_id
290
                FROM $t_glossary g, $t_item_propery ip
291
                WHERE
292
                    g.glossary_id = ip.ref AND
293
                    tool = '".TOOL_GLOSSARY."' AND
294
                    g.glossary_id = '".intval($glossary_id)."' AND
295
                    g.c_id = ".api_get_course_int_id()." AND
296
                    ip.c_id = ".api_get_course_int_id();
297
298
        $result = Database::query($sql);
299
        if ($result === false || Database::num_rows($result) != 1) {
300
            return false;
301
        }
302
303
        return Database::fetch_array($result);
304
    }
305
306
    /**
307
     * Delete a glossary term (and re-order all the others)
308
     *
309
     * @param integer $glossary_id
310
     * @param bool $showMessage
311
     *
312
     * @return bool    True on success, false on failure
313
     */
314
    public static function delete_glossary($glossary_id, $showMessage = true)
315
    {
316
        // Database table definition
317
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
318
        $course_id = api_get_course_int_id();
319
        $glossaryInfo = self::get_glossary_information($glossary_id);
320
321
        if (empty($glossaryInfo)) {
322
            return false;
323
        }
324
325
        $glossary_id = (int) $glossary_id;
326
327
        $sql = "DELETE FROM $t_glossary 
328
                WHERE 
329
                    c_id = $course_id AND 
330
                    glossary_id='".$glossary_id."'";
331
        $result = Database::query($sql);
332
        if ($result === false || Database::affected_rows($result) < 1) {
333
            return false;
334
        }
335
336
        // update item_property (delete)
337
        api_item_property_update(
338
            api_get_course_info(),
339
            TOOL_GLOSSARY,
340
            $glossary_id,
341
            'delete',
342
            api_get_user_id()
343
        );
344
345
        // reorder the remaining terms
346
        self::reorder_glossary();
347
348
        if ($showMessage) {
349
            Display::addFlash(
350
                Display::return_message(get_lang('TermDeleted').': '.$glossaryInfo['name'])
351
            );
352
        }
353
354
        return true;
355
    }
356
357
    /**
358
     * This is the main function that displays the list or the table with all
359
     * the glossary terms
360
     * @param  string  View ('table' or 'list'). Optional parameter.
361
     * Defaults to 'table' and prefers glossary_view from the session by default.
362
     *
363
     * @return string
364
     */
365
    public static function display_glossary($view = 'table')
366
    {
367
        // This function should always be called with the corresponding
368
        // parameter for view type. Meanwhile, use this cheap trick.
369
        $view = Session::read('glossary_view');
370
        if (empty($view)) {
371
            Session::write('glossary_view', $view);
372
        }
373
        // action links
374
        //echo '<div class="actions">';
375
        $actionsLeft = '';
376 View Code Duplication
        if (api_is_allowed_to_edit(null, true)) {
377
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=addglossary&msg=add?'.api_get_cidreq().'">'.
378
                Display::return_icon('new_glossary_term.png', get_lang('TermAddNew'), '', ICON_SIZE_MEDIUM).'</a>';
379
        }
380
381
        $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=export">'.
382
            Display::return_icon('export_csv.png', get_lang('ExportGlossaryAsCSV'), '', ICON_SIZE_MEDIUM).'</a>';
383 View Code Duplication
        if (api_is_allowed_to_edit(null, true)) {
384
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=import">'.
385
                Display::return_icon('import_csv.png', get_lang('ImportGlossary'), '', ICON_SIZE_MEDIUM).'</a>';
386
        }
387
388
        $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf">'.
389
            Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_MEDIUM).'</a>';
390
391
        if (($view == 'table') || (!isset($view))) {
392
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=list">'.
393
                Display::return_icon('view_detailed.png', get_lang('ListView'), '', ICON_SIZE_MEDIUM).'</a>';
394
        } else {
395
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=table">'.
396
                Display::return_icon('view_text.png', get_lang('TableView'), '', ICON_SIZE_MEDIUM).'</a>';
397
        }
398
399
        /* BUILD SEARCH FORM */
400
        $form = new FormValidator(
401
            'search',
402
            'get',
403
            api_get_self().'?'.api_get_cidreq(),
404
            '',
405
            array(),
406
            FormValidator::LAYOUT_INLINE
407
        );
408
        $form->addText('keyword', '', false, array('class' => 'col-md-2'));
409
        $form->addElement('hidden', 'cidReq', api_get_course_id());
410
        $form->addElement('hidden', 'id_session', api_get_session_id());
411
        $form->addButtonSearch(get_lang('Search'));
412
        $actionsRight = $form->returnForm();
413
414
        $toolbar = Display::toolbarAction(
415
            'toolbar-document',
416
            array($actionsLeft, $actionsRight)
417
        );
418
419
        $content = $toolbar;
420
421
        if (!$view || $view === 'table') {
422
            $table = new SortableTable(
423
                'glossary',
424
                array('GlossaryManager', 'get_number_glossary_terms'),
425
                array('GlossaryManager', 'get_glossary_data'),
426
                0
427
            );
428
            //$table->set_header(0, '', false);
429
            $table->set_header(0, get_lang('TermName'), true);
430
            $table->set_header(1, get_lang('TermDefinition'), true);
431
            if (api_is_allowed_to_edit(null, true)) {
432
                $table->set_header(2, get_lang('Actions'), false, 'width=90px', array('class' => 'td_actions'));
433
                $table->set_column_filter(2, array('GlossaryManager', 'actions_filter'));
434
            }
435
            $content .= $table->return_table();
436
        }
437
438
        if ($view === 'list') {
439
            $content .= self::displayGlossaryList();
440
        }
441
442
        return $content;
443
    }
444
445
    /**
446
     * Display the glossary terms in a list
447
     * @return bool true
448
     */
449
    public static function displayGlossaryList()
450
    {
451
        $glossary_data = self::get_glossary_data(0, 1000, 0, 'ASC');
452
        $content = '';
453
        foreach ($glossary_data as $key => $glossary_item) {
454
            $actions = '';
455
            if (api_is_allowed_to_edit(null, true)) {
456
                $actions = '<div class="pull-right">'.self::actions_filter($glossary_item[2], '', $glossary_item).'</div>';
457
            }
458
            $content .= Display::panel($glossary_item[1], $glossary_item[0].' '.$actions);
459
        }
460
        return $content;
461
    }
462
463
    /**
464
     * Get the number of glossary terms in the course (or course+session)
465
     * @param  int     Session ID filter (optional)
466
     * @return integer Count of glossary terms
467
     *
468
     */
469
    public static function get_number_glossary_terms($session_id = 0)
470
    {
471
        // Database table definition
472
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
473
        $course_id = api_get_course_int_id();
474
        $session_id = intval($session_id);
475
        $sql_filter = api_get_session_condition($session_id, true, true);
476
477
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
478
        $keywordCondition = '';
479
        if (!empty($keyword)) {
480
            $keywordCondition = "AND (name LIKE '%$keyword%' OR description LIKE '%$keyword%')";
481
        }
482
483
        $sql = "SELECT count(glossary_id) as total
484
                FROM $t_glossary
485
                WHERE c_id = $course_id $sql_filter
486
                $keywordCondition ";
487
        $res = Database::query($sql);
488
        if ($res === false) {
489
            return 0;
490
        }
491
        $obj = Database::fetch_object($res);
492
493
        return $obj->total;
494
    }
495
496
    /**
497
     * Get all the data of a glossary
498
     *
499
     * @param int $from From which item
500
     * @param int $number_of_items Number of items to collect
501
     * @param string  $column Name of column on which to order
502
     * @param string $direction  Whether to sort in ascending (ASC) or descending (DESC)
503
     *
504
     * @return array
505
     */
506
    public static function get_glossary_data($from, $number_of_items, $column, $direction)
507
    {
508
        $_user = api_get_user_info();
509
        $view = Session::read('glossary_view');
510
511
        // Database table definition
512
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
513
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
514
515
        if (api_is_allowed_to_edit(null, true)) {
516
            $col2 = " glossary.glossary_id	as col2, ";
517
        } else {
518
            $col2 = ' ';
519
        }
520
521
        //condition for the session
522
        $session_id = api_get_session_id();
523
        $condition_session = api_get_session_condition(
524
            $session_id,
525
            true,
526
            true,
527
            'glossary.session_id'
528
        );
529
530
        $column = intval($column);
531
        if (!in_array($direction, array('DESC', 'ASC'))) {
532
            $direction = 'ASC';
533
        }
534
        $from = intval($from);
535
        $number_of_items = intval($number_of_items);
536
537
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
538
        $keywordCondition = '';
539
        if (!empty($keyword)) {
540
            $keywordCondition = "AND (glossary.name LIKE '%$keyword%' OR glossary.description LIKE '%$keyword%')";
541
        }
542
        $sql = "SELECT
543
                    glossary.name as col0,
544
					glossary.description as col1,
545
					$col2
546
					glossary.session_id
547
				FROM $t_glossary glossary, $t_item_propery ip
548
				WHERE
549
				    glossary.glossary_id = ip.ref AND
550
					tool = '".TOOL_GLOSSARY."' $condition_session AND
551
					glossary.c_id = ".api_get_course_int_id()." AND
552
					ip.c_id = ".api_get_course_int_id()."
553
					$keywordCondition
554
		        ORDER BY col$column $direction
555
		        LIMIT $from,$number_of_items";
556
        $res = Database::query($sql);
557
558
        $return = array();
559
        $array = array();
560
        while ($data = Database::fetch_array($res)) {
561
            // Validation when belongs to a session
562
            $session_img = api_get_session_image($data['session_id'], $_user['status']);
563
            $array[0] = $data[0].$session_img;
564
565
            if (!$view || $view === 'table') {
566
                $array[1] = str_replace(array('<p>', '</p>'), array('', '<br />'), $data[1]);
567
            } else {
568
                $array[1] = $data[1];
569
            }
570
571
            if (api_is_allowed_to_edit(null, true)) {
572
                $array[2] = $data[2];
573
            }
574
            $return[] = $array;
575
        }
576
577
        return $return;
578
    }
579
580
    /**
581
     * Update action icons column
582
     *
583
     * @param integer $glossary_id
584
     * @param array   $url_params Parameters to use to affect links
585
     * @param array   $row The line of results from a query on the glossary table
586
     *
587
     * @return string HTML string for the action icons columns
588
     */
589
    public static function actions_filter($glossary_id, $url_params, $row)
590
    {
591
        $glossary_id = $row[2];
592
        $return = '<a href="'.api_get_self().'?action=edit_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'&msg=edit">'.
593
            Display::return_icon('edit.png', get_lang('Edit'), '', 22).'</a>';
594
        $glossary_data = self::get_glossary_information($glossary_id);
595
        $glossary_term = $glossary_data['name'];
596
        if (api_is_allowed_to_edit(null, true)) {
597 View Code Duplication
            if ($glossary_data['session_id'] == api_get_session_id()) {
598
                $return .= '<a href="'.api_get_self().'?action=delete_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'" onclick="return confirmation(\''.$glossary_term.'\');">'.
599
                    Display::return_icon('delete.png', get_lang('Delete'), '', 22).'</a>';
600
            } else {
601
                $return = get_lang('EditionNotAvailableFromSession');
602
            }
603
        }
604
605
        return $return;
606
    }
607
608
    /**
609
     * a little bit of javascript to display a prettier warning when deleting a term
610
     *
611
     * @return string  HTML string including JavaScript
612
     *
613
     */
614
    public static function javascript_glossary()
615
    {
616
        return "<script>
617
            function confirmation (name) {
618
                if (confirm(\" ".get_lang("TermConfirmDelete")." \"+ name + \" ?\")) {
619
                    return true;
620
                } else {
621
                    return false;
622
                }
623
            }
624
        </script>";
625
    }
626
627
    /**
628
     * Re-order glossary
629
     */
630
    public static function reorder_glossary()
631
    {
632
        // Database table definition
633
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
634
        $course_id = api_get_course_int_id();
635
        $sql = "SELECT * FROM $t_glossary
636
                WHERE c_id = $course_id
637
                ORDER by display_order ASC";
638
        $res = Database::query($sql);
639
640
        $i = 1;
641
        while ($data = Database::fetch_array($res)) {
642
            $sql = "UPDATE $t_glossary SET display_order = $i
643
                    WHERE c_id = $course_id AND glossary_id = '".intval($data['glossary_id'])."'";
644
            Database::query($sql);
645
            $i++;
646
        }
647
    }
648
649
    /**
650
     * Move a glossary term
651
     *
652
     * @param string $direction
653
     * @param string $glossary_id
654
     */
655
    public static function move_glossary($direction, $glossary_id)
656
    {
657
        // Database table definition
658
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
659
660
        // sort direction
661
        if ($direction === 'up') {
662
            $sortorder = 'DESC';
663
        } else {
664
            $sortorder = 'ASC';
665
        }
666
        $course_id = api_get_course_int_id();
667
668
        $sql = "SELECT * FROM $t_glossary
669
                WHERE c_id = $course_id
670
                ORDER BY display_order $sortorder";
671
        $res = Database::query($sql);
672
        $found = false;
673
        while ($row = Database::fetch_array($res)) {
674
            if ($found && empty($next_id)) {
675
                $next_id = $row['glossary_id'];
676
                $next_display_order = $row['display_order'];
677
            }
678
679
            if ($row['glossary_id'] == $glossary_id) {
680
                $current_id = $glossary_id;
681
                $current_display_order = $row['display_order'];
682
                $found = true;
683
            }
684
        }
685
        $sql1 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($next_display_order)."'
686
                 WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($current_id)."'";
687
        $sql2 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($current_display_order)."'
688
                 WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($next_id)."'";
689
        Database::query($sql1);
690
        Database::query($sql2);
691
692
        Display::addFlash(Display::return_message(get_lang('TermMoved')));
693
    }
694
695
    /**
696
     * Export to pdf
697
     */
698
    public static function export_to_pdf()
699
    {
700
        $data = self::get_glossary_data(
701
            0,
702
            self::get_number_glossary_terms(api_get_session_id()),
703
            0,
704
            'ASC'
705
        );
706
        $html = '<html><body>';
707
        $html .= '<h2>'.get_lang('Glossary').'</h2><hr><br><br>';
708
        foreach ($data as $item) {
709
            $term = $item[0];
710
            $description = $item[1];
711
            $html .= '<h4>'.$term.'</h4><p>'.$description.'<p><hr>';
712
        }
713
        $html .= '</body></html>';
714
        $courseCode = api_get_course_id();
715
        $pdf = new PDF();
716
        $pdf->content_to_pdf($html, '', get_lang('Glossary').'_'.$courseCode, $courseCode);
717
    }
718
}
719