Passed
Push — 1.11.x ( 8c9caf...15023c )
by Angel Fernando Quiroz
14:45
created

get_glossary_term_by_glossary_id()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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