Passed
Push — master ( 2a697d...2fc9bb )
by Julito
11:49 queued 02:46
created

GlossaryManager::get_glossary_information()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 3
nop 1
dl 0
loc 31
rs 9.7666
c 0
b 0
f 0
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 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...
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 glossary 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 
300
                INNER JOIN $t_item_propery ip
301
                ON (g.glossary_id = ip.ref AND g.c_id = ip.c_id)
302
                WHERE                    
303
                    tool = '".TOOL_GLOSSARY."' AND
304
                    g.glossary_id = '".intval($glossary_id)."' AND
305
                    g.c_id = ".api_get_course_int_id()." AND
306
                    ip.c_id = ".api_get_course_int_id();
307
308
        $result = Database::query($sql);
309
        if ($result === false || Database::num_rows($result) != 1) {
310
            return false;
311
        }
312
313
        return Database::fetch_array($result);
314
    }
315
316
    /**
317
     * Delete a glossary term (and re-order all the others).
318
     *
319
     * @param int  $glossary_id
320
     * @param bool $showMessage
321
     *
322
     * @return bool True on success, false on failure
323
     */
324
    public static function delete_glossary($glossary_id, $showMessage = true)
325
    {
326
        // Database table definition
327
        $table = Database::get_course_table(TABLE_GLOSSARY);
328
        $course_id = api_get_course_int_id();
329
        $glossaryInfo = self::get_glossary_information($glossary_id);
330
331
        if (empty($glossaryInfo)) {
332
            return false;
333
        }
334
335
        $glossary_id = (int) $glossary_id;
336
337
        $sql = "DELETE FROM $table 
338
                WHERE 
339
                    c_id = $course_id AND 
340
                    glossary_id='".$glossary_id."'";
341
        $result = Database::query($sql);
342
        if ($result === false || Database::affected_rows($result) < 1) {
343
            return false;
344
        }
345
346
        // update item_property (delete)
347
        api_item_property_update(
348
            api_get_course_info(),
349
            TOOL_GLOSSARY,
350
            $glossary_id,
351
            'delete',
352
            api_get_user_id()
353
        );
354
355
        // reorder the remaining terms
356
        self::reorder_glossary();
357
358
        if ($showMessage) {
359
            Display::addFlash(
360
                Display::return_message(get_lang('TermDeleted').': '.$glossaryInfo['name'])
361
            );
362
        }
363
364
        return true;
365
    }
366
367
    /**
368
     * @return string
369
     */
370
    public static function getGlossaryView()
371
    {
372
        $view = Session::read('glossary_view');
373
        if (empty($view)) {
374
            $defaultView = api_get_configuration_value('default_glossary_view');
375
            if (empty($defaultView)) {
376
                $defaultView = 'table';
377
            }
378
379
            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...
380
        } else {
381
            return $view;
382
        }
383
    }
384
385
    /**
386
     * This is the main function that displays the list or the table with all
387
     * the glossary terms
388
     * Defaults to 'table' and prefers glossary_view from the session by default.
389
     *
390
     * @return string
391
     */
392
    public static function display_glossary()
393
    {
394
        // This function should always be called with the corresponding
395
        // parameter for view type. Meanwhile, use this cheap trick.
396
        $view = self::getGlossaryView();
397
        // action links
398
        $actionsLeft = '';
399
        if (api_is_allowed_to_edit(null, true)) {
400
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=addglossary&msg=add?'.api_get_cidreq().'">'.
401
                Display::return_icon('new_glossary_term.png', get_lang('TermAddNew'), '', ICON_SIZE_MEDIUM).'</a>';
402
        }
403
404
        if (api_is_allowed_to_edit(null, true)) {
405
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=import">'.
406
                Display::return_icon('import.png', get_lang('ImportGlossary'), '', ICON_SIZE_MEDIUM).'</a>';
407
        }
408
409
        if (!api_is_anonymous()) {
410
            $actionsLeft .= '<a id="export_opener" href="'.api_get_self().'?'.api_get_cidreq().'&action=export">'.
411
                Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
412
        }
413
414
        if (($view == 'table') || (!isset($view))) {
415
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=list">'.
416
                Display::return_icon('view_detailed.png', get_lang('ListView'), '', ICON_SIZE_MEDIUM).'</a>';
417
        } else {
418
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=table">'.
419
                Display::return_icon('view_text.png', get_lang('TableView'), '', ICON_SIZE_MEDIUM).'</a>';
420
        }
421
422
        if (api_is_allowed_to_edit(true, true, true)) {
423
            $actionsLeft .= Display::url(
424
                Display::return_icon('export_to_documents.png', get_lang('ExportToDocArea'), [], ICON_SIZE_MEDIUM),
425
                api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['action' => 'export_documents'])
426
            );
427
        }
428
429
        $orderList = isset($_GET['order']) ? Database::escape_string($_GET['order']) : '';
430
        if (empty($orderList)) {
431
            $orderList = 'ASC';
432
        }
433
        if (!api_is_allowed_to_edit(true, true, true)) {
434
            if ($orderList === 'ASC') {
435
                $actionsLeft .= Display::url(
436
                    Display::return_icon('falling.png', get_lang('Sort Descending'), [], ICON_SIZE_MEDIUM),
437
                    api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['order' => 'DESC'])
438
                );
439
            } else {
440
                $actionsLeft .= Display::url(
441
                    Display::return_icon('upward.png', get_lang('Sort Ascending'), [], ICON_SIZE_MEDIUM),
442
                    api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['order' => 'ASC'])
443
                );
444
            }
445
        }
446
447
        /* BUILD SEARCH FORM */
448
        $form = new FormValidator(
449
            'search',
450
            'get',
451
            api_get_self().'?'.api_get_cidreq(),
452
            '',
453
            [],
454
            FormValidator::LAYOUT_INLINE
455
        );
456
        $form->addText('keyword', '', false, ['class' => 'col-md-2']);
457
        $form->addElement('hidden', 'cidReq', api_get_course_id());
458
        $form->addElement('hidden', 'id_session', api_get_session_id());
459
        $form->addButtonSearch(get_lang('Search'));
460
        $actionsRight = $form->returnForm();
461
462
        $toolbar = Display::toolbarAction(
463
            'toolbar-document',
464
            [$actionsLeft, $actionsRight]
465
        );
466
467
        $content = $toolbar;
468
469
        if (!$view || $view === 'table') {
470
            $table = new SortableTable(
471
                'glossary',
472
                ['GlossaryManager', 'get_number_glossary_terms'],
473
                ['GlossaryManager', 'get_glossary_data'],
474
                0
475
            );
476
477
            $table->set_header(0, get_lang('TermName'), true);
478
            $table->set_header(1, get_lang('TermDefinition'), true);
479
            if (api_is_allowed_to_edit(null, true)) {
480
                $table->set_header(2, get_lang('Actions'), false, 'width=90px', ['class' => 'td_actions']);
481
                $table->set_column_filter(2, ['GlossaryManager', 'actions_filter']);
482
            }
483
            $content .= $table->return_table();
484
        }
485
486
        if ($view === 'list') {
487
            $content .= self::displayGlossaryList();
488
        }
489
490
        return $content;
491
    }
492
493
    /**
494
     * Display the glossary terms in a list.
495
     *
496
     * @return bool true
497
     */
498
    public static function displayGlossaryList()
499
    {
500
        $glossaryList = self::get_glossary_data(0, 1000, 0, 'ASC');
501
        $content = '';
502
        foreach ($glossaryList as $key => $glossary_item) {
503
            $actions = '';
504
            if (api_is_allowed_to_edit(null, true)) {
505
                $actions = '<div class="float-right">'.self::actions_filter($glossary_item[2], '', $glossary_item).'</div>';
506
            }
507
            $content .= Display::panel($glossary_item[1], $glossary_item[0].' '.$actions);
508
        }
509
510
        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...
511
    }
512
513
    /**
514
     * Get the number of glossary terms in the course (or course+session).
515
     *
516
     * @param  int     Session ID filter (optional)
517
     *
518
     * @return int Count of glossary terms
519
     */
520
    public static function get_number_glossary_terms($session_id = 0)
521
    {
522
        // Database table definition
523
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
524
        $course_id = api_get_course_int_id();
525
        $session_id = intval($session_id);
526
        $sql_filter = api_get_session_condition($session_id, true, true);
527
528
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
529
        $keywordCondition = '';
530
        if (!empty($keyword)) {
531
            $keywordCondition = "AND (name LIKE '%$keyword%' OR description LIKE '%$keyword%')";
532
        }
533
534
        $sql = "SELECT count(glossary_id) as total
535
                FROM $t_glossary
536
                WHERE c_id = $course_id $sql_filter
537
                $keywordCondition ";
538
        $res = Database::query($sql);
539
        if ($res === false) {
540
            return 0;
541
        }
542
        $obj = Database::fetch_object($res);
543
544
        return $obj->total;
545
    }
546
547
    /**
548
     * Get all the data of a glossary.
549
     *
550
     * @param int    $from            From which item
551
     * @param int    $number_of_items Number of items to collect
552
     * @param string $column          Name of column on which to order
553
     * @param string $direction       Whether to sort in ascending (ASC) or descending (DESC)
554
     *
555
     * @return array
556
     */
557
    public static function get_glossary_data(
558
        $from,
559
        $number_of_items,
560
        $column,
561
        $direction
562
    ) {
563
        $_user = api_get_user_info();
564
        $view = self::getGlossaryView();
565
566
        // Database table definition
567
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
568
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
569
570
        if (api_is_allowed_to_edit(null, true)) {
571
            $col2 = " glossary.glossary_id	as col2, ";
572
        } else {
573
            $col2 = ' ';
574
        }
575
576
        //condition for the session
577
        $session_id = api_get_session_id();
578
        $condition_session = api_get_session_condition(
579
            $session_id,
580
            true,
581
            true,
582
            'glossary.session_id'
583
        );
584
585
        $column = intval($column);
586
        if (!in_array($direction, ['DESC', 'ASC'])) {
587
            $direction = 'ASC';
588
        }
589
        $from = intval($from);
590
        $number_of_items = intval($number_of_items);
591
592
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
593
        $keywordCondition = '';
594
        if (!empty($keyword)) {
595
            $keywordCondition = "AND (glossary.name LIKE '%$keyword%' OR glossary.description LIKE '%$keyword%')";
596
        }
597
        $sql = "SELECT
598
                    glossary.name as col0,
599
					glossary.description as col1,
600
					$col2
601
					glossary.session_id
602
				FROM $t_glossary glossary 
603
				INNER JOIN $t_item_propery ip
604
				ON (glossary.glossary_id = ip.ref AND glossary.c_id = ip.c_id)
605
				WHERE				    
606
					tool = '".TOOL_GLOSSARY."' 
607
					$condition_session AND
608
					glossary.c_id = ".api_get_course_int_id()." AND
609
					ip.c_id = ".api_get_course_int_id()."
610
					$keywordCondition
611
		        ORDER BY col$column $direction
612
		        LIMIT $from,$number_of_items";
613
        $res = Database::query($sql);
614
615
        $return = [];
616
        $array = [];
617
        while ($data = Database::fetch_array($res)) {
618
            // Validation when belongs to a session
619
            $session_img = api_get_session_image($data['session_id'], $_user['status']);
620
            $array[0] = $data[0].$session_img;
621
622
            if (!$view || $view === 'table') {
623
                $array[1] = str_replace(['<p>', '</p>'], ['', '<br />'], $data[1]);
624
            } else {
625
                $array[1] = $data[1];
626
            }
627
628
            if (isset($_GET['action']) && $_GET['action'] == 'export') {
629
                $array[1] = api_html_entity_decode($data[1]);
630
            }
631
632
            if (api_is_allowed_to_edit(null, true)) {
633
                $array[2] = $data[2];
634
            }
635
            $return[] = $array;
636
        }
637
638
        return $return;
639
    }
640
641
    /**
642
     * Update action icons column.
643
     *
644
     * @param int   $glossary_id
645
     * @param array $url_params  Parameters to use to affect links
646
     * @param array $row         The line of results from a query on the glossary table
647
     *
648
     * @return string HTML string for the action icons columns
649
     */
650
    public static function actions_filter($glossary_id, $url_params, $row)
651
    {
652
        $glossary_id = $row[2];
653
        $return = '<a href="'.api_get_self().'?action=edit_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'&msg=edit">'.
654
            Display::return_icon('edit.png', get_lang('Edit'), '', 22).'</a>';
655
        $glossary_data = self::get_glossary_information($glossary_id);
656
        $glossary_term = $glossary_data['name'];
657
        if (api_is_allowed_to_edit(null, true)) {
658
            if ($glossary_data['session_id'] == api_get_session_id()) {
659
                $return .= '<a href="'.api_get_self().'?action=delete_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'" onclick="return confirmation(\''.$glossary_term.'\');">'.
660
                    Display::return_icon('delete.png', get_lang('Delete'), '', 22).'</a>';
661
            } else {
662
                $return = get_lang('EditionNotAvailableFromSession');
663
            }
664
        }
665
666
        return $return;
667
    }
668
669
    /**
670
     * a little bit of javascript to display a prettier warning when deleting a term.
671
     *
672
     * @return string HTML string including JavaScript
673
     */
674
    public static function javascript_glossary()
675
    {
676
        return "<script>
677
            function confirmation (name) {
678
                if (confirm(\" ".get_lang("TermConfirmDelete")." \"+ name + \" ?\")) {
679
                    return true;
680
                } else {
681
                    return false;
682
                }
683
            }
684
        </script>";
685
    }
686
687
    /**
688
     * Re-order glossary.
689
     */
690
    public static function reorder_glossary()
691
    {
692
        // Database table definition
693
        $table = Database::get_course_table(TABLE_GLOSSARY);
694
        $course_id = api_get_course_int_id();
695
        $sql = "SELECT * FROM $table
696
                WHERE c_id = $course_id
697
                ORDER by display_order ASC";
698
        $res = Database::query($sql);
699
700
        $i = 1;
701
        while ($data = Database::fetch_array($res)) {
702
            $sql = "UPDATE $table SET display_order = $i
703
                    WHERE c_id = $course_id AND glossary_id = '".intval($data['glossary_id'])."'";
704
            Database::query($sql);
705
            $i++;
706
        }
707
    }
708
709
    /**
710
     * Move a glossary term.
711
     *
712
     * @param string $direction
713
     * @param string $glossary_id
714
     */
715
    public static function move_glossary($direction, $glossary_id)
716
    {
717
        // Database table definition
718
        $table = Database::get_course_table(TABLE_GLOSSARY);
719
720
        // sort direction
721
        if ($direction === 'up') {
722
            $sortorder = 'DESC';
723
        } else {
724
            $sortorder = 'ASC';
725
        }
726
        $course_id = api_get_course_int_id();
727
728
        $sql = "SELECT * FROM $table
729
                WHERE c_id = $course_id
730
                ORDER BY display_order $sortorder";
731
        $res = Database::query($sql);
732
        $found = false;
733
        while ($row = Database::fetch_array($res)) {
734
            if ($found && empty($next_id)) {
735
                $next_id = $row['glossary_id'];
736
                $next_display_order = $row['display_order'];
737
            }
738
739
            if ($row['glossary_id'] == $glossary_id) {
740
                $current_id = $glossary_id;
741
                $current_display_order = $row['display_order'];
742
                $found = true;
743
            }
744
        }
745
746
        $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...
747
                 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...
748
        $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...
749
                 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...
750
        Database::query($sql1);
751
        Database::query($sql2);
752
753
        Display::addFlash(Display::return_message(get_lang('TermMoved')));
754
    }
755
756
    /**
757
     * Export to pdf.
758
     */
759
    public static function export_to_pdf()
760
    {
761
        $data = self::get_glossary_data(
762
            0,
763
            self::get_number_glossary_terms(api_get_session_id()),
764
            0,
765
            'ASC'
766
        );
767
        $template = new Template('', false, false, false, true, false, false);
768
        $layout = $template->get_template('glossary/export_pdf.tpl');
769
        $template->assign('items', $data);
770
771
        $html = $template->fetch($layout);
772
        $courseCode = api_get_course_id();
773
        $pdf = new PDF();
774
        $pdf->content_to_pdf($html, '', get_lang('Glossary').'_'.$courseCode, $courseCode);
775
    }
776
777
    /**
778
     * Generate a PDF with all glossary terms and move file to documents.
779
     *
780
     * @return bool false if there's nothing in the glossary
781
     */
782
    public static function movePdfToDocuments()
783
    {
784
        $sessionId = api_get_session_id();
785
        $courseId = api_get_course_int_id();
786
        $data = self::get_glossary_data(
787
            0,
788
            self::get_number_glossary_terms($sessionId),
789
            0,
790
            'ASC'
791
        );
792
793
        if (!empty($data)) {
794
            $template = new Template('', false, false, false, true, false, false);
795
            $layout = $template->get_template('glossary/export_pdf.tpl');
796
            $template->assign('items', $data);
797
            $fileName = get_lang('Glossary').'-'.api_get_local_time();
798
            $signatures = ['Drh', 'Teacher', 'Date'];
799
800
            $pdf = new PDF(
801
                'A4-P',
802
                'P',
803
                [
804
                    'filename' => $fileName,
805
                    'pdf_title' => $fileName,
806
                    'add_signatures' => $signatures,
807
                ]
808
            );
809
            $pdf->exportFromHtmlToDocumentsArea(
810
                $template->fetch($layout),
811
                $fileName,
812
                $courseId
813
            );
814
815
            return true;
816
        } else {
817
            Display::addFlash(Display::return_message(get_lang('NothingToAdd')));
818
        }
819
820
        return false;
821
    }
822
823
    /**
824
     * @param string $format
825
     */
826
    public static function exportToFormat($format)
827
    {
828
        if ($format == 'pdf') {
829
            self::export_to_pdf();
830
831
            return;
832
        }
833
834
        $data = self::get_glossary_data(
835
            0,
836
            self::get_number_glossary_terms(api_get_session_id()),
837
            0,
838
            'ASC'
839
        );
840
        usort($data, 'sorter');
841
        $list = [];
842
        $list[] = ['term', 'definition'];
843
        $allowStrip = api_get_configuration_value('allow_remove_tags_in_glossary_export');
844
        foreach ($data as $line) {
845
            $definition = $line[1];
846
            if ($allowStrip) {
847
                // htmlspecialchars_decode replace &#39 to '
848
                // strip_tags remove HTML tags
849
                $definition = htmlspecialchars_decode(strip_tags($definition), ENT_QUOTES);
850
            }
851
            $list[] = [$line[0], $definition];
852
        }
853
        $filename = 'glossary_course_'.api_get_course_id();
854
855
        switch ($format) {
856
            case 'csv':
857
                Export::arrayToCsv($list, $filename);
858
                break;
859
            case 'xls':
860
                Export::arrayToXls($list, $filename);
861
                break;
862
        }
863
    }
864
}
865