Passed
Push — master ( 44ae74...4bbff2 )
by Julito
10:31
created

GlossaryManager::get_glossary_information()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 15
nc 1
nop 1
dl 0
loc 21
rs 9.7666
c 2
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CGlossary;
7
use ChamiloSession as Session;
8
use Doctrine\ORM\NoResultException;
9
10
/**
11
 * Class GlossaryManager
12
 * This library provides functions for the glossary tool.
13
 * Include/require it in your code to use its functionality.
14
 *
15
 * @author Julio Montoya
16
 * @author Christian Fasanando
17
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium januari 2009, dokeos 1.8.6
18
 */
19
class GlossaryManager
20
{
21
    /**
22
     * Get all glossary terms.
23
     *
24
     * @author Isaac Flores <[email protected]>
25
     *
26
     * @return array Contain glossary terms
27
     */
28
    public static function get_glossary_terms()
29
    {
30
        $glossaryData = [];
31
        $repo = Container::getGlossaryRepository();
32
33
        $courseId = api_get_course_int_id();
34
        $sessionId = api_get_session_id();
35
36
        $course = api_get_course_entity($courseId);
37
        $session = api_get_session_entity($sessionId);
38
39
        $glossaries = $repo->getResourcesByCourse($course, $session);
40
        /** @var CGlossary $item */
41
        foreach ($glossaries as $item) {
42
            $glossaryData[] = [
43
                'id' => $item->getIid(),
44
                'name' => $item->getName(),
45
                'description' => $item->getDescription(),
46
            ];
47
        }
48
49
        return $glossaryData;
50
51
        /*
52
        $table = Database::get_course_table(TABLE_GLOSSARY);
53
        $session_id = api_get_session_id();
54
        $sql_filter = api_get_session_condition($session_id);
55
        $course_id = api_get_course_int_id();
56
57
        $sql = "SELECT glossary_id as id, name, description
58
                FROM $table
59
                WHERE c_id = $course_id $sql_filter";
60
        $rs = Database::query($sql);
61
        while ($row = Database::fetch_array($rs)) {
62
            $glossary_data[] = $row;
63
        }
64
65
        return $glossary_data;
66
        */
67
    }
68
69
    /**
70
     * Get glossary description by glossary id.
71
     *
72
     * @author Isaac Flores <[email protected]>
73
     *
74
     * @param int $glossary_id
75
     *
76
     * @return string The glossary description
77
     */
78
    public static function get_glossary_term_by_glossary_id($glossary_id)
79
    {
80
        $repo = Container::getGlossaryRepository();
81
        /** @var CGlossary $glossary */
82
        $glossary = $repo->find($glossary_id);
83
        $description = '';
84
        if (null !== $glossary) {
85
            $description = $glossary->getDescription();
86
        }
87
88
        return $description;
89
90
        /*
91
        $table = Database::get_course_table(TABLE_GLOSSARY);
92
        $course_id = api_get_course_int_id();
93
        $glossary_id = (int) $glossary_id;
94
95
        $sql = "SELECT description
96
                FROM $table
97
                WHERE c_id = $course_id  AND glossary_id =".$glossary_id;
98
        $rs = Database::query($sql);
99
        if (Database::num_rows($rs) > 0) {
100
            $row = Database::fetch_array($rs);
101
102
            return $row['description'];
103
        }
104
105
        return '';
106
        */
107
    }
108
109
    /**
110
     * Get glossary term by glossary id.
111
     *
112
     * @author Isaac Flores <[email protected]>
113
     *
114
     * @param string $name The glossary term name
115
     *
116
     * @return array The glossary info
117
     */
118
    public static function get_glossary_term_by_glossary_name($name)
119
    {
120
        // @todo Filter by like on ORM
121
        $table = Database::get_course_table(TABLE_GLOSSARY);
122
        $sessionId = api_get_session_id();
123
        $course_id = api_get_course_int_id();
124
        $sessionCondition = api_get_session_condition($sessionId);
125
126
        $glossaryName = Security::remove_XSS($name);
127
        $glossaryName = api_convert_encoding($glossaryName, 'UTF-8', 'UTF-8');
128
        $glossaryName = trim($glossaryName);
129
        $parsed = $glossaryName;
130
131
        if (api_get_configuration_value('save_titles_as_html')) {
132
            $parsed = api_htmlentities($parsed);
133
            $parsed = "%$parsed%";
134
        }
135
136
        $sql = "SELECT * FROM $table
137
		        WHERE
138
		            c_id = $course_id AND
139
		            (
140
		                name LIKE '".Database::escape_string($glossaryName)."'
141
		                OR
142
		                name LIKE '".Database::escape_string($parsed)."'
143
                    )
144
                    $sessionCondition
145
                LIMIT 1
146
                ";
147
        $rs = Database::query($sql);
148
149
        if (Database::num_rows($rs) > 0) {
150
            return Database::fetch_array($rs, 'ASSOC');
151
        }
152
153
        return [];
154
    }
155
156
    /**
157
     * This functions stores the glossary in the database.
158
     *
159
     * @param array $values Array of title + description (name => $title, description => $comment)
160
     *
161
     * @return mixed Term id on success, false on failure
162
     */
163
    public static function save_glossary($values, $showMessage = true)
164
    {
165
        if (!is_array($values) || !isset($values['name'])) {
166
            return false;
167
        }
168
169
        // get the maximum display order of all the glossary items
170
        $max_glossary_item = self::get_max_glossary_item();
171
172
        // check if the glossary term already exists
173
        if (self::glossary_exists($values['name'])) {
174
            // display the feedback message
175
            if ($showMessage) {
176
                Display::addFlash(
177
                    Display::return_message(
178
                        get_lang('This glossary term already exists. Please change the term name.'),
179
                        'error'
180
                    )
181
                );
182
            }
183
184
            return false;
185
        } else {
186
            $glossary = new CGlossary();
187
188
            $courseId = api_get_course_int_id();
189
            $sessionId = api_get_session_id();
190
191
            $glossary
192
                ->setName($values['name'])
193
                ->setDescription($values['description'])
194
                ->setDisplayOrder($max_glossary_item + 1)
195
            ;
196
197
            $course = api_get_course_entity($courseId);
198
            $session = api_get_session_entity($sessionId);
199
            $glossary->setParent($course);
200
            $glossary->addCourseLink($course, $session);
201
202
            $repo = Container::getGlossaryRepository();
203
            $repo->create($glossary);
204
            /*
205
            throw new Exception('implement resources');
206
207
208
            // Database table definition
209
            $table = Database::get_course_table(TABLE_GLOSSARY);
210
            $params = [
211
                'glossary_id' => 0,
212
                'c_id' => api_get_course_int_id(),
213
                'name' => $values['name'],
214
                'description' => $values['description'],
215
                'display_order' => $max_glossary_item + 1,
216
                'session_id' => $session_id,
217
            ];
218
            $id = Database::insert($table, $params);
219
220
            if ($id) {
221
                $sql = "UPDATE $table SET glossary_id = $id WHERE iid = $id";
222
                Database::query($sql);
223
224
                //insert into item_property
225
                /*api_item_property_update(
226
                    api_get_course_info(),
227
                    TOOL_GLOSSARY,
228
                    $id,
229
                    'GlossaryAdded',
230
                    api_get_user_id()
231
                );* /
232
            }
233
            */
234
            // display the feedback message
235
            if ($showMessage) {
236
                Display::addFlash(
237
                    Display::return_message(get_lang('Term added'))
238
                );
239
            }
240
241
            return $glossary;
242
        }
243
    }
244
245
    /**
246
     * update the information of a glossary term in the database.
247
     *
248
     * @param array $values an array containing all the form elements
249
     *
250
     * @return bool True on success, false on failure
251
     */
252
    public static function update_glossary($values, $showMessage = true)
253
    {
254
        /*
255
        // Database table definition
256
        $table = Database::get_course_table(TABLE_GLOSSARY);
257
        $course_id = api_get_course_int_id();
258
259
        */
260
        // check if the glossary term already exists
261
        if (self::glossary_exists($values['name'], $values['glossary_id'])) {
262
            // display the feedback message
263
            if ($showMessage) {
264
                Display::addFlash(
265
                    Display::return_message(
266
                        get_lang('This glossary term already exists. Please change the term name.'),
267
                        'error'
268
                    )
269
                );
270
            }
271
272
            return false;
273
        } else {
274
            $repo = Container::getGlossaryRepository();
275
276
            /** @var CGlossary $glossary */
277
            $glossary = $repo->find($values['glossary_id']);
278
            if (null !== $glossary) {
279
                $glossary
280
                    ->setName($values['name'])
281
                    ->setDescription($values['description']);
282
                $repo->update($glossary);
283
            }
284
            /*
285
286
            $sql = "UPDATE $table SET
287
                        name = '".Database::escape_string($values['name'])."',
288
                        description	= '".Database::escape_string($values['description'])."'
289
                    WHERE
290
                        c_id = $course_id AND
291
                        glossary_id = ".intval($values['glossary_id']);
292
            $result = Database::query($sql);
293
            if (false === $result) {
294
                return false;
295
            }
296
297
            //update glossary into item_property
298
            /*api_item_property_update(
299
                api_get_course_info(),
300
                TOOL_GLOSSARY,
301
                intval($values['glossary_id']),
302
                'GlossaryUpdated',
303
                api_get_user_id()
304
            );* /
305
306
            */
307
            if ($showMessage) {
308
                // display the feedback message
309
                Display::addFlash(
310
                    Display::return_message(get_lang('Term updated'))
311
                );
312
            }
313
        }
314
315
        return true;
316
    }
317
318
    /**
319
     * Get the maximum display order of the glossary item.
320
     *
321
     * @return int Maximum glossary display order
322
     */
323
    public static function get_max_glossary_item()
324
    {
325
        // @todo get max by orm
326
        /*
327
        $repo = Container::getGlossaryRepository();
328
329
        $findArray  = [
330
            'cId' => api_get_course_int_id(),
331
            'sessionId' => api_get_session_id(),
332
            'name'=>$term,
333
        ];
334
        $glossary = $repo->findBy($findArray);
335
        */
336
        // Database table definition
337
338
        $repo = Container::getGlossaryRepository();
339
340
        $courseId = api_get_course_int_id();
341
        $sessionId = api_get_session_id();
342
343
        $course = api_get_course_entity($courseId);
344
        $session = api_get_session_entity($sessionId);
345
        $qb = $repo->getResourcesByCourse($course, $session);
346
347
        try {
348
            $count = $qb->select('COUNT(resource)')->getQuery()->getSingleScalarResult();
349
        } catch (NoResultException $e) {
350
            $count = 0;
351
        }
352
353
        return $count;
354
355
        $table = Database::get_course_table(TABLE_GLOSSARY);
0 ignored issues
show
Unused Code introduced by
$table = Database::get_c...e_table(TABLE_GLOSSARY) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
356
        $course_id = api_get_course_int_id();
357
        $get_max = "SELECT MAX(display_order) FROM $table
358
                    WHERE c_id = $course_id ";
359
        $res_max = Database::query($get_max);
360
        if (0 == Database::num_rows($res_max)) {
361
            return 0;
362
        }
363
        $row = Database::fetch_array($res_max);
364
        if (!empty($row[0])) {
365
            return $row[0];
366
        }
367
368
        return 0;
369
    }
370
371
    /**
372
     * check if the glossary term exists or not.
373
     *
374
     * @param string $term   Term to look for
375
     * @param int    $not_id ID to counter-check if the term exists with this ID as well (optional)
376
     *
377
     * @return bool True if term exists
378
     */
379
    public static function glossary_exists($term, $not_id = 0)
380
    {
381
        $repo = Container::getGlossaryRepository();
382
383
        $courseId = api_get_course_int_id();
384
        $sessionId = api_get_session_id();
385
386
        $course = api_get_course_entity($courseId);
387
        $session = api_get_session_entity($sessionId);
388
389
        $qb = $repo->getResourcesByCourse($course, $session);
390
        $glossaries = $qb->getQuery()->getResult();
391
392
        if (0 === count($glossaries)) {
393
            return false;
394
        }
395
396
        /** @var CGlossary $item */
397
        foreach ($glossaries as $item) {
398
            if ($term == $item->getName() && $not_id != $item->getIid()) {
399
                return true;
400
            }
401
        }
402
403
        return false;
404
        /*
405
406
        // Database table definition
407
        $table = Database::get_course_table(TABLE_GLOSSARY);
408
        $course_id = api_get_course_int_id();
409
410
        $sql = "SELECT name FROM $table
411
                WHERE
412
                    c_id = $course_id AND
413
                    name = '".Database::escape_string($term)."'";
414
        if ('' != $not_id) {
415
            $sql .= " AND glossary_id <> '".intval($not_id)."'";
416
        }
417
        $result = Database::query($sql);
418
        $count = Database::num_rows($result);
419
        if ($count > 0) {
420
            return true;
421
        } else {
422
            return false;
423
        }
424
        */
425
    }
426
427
    /**
428
     * Delete a glossary term (and re-order all the others).
429
     *
430
     * @param int  $glossary_id
431
     * @param bool $showMessage
432
     *
433
     * @return bool True on success, false on failure
434
     */
435
    public static function delete_glossary($glossary_id, $showMessage = true)
436
    {
437
        $repo = Container::getGlossaryRepository();
438
        /** @var CGlossary $glossary */
439
        $glossary = $repo->find($glossary_id);
440
        if (null !== $glossary) {
441
            $repo->delete($glossary);
442
        } else {
443
            $showMessage = false;
444
        }
445
446
        /*
447
         // update item_property (delete)
448
        api_item_property_update(
449
            api_get_course_info(),
450
            TOOL_GLOSSARY,
451
            $glossary_id,
452
            'delete',
453
            api_get_user_id()
454
        );
455
        */
456
        // reorder the remaining terms
457
        self::reorder_glossary();
458
459
        if ($showMessage) {
460
            Display::addFlash(
461
                Display::return_message(
462
                    get_lang('Term removed').': '.Security::remove_XSS($glossary->getName()),
463
                    'normal',
464
                    false
465
                )
466
            );
467
        }
468
469
        return true;
470
    }
471
472
    /**
473
     * @return string
474
     */
475
    public static function getGlossaryView()
476
    {
477
        $view = Session::read('glossary_view');
478
        if (empty($view)) {
479
            $defaultView = api_get_configuration_value('default_glossary_view');
480
            if (empty($defaultView)) {
481
                $defaultView = 'table';
482
            }
483
484
            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...
485
        }
486
487
        return $view;
488
    }
489
490
    /**
491
     * This is the main function that displays the list or the table with all
492
     * the glossary terms
493
     * Defaults to 'table' and prefers glossary_view from the session by default.
494
     *
495
     * @return string
496
     */
497
    public static function display_glossary()
498
    {
499
        // This function should always be called with the corresponding
500
        // parameter for view type. Meanwhile, use this cheap trick.
501
        $view = self::getGlossaryView();
502
        // action links
503
        $actionsLeft = '';
504
        if (api_is_allowed_to_edit(null, true)) {
505
            $addIcon = Display::return_icon(
506
                'new_glossary_term.png',
507
                get_lang('Add new glossary term'),
508
                '',
509
                ICON_SIZE_MEDIUM
510
            );
511
            $actionsLeft .= '<a
512
                href="index.php?'.api_get_cidreq().'&action=addglossary&msg=add?'.api_get_cidreq().'">'.$addIcon.'</a>';
513
        }
514
515
        if (api_is_allowed_to_edit(null, true)) {
516
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=import">'.
517
                Display::return_icon('import.png', get_lang('Import glossary'), '', ICON_SIZE_MEDIUM).'</a>';
518
        }
519
520
        if (!api_is_anonymous()) {
521
            $actionsLeft .= '<a id="export_opener" href="'.api_get_self().'?'.api_get_cidreq().'&action=export">'.
522
                Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
523
        }
524
525
        if ('table' === $view || !isset($view)) {
526
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=list">'.
527
                Display::return_icon('view_detailed.png', get_lang('List view'), '', ICON_SIZE_MEDIUM).'</a>';
528
        } else {
529
            $actionsLeft .= '<a href="index.php?'.api_get_cidreq().'&action=changeview&view=table">'.
530
                Display::return_icon('view_text.png', get_lang('Table view'), '', ICON_SIZE_MEDIUM).'</a>';
531
        }
532
533
        if (api_is_allowed_to_edit(true, true, true)) {
534
            $exportIcon = Display::return_icon(
535
                'export_to_documents.png',
536
                get_lang('Export latest version of this page to Documents'),
537
                [],
538
                ICON_SIZE_MEDIUM
539
            );
540
            $actionsLeft .= Display::url(
541
                $exportIcon,
542
                api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['action' => 'export_documents'])
543
            );
544
        }
545
546
        $orderList = isset($_GET['order']) ? Database::escape_string($_GET['order']) : '';
547
        if (empty($orderList)) {
548
            $orderList = 'ASC';
549
        }
550
        if (!api_is_allowed_to_edit(true, true, true)) {
551
            if ('ASC' === $orderList) {
552
                $actionsLeft .= Display::url(
553
                    Display::return_icon('falling.png', get_lang('Sort Descending'), [], ICON_SIZE_MEDIUM),
554
                    api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['order' => 'DESC'])
555
                );
556
            } else {
557
                $actionsLeft .= Display::url(
558
                    Display::return_icon('upward.png', get_lang('Sort Ascending'), [], ICON_SIZE_MEDIUM),
559
                    api_get_self().'?'.api_get_cidreq().'&'.http_build_query(['order' => 'ASC'])
560
                );
561
            }
562
        }
563
564
        /* BUILD SEARCH FORM */
565
        $form = new FormValidator(
566
            'search',
567
            'get',
568
            api_get_self().'?'.api_get_cidreq(),
569
            '',
570
            [],
571
            FormValidator::LAYOUT_INLINE
572
        );
573
        $form->addText('keyword', '', false, ['class' => '']);
574
        $form->addElement('hidden', 'cidReq', api_get_course_id());
575
        $form->addElement('hidden', 'id_session', api_get_session_id());
576
        $form->addButtonSearch(get_lang('Search'));
577
        $actionsRight = $form->returnForm();
578
579
        $toolbar = Display::toolbarAction(
580
            'toolbar-document',
581
            [$actionsLeft, $actionsRight]
582
        );
583
584
        $content = $toolbar;
585
586
        $items = self::get_number_glossary_terms();
587
        if (0 != $items && (!$view || 'table' === $view)) {
588
            // @todo Table haven't paggination
589
            $table = new SortableTable(
590
                'glossary',
591
                ['GlossaryManager', 'get_number_glossary_terms'],
592
                ['GlossaryManager', 'get_glossary_data'],
593
                0
594
            );
595
            $table->set_header(0, get_lang('Term'), true);
596
            $table->set_header(1, get_lang('Term definition'), true);
597
            if (api_is_allowed_to_edit(null, true)) {
598
                $table->set_header(2, get_lang('Detail'), false, 'width=90px', ['class' => 'td_actions']);
599
                $table->set_column_filter(2, ['GlossaryManager', 'actions_filter']);
600
            }
601
            $content .= $table->return_table();
602
        }
603
604
        if ('list' === $view) {
605
            $content .= self::displayGlossaryList();
606
        }
607
608
        return $content;
609
    }
610
611
    /**
612
     * Display the glossary terms in a list.
613
     *
614
     * @return bool true
615
     */
616
    public static function displayGlossaryList()
617
    {
618
        $glossaryList = self::get_glossary_data(0, 1000, 0, 'ASC');
619
        $content = '';
620
        foreach ($glossaryList as $key => $glossary_item) {
621
            $actions = '';
622
            if (api_is_allowed_to_edit(null, true)) {
623
                $actions = '<div class="pull-right">'.
624
                        self::actions_filter($glossary_item[2], '', $glossary_item).'</div>';
625
            }
626
            $content .= Display::panel($glossary_item[1], $glossary_item[0].' '.$actions);
627
        }
628
629
        return $content;
630
    }
631
632
    /**
633
     * Get the number of glossary terms in the course (or course+session).
634
     *
635
     * @param  int     Session ID filter (optional)
636
     *
637
     * @return int Count of glossary terms
638
     */
639
    public static function get_number_glossary_terms($sessionId = 0)
640
    {
641
        // @todo Filter by keywork dont work
642
        $repo = Container::getGlossaryRepository();
643
644
        $courseId = api_get_course_int_id();
645
        $sessionId = !empty($sessionId) ? $sessionId : api_get_session_id();
646
647
        $course = api_get_course_entity($courseId);
648
        $session = api_get_session_entity($sessionId);
649
650
        $qb = $repo->getResourcesByCourse($course, $session);
651
        /*
652
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
653
        if(!empty($keyword)){
654
            $qb->andWhere(
655
                $qb->expr()->like('resource.name',':keyword')
656
            )->andWhere(
657
                $qb->expr()->like('resource.description',':keyword')
658
            )->setParameter('keyword', '%'.$keyword.'%');
659
        }
660
        */
661
662
        try {
663
            $count = $qb->select('COUNT(resource)')->getQuery()->getSingleScalarResult();
664
        } catch (NoResultException $e) {
665
            $count = 0;
666
        }
667
668
        return $count;
669
        /*
670
671
        // Database table definition
672
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
673
        $course_id = api_get_course_int_id();
674
        $session_id = (int) $session_id;
675
        $sql_filter = api_get_session_condition($session_id, true, true);
676
677
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
678
        $keywordCondition = '';
679
        if (!empty($keyword)) {
680
            $keywordCondition = "AND (name LIKE '%$keyword%' OR description LIKE '%$keyword%')";
681
        }
682
683
        $sql = "SELECT count(glossary_id) as total
684
                FROM $t_glossary
685
                WHERE c_id = $course_id $sql_filter
686
                $keywordCondition ";
687
        $res = Database::query($sql);
688
        if (false === $res) {
689
            return 0;
690
        }
691
        $obj = Database::fetch_object($res);
692
693
        return $obj->total;
694
        */
695
    }
696
697
    /**
698
     * Get all the data of a glossary.
699
     *
700
     * @param int    $from            From which item
701
     * @param int    $number_of_items Number of items to collect
702
     * @param string $column          Name of column on which to order
703
     * @param string $direction       Whether to sort in ascending (ASC) or descending (DESC)
704
     *
705
     * @return array
706
     */
707
    public static function get_glossary_data(
708
        $from,
709
        $number_of_items,
710
        $column,
711
        $direction
712
    ) {
713
        // @todo Table haven't paggination
714
        // @todo Filter by keywork dont work
715
        $repo = Container::getGlossaryRepository();
716
        $courseId = api_get_course_int_id();
717
        $sessionId = api_get_session_id();
718
719
        $course = api_get_course_entity($courseId);
720
        $session = api_get_session_entity($sessionId);
721
722
        $qb = $repo->getResourcesByCourse($course, $session);
723
724
        /*
725
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
726
        if(!empty($keyword)){
727
            $qb->andWhere(
728
                $qb->expr()->like('resource.name',':keyword')
729
730
            )->andWhere(
731
                $qb->expr()->like('resource.description',':keyword')
732
733
            )->setParameter('keyword', '%'.$keyword.'%');
734
        }
735
        */
736
737
        $return = [];
738
        $array = [];
739
        $_user = api_get_user_info();
740
        $view = self::getGlossaryView();
741
        $glossaries = $qb->getQuery()->getResult();
742
743
        foreach ($glossaries as $glossary) {
744
            /** @var CGlossary $glossary */
745
            $session_img = api_get_session_image($sessionId, $_user['status']);
746
            $array[0] = $glossary->getName().$session_img;
747
            if (!$view || 'table' === $view) {
748
                $array[1] = str_replace(['<p>', '</p>'], ['', '<br />'], $glossary->getDescription());
749
            } else {
750
                $array[1] = $glossary->getDescription();
751
            }
752
753
            if (isset($_GET['action']) && 'export' === $_GET['action']) {
754
                $array[1] = api_html_entity_decode($glossary->getDescription());
755
            }
756
            if (api_is_allowed_to_edit(null, true)) {
757
                $array[2] = $glossary->getIid();
758
            }
759
            $return[] = $array;
760
        }
761
762
        return $return;
763
        /*
764
        $_user = api_get_user_info();
765
        $view = self::getGlossaryView();
766
767
        // Database table definition
768
        $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
769
        $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
770
771
        if (api_is_allowed_to_edit(null, true)) {
772
            $col2 = ' glossary.glossary_id	as col2, ';
773
        } else {
774
            $col2 = ' ';
775
        }
776
777
        // Condition for the session
778
        $session_id = api_get_session_id();
779
        $condition_session = api_get_session_condition(
780
            $session_id,
781
            true,
782
            true,
783
            'glossary.session_id'
784
        );
785
786
        $column = (int) $column;
787
        $from = (int) $from;
788
        $number_of_items = (int) $number_of_items;
789
790
        if (!in_array($direction, ['DESC', 'ASC'])) {
791
            $direction = 'ASC';
792
        }
793
794
        $keyword = isset($_GET['keyword']) ? Database::escape_string($_GET['keyword']) : '';
795
        $keywordCondition = '';
796
        if (!empty($keyword)) {
797
            $keywordCondition = "AND (glossary.name LIKE '%$keyword%' OR glossary.description LIKE '%$keyword%')";
798
        }
799
        $sql = "SELECT
800
                    glossary.name as col0,
801
                    glossary.description as col1,
802
                    $col2
803
                    glossary.session_id
804
                FROM $t_glossary glossary
805
                INNER JOIN $t_item_propery ip
806
                ON (glossary.glossary_id = ip.ref AND glossary.c_id = ip.c_id)
807
                WHERE
808
                    tool = '".TOOL_GLOSSARY."'
809
                    $condition_session AND
810
                    glossary.c_id = ".api_get_course_int_id()." AND
811
                    ip.c_id = ".api_get_course_int_id()."
812
                    $keywordCondition
813
                ORDER BY col$column $direction
814
                LIMIT $from, $number_of_items";
815
        $res = Database::query($sql);
816
817
        $return = [];
818
        $array = [];
819
        while ($data = Database::fetch_array($res)) {
820
            // Validation when belongs to a session
821
            $session_img = api_get_session_image($data['session_id'], $_user['status']);
822
            $array[0] = $data[0].$session_img;
823
824
            if (!$view || 'table' === $view) {
825
                $array[1] = str_replace(['<p>', '</p>'], ['', '<br />'], $data[1]);
826
            } else {
827
                $array[1] = $data[1];
828
            }
829
830
            if (isset($_GET['action']) && 'export' === $_GET['action']) {
831
                $array[1] = api_html_entity_decode($data[1]);
832
            }
833
834
            if (api_is_allowed_to_edit(null, true)) {
835
                $array[2] = $data[2];
836
            }
837
            $return[] = $array;
838
        }
839
840
        return $return;
841
        */
842
    }
843
844
    /**
845
     * Update action icons column.
846
     *
847
     * @param int   $glossary_id
848
     * @param array $url_params  Parameters to use to affect links
849
     * @param array $row         The line of results from a query on the glossary table
850
     *
851
     * @return string HTML string for the action icons columns
852
     */
853
    public static function actions_filter($glossary_id, $url_params, $row)
854
    {
855
        $glossary_id = $row[2];
856
        $return = '<a href="'.api_get_self().'?action=edit_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'&msg=edit">'.
857
            Display::return_icon('edit.png', get_lang('Edit'), '', 22).'</a>';
858
        $repo = Container::getGlossaryRepository();
859
        /** @var CGlossary $glossaryData */
860
        $glossaryData = $repo->find($glossary_id);
861
        $glossaryTerm = Security::remove_XSS(strip_tags($glossaryData->getName()));
862
        if (api_is_allowed_to_edit(null, true)) {
863
            $return .= '<a
864
                href="'.api_get_self().'?action=delete_glossary&glossary_id='.$glossary_id.'&'.api_get_cidreq().'"
865
                onclick="return confirmation(\''.$glossaryTerm.'\');">'.
866
                Display::return_icon('delete.png', get_lang('Delete'), '', 22).'</a>';
867
            /*
868
             * if ($glossaryData->getSessionId() == api_get_session_id()) {
869
            } else {
870
                $return = get_lang('Edition not available from the session, please edit from the basic course.');
871
            }
872
            */
873
        }
874
875
        return $return;
876
    }
877
878
    /**
879
     * a little bit of javascript to display a prettier warning when deleting a term.
880
     *
881
     * @return string HTML string including JavaScript
882
     */
883
    public static function javascript_glossary()
884
    {
885
        return "<script>
886
            function confirmation (name) {
887
                if (confirm(\" ".get_lang("Do you really want to delete this term")." \"+ name + \" ?\")) {
888
                    return true;
889
                } else {
890
                    return false;
891
                }
892
            }
893
        </script>";
894
    }
895
896
    /**
897
     * Re-order glossary.
898
     */
899
    public static function reorder_glossary()
900
    {
901
        $repo = Container::getGlossaryRepository();
902
903
        $courseId = api_get_course_int_id();
904
        $sessionId = api_get_session_id();
905
906
        $course = api_get_course_entity($courseId);
907
        $session = api_get_session_entity($sessionId);
908
909
        $glossaries = $repo->getResourcesByCourse($course, $session);
910
        $i = 1;
911
        /** @var CGlossary $item */
912
        foreach ($glossaries as $item) {
913
            $item->setDisplayOrder($i);
914
            $repo->update($item);
915
            $i++;
916
        }
917
        /*
918
        // Database table definition
919
        $table = Database::get_course_table(TABLE_GLOSSARY);
920
        $course_id = api_get_course_int_id();
921
        $sql = "SELECT * FROM $table
922
                WHERE c_id = $course_id
923
                ORDER by display_order ASC";
924
        $res = Database::query($sql);
925
926
        $i = 1;
927
        while ($data = Database::fetch_array($res)) {
928
            $sql = "UPDATE $table SET display_order = $i
929
                    WHERE c_id = $course_id AND glossary_id = '".intval($data['glossary_id'])."'";
930
            Database::query($sql);
931
            $i++;
932
        }
933
        */
934
    }
935
936
    /**
937
     * Move a glossary term.
938
     *
939
     * @param string $direction
940
     * @param string $glossary_id
941
     */
942
    public static function move_glossary($direction, $glossary_id)
943
    {
944
        // Database table definition
945
        $table = Database::get_course_table(TABLE_GLOSSARY);
946
947
        // sort direction
948
        if ('up' === $direction) {
949
            $sortorder = 'DESC';
950
        } else {
951
            $sortorder = 'ASC';
952
        }
953
        $course_id = api_get_course_int_id();
954
955
        $sql = "SELECT * FROM $table
956
                WHERE c_id = $course_id
957
                ORDER BY display_order $sortorder";
958
        $res = Database::query($sql);
959
        $found = false;
960
        while ($row = Database::fetch_array($res)) {
961
            if ($found && empty($next_id)) {
962
                $next_id = $row['glossary_id'];
963
                $next_display_order = $row['display_order'];
964
            }
965
966
            if ($row['glossary_id'] == $glossary_id) {
967
                $current_id = $glossary_id;
968
                $current_display_order = $row['display_order'];
969
                $found = true;
970
            }
971
        }
972
973
        $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...
974
                 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...
975
        $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...
976
                 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...
977
        Database::query($sql1);
978
        Database::query($sql2);
979
980
        Display::addFlash(Display::return_message(get_lang('The term has moved')));
981
    }
982
983
    /**
984
     * Export to pdf.
985
     */
986
    public static function export_to_pdf()
987
    {
988
        $data = self::get_glossary_data(
989
            0,
990
            self::get_number_glossary_terms(api_get_session_id()),
991
            0,
992
            'ASC'
993
        );
994
        $template = new Template('', false, false, false, true, false, false);
995
        $layout = $template->get_template('glossary/export_pdf.tpl');
996
        $template->assign('items', $data);
997
998
        $html = $template->fetch($layout);
999
        $courseCode = api_get_course_id();
1000
        $pdf = new PDF();
1001
        $pdf->content_to_pdf($html, '', get_lang('Glossary').'_'.$courseCode, $courseCode);
1002
    }
1003
1004
    /**
1005
     * Generate a PDF with all glossary terms and move file to documents.
1006
     *
1007
     * @return bool false if there's nothing in the glossary
1008
     */
1009
    public static function movePdfToDocuments()
1010
    {
1011
        $sessionId = api_get_session_id();
1012
        $courseId = api_get_course_int_id();
1013
        $data = self::get_glossary_data(
1014
            0,
1015
            self::get_number_glossary_terms($sessionId),
1016
            0,
1017
            'ASC'
1018
        );
1019
1020
        if (!empty($data)) {
1021
            $template = new Template('', false, false, false, true, false, false);
1022
            $layout = $template->get_template('glossary/export_pdf.tpl');
1023
            $template->assign('items', $data);
1024
            $fileName = get_lang('Glossary').'-'.api_get_local_time();
1025
            $signatures = ['Drh', 'Teacher', 'Date'];
1026
1027
            $pdf = new PDF(
1028
                'A4-P',
1029
                'P',
1030
                [
1031
                    'filename' => $fileName,
1032
                    'pdf_title' => $fileName,
1033
                    'add_signatures' => $signatures,
1034
                ]
1035
            );
1036
            $pdf->exportFromHtmlToDocumentsArea(
1037
                $template->fetch($layout),
1038
                $fileName,
1039
                $courseId
1040
            );
1041
1042
            return true;
1043
        } else {
1044
            Display::addFlash(Display::return_message(get_lang('Nothing to add')));
1045
        }
1046
1047
        return false;
1048
    }
1049
1050
    /**
1051
     * @param string $format
1052
     */
1053
    public static function exportToFormat($format)
1054
    {
1055
        if ('pdf' == $format) {
1056
            self::export_to_pdf();
1057
1058
            return;
1059
        }
1060
1061
        $data = self::get_glossary_data(
1062
            0,
1063
            self::get_number_glossary_terms(api_get_session_id()),
1064
            0,
1065
            'ASC'
1066
        );
1067
        usort($data, 'self::sorter');
1068
        //usort($data, 'sorter');
1069
        $list = [];
1070
        $list[] = ['term', 'definition'];
1071
        $allowStrip = api_get_configuration_value('allow_remove_tags_in_glossary_export');
1072
        foreach ($data as $line) {
1073
            $definition = $line[1];
1074
            if ($allowStrip) {
1075
                // htmlspecialchars_decode replace &#39 to '
1076
                // strip_tags remove HTML tags
1077
                $definition = htmlspecialchars_decode(strip_tags($definition), ENT_QUOTES);
1078
            }
1079
            $list[] = [$line[0], $definition];
1080
        }
1081
        $filename = 'glossary_course_'.api_get_course_id();
1082
1083
        switch ($format) {
1084
            case 'csv':
1085
                Export::arrayToCsv($list, $filename);
1086
                break;
1087
            case 'xls':
1088
                Export::arrayToXls($list, $filename);
1089
                break;
1090
        }
1091
    }
1092
1093
    public static function sorter($item1, $item2)
1094
    {
1095
        if ($item1[2] == $item2[2]) {
1096
            return 0;
1097
        }
1098
1099
        return $item1[2] < $item2[2] ? -1 : 1;
1100
    }
1101
}
1102