GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — 2.9 ( 7343d3...e1b57e )
by Thorsten
16:48
created

PMF_Faq::getRecordBySolutionId()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 61
Code Lines 36

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 61
rs 8.9392
cc 4
eloc 36
nc 5
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * The main FAQ class.
5
 *
6
 * PHP Version 5.5
7
 *
8
 * This Source Code Form is subject to the terms of the Mozilla Public License,
9
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
10
 * obtain one at http://mozilla.org/MPL/2.0/.
11
 *
12
 * @category  phpMyFAQ
13
 * @author    Thorsten Rinne <[email protected]>
14
 * @author    Matteo Scaramuccia <[email protected]>
15
 * @author    Georgi Korchev <[email protected]>
16
 * @author    Adrianna Musiol <[email protected]>
17
 * @author    Peter Caesar <[email protected]>
18
 * @copyright 2005-2015 phpMyFAQ Team
19
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
20
 * @link      http://www.phpmyfaq.de
21
 * @since     2005-12-20
22
 */
23
if (!defined('IS_VALID_PHPMYFAQ')) {
24
    exit();
25
}
26
27
/*
28
 * SQL constants definitions
29
 */
30
define('FAQ_SQL_ACTIVE_YES', 'yes');
31
define('FAQ_SQL_ACTIVE_NO',  'no');
32
33
/*
34
 * Query type definitions
35
 */
36
define('FAQ_QUERY_TYPE_DEFAULT',      'faq_default');
37
define('FAQ_QUERY_TYPE_APPROVAL',     'faq_approval');
38
define('FAQ_QUERY_TYPE_EXPORT_PDF',   'faq_export_pdf');
39
define('FAQ_QUERY_TYPE_EXPORT_XHTML', 'faq_export_xhtml');
40
define('FAQ_QUERY_TYPE_EXPORT_XML',   'faq_export_xml');
41
define('FAQ_QUERY_TYPE_RSS_LATEST',   'faq_rss_latest');
42
43
/*
44
 * Sorting type definitions
45
 */
46
define('FAQ_SORTING_TYPE_NONE', 0);
47
define('FAQ_SORTING_TYPE_CATID_FAQID', 1);
48
define('FAQ_SORTING_TYPE_FAQTITLE_FAQID', 2);
49
define('FAQ_SORTING_TYPE_DATE_FAQID', 3);
50
define('FAQ_SORTING_TYPE_FAQID', 4);
51
52
/**
53
 * The main FAQ class - 3K LOC of funny things for phpMyFAQ.
54
 *
55
 * @category  phpMyFAQ
56
 * @author    Thorsten Rinne <[email protected]>
57
 * @author    Matteo Scaramuccia <[email protected]>
58
 * @author    Georgi Korchev <[email protected]>
59
 * @author    Adrianna Musiol <[email protected]>
60
 * @author    Peter Caesar <[email protected]>
61
 * @copyright 2005-2015 phpMyFAQ Team
62
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
63
 * @link      http://www.phpmyfaq.de
64
 * @since     2005-12-20
65
 */
66
class PMF_Faq
67
{
68
    /**
69
     * @var PMF_Configuration
70
     */
71
    private $_config;
72
73
    /**
74
     * Language strings.
75
     *
76
     * @var string
77
     */
78
    private $pmf_lang;
79
80
    /**
81
     * Plural form support.
82
     *
83
     * @var PMF_Language_Plurals
84
     */
85
    private $plr;
86
87
    /**
88
     * The current FAQ record.
89
     *
90
     * @var array
91
     */
92
    public $faqRecord = [];
93
94
    /**
95
     * All current FAQ records in an array.
96
     *
97
     * @var array
98
     */
99
    public $faqRecords = [];
100
101
    /**
102
     * Users.
103
     *
104
     * @var int
105
     */
106
    private $user = -1;
107
108
    /**
109
     * Groups.
110
     *
111
     * @var array
112
     */
113
    private $groups = array(-1);
114
115
    /**
116
     * Flag for Group support.
117
     *
118
     * @var bool
119
     */
120
    private $groupSupport = false;
121
122
    /**
123
     * Constructor.
124
     *
125
     * @param PMF_Configuration $config
126
     *
127
     * @return PMF_Faq
128
     */
129
    public function __construct(PMF_Configuration $config)
130
    {
131
        global $PMF_LANG, $plr;
132
133
        $this->_config = $config;
134
        $this->pmf_lang = $PMF_LANG;
135
        $this->plr = $plr;
136
137
        if ($this->_config->get('security.permLevel') == 'medium') {
138
            $this->groupSupport = true;
139
        }
140
    }
141
142
    //
143
    //
144
    // PUBLIC METHODS
145
    //
146
    //
147
148
    /**
149
     * @param int $userId
150
     */
151
    public function setUser($userId = -1)
152
    {
153
        $this->user = $userId;
154
    }
155
156
    /**
157
     * @param array $groups
158
     */
159
    public function setGroups(Array $groups)
160
    {
161
        $this->groups = $groups;
162
    }
163
164
    /**
165
     * This function returns all not expired records from one category.
166
     *
167
     * @param int    $category_id Category ID
168
     * @param string $orderby     Order by
169
     * @param string $sortby      Sorty by
170
     *
171
     * @return array
172
     */
173
    public function getAllRecordPerCategory($category_id, $orderby = 'id', $sortby = 'ASC')
174
    {
175
        global $sids;
176
177
        $faqdata = [];
178
179
        if ($orderby == 'visits') {
180
            $currentTable = 'fv';
181
        } else {
182
            $currentTable = 'fd';
183
        }
184
185
        $now = date('YmdHis');
186
        $query = sprintf("
187
            SELECT
188
                fd.id AS id,
189
                fd.lang AS lang,
190
                fd.thema AS thema,
191
                fd.content AS record_content,
192
                fd.updated AS updated,
193
                fcr.category_id AS category_id,
194
                fv.visits AS visits,
195
                fd.created AS created
196
            FROM
197
                %sfaqdata AS fd
198
            LEFT JOIN
199
                %sfaqcategoryrelations AS fcr
200
            ON
201
                fd.id = fcr.record_id
202
            AND
203
                fd.lang = fcr.record_lang
204
            LEFT JOIN
205
                %sfaqvisits AS fv
206
            ON
207
                fd.id = fv.id
208
            AND
209
                fv.lang = fd.lang
210
            LEFT JOIN
211
                %sfaqdata_group AS fdg
212
            ON
213
                fd.id = fdg.record_id
214
            LEFT JOIN
215
                %sfaqdata_user AS fdu
216
            ON
217
                fd.id = fdu.record_id
218
            WHERE
219
                fd.date_start <= '%s'
220
            AND
221
                fd.date_end   >= '%s'
222
            AND
223
                fd.active = 'yes'
224
            AND
225
                fcr.category_id = %d
226
            AND
227
                fd.lang = '%s'
228
                %s
229
            ORDER BY
230
                %s.%s %s",
231
            PMF_Db::getTablePrefix(),
232
            PMF_Db::getTablePrefix(),
233
            PMF_Db::getTablePrefix(),
234
            PMF_Db::getTablePrefix(),
235
            PMF_Db::getTablePrefix(),
236
            $now,
237
            $now,
238
            $category_id,
239
            $this->_config->getLanguage()->getLanguage(),
240
            $this->queryPermission($this->groupSupport),
241
            $currentTable,
242
            $this->_config->getDb()->escape($orderby),
243
            $this->_config->getDb()->escape($sortby)
244
        );
245
246
        $result = $this->_config->getDb()->query($query);
247
        $num = $this->_config->getDb()->numRows($result);
248
249
        if ($num > 0) {
250
            $parsedown = new ParsedownExtra();
251
            while (($row = $this->_config->getDb()->fetchObject($result))) {
252
                if (empty($row->visits)) {
253
                    $visits = 0;
254
                } else {
255
                    $visits = $row->visits;
256
                }
257
258
                $url = sprintf(
259
                    '%sindex.php?%saction=artikel&cat=%d&id=%d&artlang=%s',
260
                    $this->_config->getDefaultUrl(),
261
                    $sids,
262
                    $row->category_id,
263
                    $row->id,
264
                    $row->lang
265
                );
266
                $oLink = new PMF_Link($url, $this->_config);
267
                $oLink->itemTitle = $oLink->text = $oLink->tooltip = $row->thema;
268
269 View Code Duplication
                if ($this->_config->get('main.enableMarkdownEditor')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
                    $answerPreview = PMF_Utils::chopString(strip_tags($parsedown->text($row->record_content)), 25);
271
                } else {
272
                    $answerPreview = PMF_Utils::chopString(strip_tags($row->record_content), 25);
273
                }
274
                $faqdata[] = array(
275
                    'record_id' => $row->id,
276
                    'record_lang' => $row->lang,
277
                    'category_id' => $row->category_id,
278
                    'record_title' => $row->thema,
279
                    'record_preview' => $answerPreview,
280
                    'record_link' => $oLink->toString(),
281
                    'record_updated' => $row->updated,
282
                    'visits' => $visits,
283
                    'record_created' => $row->created,
284
                );
285
            }
286
        } else {
287
            return $faqdata;
288
        }
289
290
        return $faqdata;
291
    }
292
293
    /**
294
     * This function returns all not expired records from one category.
295
     *
296
     * @param int    $categoryId Category ID
297
     * @param string $orderby    Order by
298
     * @param string $sortby     Sorty by
299
     *
300
     * @return string
301
     */
302
    public function showAllRecords($categoryId, $orderby = 'id', $sortby = 'ASC')
303
    {
304
        global $sids;
305
306
        $numPerPage = $this->_config->get('records.numberOfRecordsPerPage');
307
        $page = PMF_Filter::filterInput(INPUT_GET, 'seite', FILTER_VALIDATE_INT, 1);
308
        $output = '';
309
        $title = '';
310
311
        if ($orderby == 'visits') {
312
            $currentTable = 'fv';
313
        } else {
314
            $currentTable = 'fd';
315
        }
316
317
        // If random FAQs are activated, we don't need an order
318
        if (true === $this->_config->get('records.randomSort')) {
319
            $order = '';
320
        } else {
321
            $order = sprintf(
322
                'ORDER BY fd.sticky DESC, %s.%s %s',
323
                $currentTable,
324
                $this->_config->getDb()->escape($orderby),
325
                $this->_config->getDb()->escape($sortby)
326
            );
327
        }
328
329
        $now = date('YmdHis');
330
        $query = sprintf("
331
            SELECT
332
                fd.id AS id,
333
                fd.lang AS lang,
334
                fd.sticky AS sticky,
335
                fd.thema AS thema,
336
                fcr.category_id AS category_id,
337
                fv.visits AS visits
338
            FROM
339
                %sfaqdata AS fd
340
            LEFT JOIN
341
                %sfaqcategoryrelations AS fcr
342
            ON
343
                fd.id = fcr.record_id
344
            AND
345
                fd.lang = fcr.record_lang
346
            LEFT JOIN
347
                %sfaqvisits AS fv
348
            ON
349
                fd.id = fv.id
350
            AND
351
                fv.lang = fd.lang
352
            LEFT JOIN
353
                %sfaqdata_group AS fdg
354
            ON
355
                fd.id = fdg.record_id
356
            LEFT JOIN
357
                %sfaqdata_user AS fdu
358
            ON
359
                fd.id = fdu.record_id
360
            WHERE
361
                fd.date_start <= '%s'
362
            AND
363
                fd.date_end   >= '%s'
364
            AND
365
                fd.active = 'yes'
366
            AND
367
                fcr.category_id = %d
368
            AND
369
                fd.lang = '%s'
370
            %s
371
            %s",
372
            PMF_Db::getTablePrefix(),
373
            PMF_Db::getTablePrefix(),
374
            PMF_Db::getTablePrefix(),
375
            PMF_Db::getTablePrefix(),
376
            PMF_Db::getTablePrefix(),
377
            $now,
378
            $now,
379
            $categoryId,
380
            $this->_config->getLanguage()->getLanguage(),
381
            $this->queryPermission($this->groupSupport),
382
            $order
383
        );
384
385
        $result = $this->_config->getDb()->query($query);
386
        $num = $this->_config->getDb()->numRows($result);
387
        $pages = (int) ceil($num / $numPerPage);
388
389
        if ($page == 1) {
390
            $first = 0;
391
        } else {
392
            $first = $page * $numPerPage - $numPerPage;
393
        }
394
395
        if ($num > 0) {
396 View Code Duplication
            if ($pages > 1) {
397
                $output .= sprintf('<p><strong>%s %s %s</strong></p>',
398
                    $this->pmf_lang['msgPage'].$page,
399
                    $this->pmf_lang['msgVoteFrom'],
400
                    $pages.$this->pmf_lang['msgPages']);
401
            }
402
            $output .= '<ul class="phpmyfaq_ul">';
403
404
            $counter = 0;
405
            $displayedCounter = 0;
406
            $renderedItems = [];
407
            while (($row = $this->_config->getDb()->fetchObject($result)) && $displayedCounter < $numPerPage) {
408
                ++$counter;
409
                if ($counter <= $first) {
410
                    continue;
411
                }
412
                ++$displayedCounter;
413
414
                if (empty($row->visits)) {
415
                    $visits = 0;
416
                } else {
417
                    $visits = $row->visits;
418
                }
419
420
                $title = $row->thema;
421
                $url = sprintf(
422
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
423
                    PMF_Link::getSystemRelativeUri(),
424
                    $sids,
425
                    $row->category_id,
426
                    $row->id,
427
                    $row->lang
428
                );
429
430
                $oLink = new PMF_Link($url, $this->_config);
431
                $oLink->itemTitle = $oLink->text = $oLink->tooltip = $title;
432
433
                // If random FAQs are activated, we don't need sticky FAQs
434
                if (true === $this->_config->get('records.randomSort')) {
435
                    $row->sticky = 0;
436
                }
437
438
                $renderedItems[$row->id] = sprintf(
439
                    '<li%s>%s<span id="viewsPerRecord"><br /><small>(%s)</small></span></li>',
440
                    ($row->sticky == 1) ? ' class="sticky-faqs"' : '',
441
                    $oLink->toHtmlAnchor(),
442
                    $this->plr->GetMsg('plmsgViews', $visits)
443
                );
444
            }
445
446
            // If random FAQs are activated, shuffle the FAQs :-)
447
            if (true === $this->_config->get('records.randomSort')) {
448
                shuffle($renderedItems);
449
            }
450
451
            $output .= implode("\n", $renderedItems);
452
            $output .= '</ul><span class="totalFaqRecords hide">'.$num.'</span>';
453
        } else {
454
            return false;
455
        }
456
457
        if ($pages > 1) {
458
            // Set rewrite URL, if needed
459
            if ($this->_config->get('main.enableRewriteRules')) {
460
                $link = new PMF_Link(PMF_Link::getSystemRelativeUri('index.php'), $this->_config);
461
                $useRewrite = true;
462
                $rewriteUrl = sprintf(
463
                    '%scategory/%d/%%d/%s.html',
464
                    PMF_Link::getSystemRelativeUri('index.php'),
465
                    $categoryId,
466
                    $link->getSEOItemTitle($title)
467
                );
468
            } else {
469
                $useRewrite = false;
470
                $rewriteUrl = '';
471
            }
472
            $baseUrl = sprintf(
473
                '%s?%saction=show&amp;cat=%d&amp;seite=%d',
474
                PMF_Link::getSystemRelativeUri(),
475
                (empty($sids) ? '' : $sids),
476
                $categoryId,
477
                $page
478
            );
479
480
            $options = array(
481
                'baseUrl' => $baseUrl,
482
                'total' => $num,
483
                'perPage' => $this->_config->get('records.numberOfRecordsPerPage'),
484
                'useRewrite' => $useRewrite,
485
                'rewriteUrl' => $rewriteUrl,
486
                'pageParamName' => 'seite',
487
            );
488
489
            $pagination = new PMF_Pagination($this->_config, $options);
490
            $output    .= $pagination->render();
491
        }
492
493
        return $output;
494
    }
495
496
    /**
497
     * This function returns all not expired records from the given record ids.
498
     *
499
     * @param array  $record_ids Array of record ids
500
     * @param string $orderby    Order by
501
     * @param string $sortby     Sort by
502
     *
503
     * @return string
504
     */
505
    public function showAllRecordsByIds(Array $record_ids, $orderby = 'fd.id', $sortby = 'ASC')
506
    {
507
        global $sids;
508
509
        $records = implode(', ', $record_ids);
510
        $page = PMF_Filter::filterInput(INPUT_GET, 'seite', FILTER_VALIDATE_INT, 1);
511
        $tagging_id = PMF_Filter::filterInput(INPUT_GET, 'tagging_id', FILTER_VALIDATE_INT);
512
        $output = '';
513
514
        $now = date('YmdHis');
515
        $query = sprintf("
516
            SELECT
517
                fd.id AS id,
518
                fd.lang AS lang,
519
                fd.thema AS thema,
520
                fcr.category_id AS category_id,
521
                fv.visits AS visits
522
            FROM
523
                %sfaqdata AS fd
524
            LEFT JOIN
525
                %sfaqcategoryrelations AS fcr
526
            ON
527
                fd.id = fcr.record_id
528
            AND
529
                fd.lang = fcr.record_lang
530
            LEFT JOIN
531
                %sfaqvisits AS fv
532
            ON
533
                fd.id = fv.id
534
            AND
535
                fv.lang = fd.lang
536
            LEFT JOIN
537
                %sfaqdata_group AS fdg
538
            ON
539
                fd.id = fdg.record_id
540
            LEFT JOIN
541
                %sfaqdata_user AS fdu
542
            ON
543
                fd.id = fdu.record_id
544
            WHERE
545
                fd.date_start <= '%s'
546
            AND
547
                fd.date_end   >= '%s'
548
            AND
549
                fd.active = 'yes'
550
            AND
551
                fd.id IN (%s)
552
            AND
553
                fd.lang = '%s'
554
                %s
555
            ORDER BY
556
                %s %s",
557
            PMF_Db::getTablePrefix(),
558
            PMF_Db::getTablePrefix(),
559
            PMF_Db::getTablePrefix(),
560
            PMF_Db::getTablePrefix(),
561
            PMF_Db::getTablePrefix(),
562
            $now,
563
            $now,
564
            $records,
565
            $this->_config->getLanguage()->getLanguage(),
566
            $this->queryPermission($this->groupSupport),
567
            $this->_config->getDb()->escape($orderby),
568
            $this->_config->getDb()->escape($sortby));
569
570
        $result = $this->_config->getDb()->query($query);
571
572
        $num = $this->_config->getDb()->numRows($result);
573
        $pages = ceil($num / $this->_config->get('records.numberOfRecordsPerPage'));
574
575
        if ($page == 1) {
576
            $first = 0;
577
        } else {
578
            $first = ($page * $this->_config->get('records.numberOfRecordsPerPage')) - $this->_config->get('records.numberOfRecordsPerPage');
579
        }
580
581
        if ($num > 0) {
582 View Code Duplication
            if ($pages > 1) {
583
                $output .= sprintf('<p><strong>%s %s %s</strong></p>',
584
                    $this->pmf_lang['msgPage'].$page,
585
                    $this->pmf_lang['msgVoteFrom'],
586
                    $pages.$this->pmf_lang['msgPages']);
587
            }
588
            $output .= '<ul class="phpmyfaq_ul">';
589
            $counter = 0;
590
            $displayedCounter = 0;
591
592
            $lastFaqId = 0;
593
            while (($row = $this->_config->getDb()->fetchObject($result)) && $displayedCounter < $this->_config->get('records.numberOfRecordsPerPage')) {
594
                ++$counter;
595
                if ($counter <= $first) {
596
                    continue;
597
                }
598
                ++$displayedCounter;
599
600
                if ($lastFaqId == $row->id) {
601
                    continue; // Don't show multiple FAQs
602
                }
603
604
                if (empty($row->visits)) {
605
                    $visits = 0;
606
                } else {
607
                    $visits = $row->visits;
608
                }
609
610
                $title = $row->thema;
611
                $url = sprintf(
612
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
613
                    PMF_Link::getSystemRelativeUri(),
614
                    $sids,
615
                    $row->category_id,
616
                    $row->id,
617
                    $row->lang
618
                );
619
                $oLink = new PMF_Link($url, $this->_config);
620
                $oLink->itemTitle = $row->thema;
621
                $oLink->text = $title;
622
                $oLink->tooltip = $title;
623
                $listItem = sprintf(
624
                    '<li>%s<br /><small>(%s)</small></li>',
625
                    $oLink->toHtmlAnchor(),
626
                    $this->plr->GetMsg('plmsgViews', $visits)
627
                );
628
629
                $output .= $listItem;
630
631
                $lastFaqId = $row->id;
632
            }
633
            $output .= '</ul><span id="totFaqRecords" style="display: none;">'.$num.'</span>';
634
        } else {
635
            return false;
636
        }
637
638
        if ($num > $this->_config->get('records.numberOfRecordsPerPage')) {
639
            $output .= '<p class="text-center"><strong>';
640
            if (!isset($page)) {
641
                $page = 1;
642
            }
643
            $vor = $page - 1;
644
            $next = $page + 1;
645 View Code Duplication
            if ($vor != 0) {
646
                $url = $sids.'&amp;action=search&amp;tagging_id='.$tagging_id.'&amp;seite='.$vor;
647
                $oLink = new PMF_Link(PMF_Link::getSystemRelativeUri().'?'.$url, $this->_config);
648
                $oLink->itemTitle = 'tag';
649
                $oLink->text = $this->pmf_lang['msgPrevious'];
650
                $oLink->tooltip = $this->pmf_lang['msgPrevious'];
651
                $output          .= '[ '.$oLink->toHtmlAnchor().' ]';
652
            }
653
            $output .= ' ';
654 View Code Duplication
            if ($next <= $pages) {
655
                $url = $sids.'&amp;action=search&amp;tagging_id='.$tagging_id.'&amp;seite='.$next;
656
                $oLink = new PMF_Link(PMF_Link::getSystemRelativeUri().'?'.$url, $this->_config);
657
                $oLink->itemTitle = 'tag';
658
                $oLink->text = $this->pmf_lang['msgNext'];
659
                $oLink->tooltip = $this->pmf_lang['msgNext'];
660
                $output          .= '[ '.$oLink->toHtmlAnchor().' ]';
661
            }
662
            $output .= '</strong></p>';
663
        }
664
665
        return $output;
666
    }
667
668
    /**
669
     * Returns an array with all data from a FAQ record.
670
     *
671
     * @param int  $faqId         FAQ ID
672
     * @param int  $faqRevisionId Revision ID
673
     * @param bool $isAdmin       Must be true if it is called by an admin/author context
674
     */
675
    public function getRecord($faqId, $faqRevisionId = null, $isAdmin = false)
676
    {
677
        global $PMF_LANG;
678
679
        $currentLanguage = $this->_config->getLanguage()->getLanguage();
680
        $defaultLanguage = $this->_config->getDefaultLanguage();
681
682
        $result = $this->getRecordResult($faqId, $currentLanguage, $faqRevisionId, $isAdmin);
683
684
        if (0 === $this->_config->getDb()->numRows($result)) {
685
            $result = $this->getRecordResult($faqId, $defaultLanguage, $faqRevisionId, $isAdmin);
686
        }
687
688
        if ($row = $this->_config->getDb()->fetchObject($result)) {
689
            $question = nl2br($row->thema);
690
            $answer = $row->content;
691
            $active = ('yes' === $row->active);
692
            $expired = (date('YmdHis') > $row->date_end);
693
694
            if (!$isAdmin) {
695
                if (!$active) {
696
                    $answer = $this->pmf_lang['err_inactiveArticle'];
697
                }
698
                if ($expired) {
699
                    $answer = $this->pmf_lang['err_expiredArticle'];
700
                }
701
            }
702
703
            $this->faqRecord = [
704
                'id' => $row->id,
705
                'lang' => $row->lang,
706
                'solution_id' => $row->solution_id,
707
                'revision_id' => $row->revision_id,
708
                'active' => $row->active,
709
                'sticky' => $row->sticky,
710
                'keywords' => $row->keywords,
711
                'title' => $question,
712
                'content' => $answer,
713
                'author' => $row->author,
714
                'email' => $row->email,
715
                'comment' => $row->comment,
716
                'date' => PMF_Date::createIsoDate($row->updated),
717
                'dateStart' => $row->date_start,
718
                'dateEnd' => $row->date_end,
719
                'linkState' => $row->links_state,
720
                'linkCheckDate' => $row->links_check_date,
721
                'created' => $row->created,
722
            ];
723
        } else {
724
            $this->faqRecord = [
725
                'id' => $faqId,
726
                'lang' => $currentLanguage,
727
                'solution_id' => 42,
728
                'revision_id' => $faqRevisionId,
729
                'active' => 'no',
730
                'sticky' => 0,
731
                'keywords' => '',
732
                'title' => '',
733
                'content' => $PMF_LANG['msgAccessDenied'],
734
                'author' => '',
735
                'email' => '',
736
                'comment' => '',
737
                'date' => PMF_Date::createIsoDate(date('YmdHis')),
738
                'dateStart' => '',
739
                'dateEnd' => '',
740
                'linkState' => '',
741
                'linkCheckDate' => '',
742
                'created' => date('c'),
743
            ];
744
        }
745
    }
746
747
    /**
748
     * Executes a query to retrieve a single FAQ.
749
     *
750
     * @param int    $faqId
751
     * @param string $faqLanguage
752
     * @param int    $faqRevisionId
753
     * @param bool   $isAdmin
754
     *
755
     * @return mixed
756
     */
757
    public function getRecordResult($faqId, $faqLanguage, $faqRevisionId = null, $isAdmin = false)
758
    {
759
        $query = sprintf(
760
            "SELECT
761
                 id, lang, solution_id, revision_id, active, sticky, keywords,
762
                 thema, content, author, email, comment, updated, links_state,
763
                 links_check_date, date_start, date_end, created
764
            FROM
765
                %s%s fd
766
            LEFT JOIN
767
                %sfaqdata_group fdg
768
            ON
769
                fd.id = fdg.record_id
770
            LEFT JOIN
771
                %sfaqdata_user fdu
772
            ON
773
                fd.id = fdu.record_id
774
            WHERE
775
                fd.id = %d
776
            %s
777
            AND
778
                fd.lang = '%s'
779
                %s",
780
            PMF_Db::getTablePrefix(),
781
            isset($faqRevisionId) ? 'faqdata_revisions' : 'faqdata',
782
            PMF_Db::getTablePrefix(),
783
            PMF_Db::getTablePrefix(),
784
            $faqId,
785
            isset($faqRevisionId) ? 'AND revision_id = '.$faqRevisionId : '',
786
            $faqLanguage,
787
            ($isAdmin) ? 'AND 1=1' : $this->queryPermission($this->groupSupport)
788
        );
789
790
        return $this->_config->getDb()->query($query);
791
    }
792
793
    /**
794
     * Adds a new record.
795
     *
796
     * @param array $data      Array of FAQ data
797
     * @param bool  $newRecord Do not create a new ID if false
798
     *
799
     * @return int
800
     */
801
    public function addRecord(Array $data, $newRecord = true)
802
    {
803
        if ($newRecord) {
804
            $recordId = $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqdata', 'id');
805
        } else {
806
            $recordId = $data['id'];
807
        }
808
809
        // Add new entry
810
        $query = sprintf(
811
            "INSERT INTO
812
                %sfaqdata
813
            VALUES
814
                (%d, '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s')",
815
            PMF_Db::getTablePrefix(),
816
            $recordId,
817
            $data['lang'],
818
            $this->getSolutionId(),
819
            0,
820
            $data['active'],
821
            $data['sticky'],
822
            $this->_config->getDb()->escape($data['keywords']),
823
            $this->_config->getDb()->escape($data['thema']),
824
            $this->_config->getDb()->escape($data['content']),
825
            $this->_config->getDb()->escape($data['author']),
826
            $data['email'],
827
            $data['comment'],
828
            $data['date'],
829
            $data['linkState'],
830
            $data['linkDateCheck'],
831
            $data['dateStart'],
832
            $data['dateEnd'],
833
            date('Y-m-d H:i:s')
834
        );
835
836
        $this->_config->getDb()->query($query);
837
838
        return $recordId;
839
    }
840
841
    /**
842
     * Updates a record.
843
     *
844
     * @param array $data Array of FAQ data
845
     *
846
     * @return bool
847
     */
848
    public function updateRecord(Array $data)
849
    {
850
        // Update entry
851
        $query = sprintf("
852
            UPDATE
853
                %sfaqdata
854
            SET
855
                revision_id = %d,
856
                active = '%s',
857
                sticky = %d,
858
                keywords = '%s',
859
                thema = '%s',
860
                content = '%s',
861
                author = '%s',
862
                email = '%s',
863
                comment = '%s',
864
                updated = '%s',
865
                links_state = '%s',
866
                links_check_date = %d,
867
                date_start = '%s',
868
                date_end = '%s'
869
            WHERE
870
                id = %d
871
            AND
872
                lang = '%s'",
873
            PMF_Db::getTablePrefix(),
874
            $data['revision_id'],
875
            $data['active'],
876
            $data['sticky'],
877
            $this->_config->getDb()->escape($data['keywords']),
878
            $this->_config->getDb()->escape($data['thema']),
879
            $this->_config->getDb()->escape($data['content']),
880
            $this->_config->getDb()->escape($data['author']),
881
            $data['email'],
882
            $data['comment'],
883
            $data['date'],
884
            $data['linkState'],
885
            $data['linkDateCheck'],
886
            $data['dateStart'],
887
            $data['dateEnd'],
888
            $data['id'],
889
            $data['lang']);
890
891
        $this->_config->getDb()->query($query);
892
893
        return true;
894
    }
895
896
    /**
897
     * Deletes a record and all the dependencies.
898
     *
899
     * @param int    $recordId   Record id
900
     * @param string $recordLang Record language
901
     *
902
     * @return bool
903
     */
904
    public function deleteRecord($recordId, $recordLang)
905
    {
906
        $solutionId = $this->getSolutionIdFromId($recordId, $recordLang);
907
908
        $queries = array(
909
            sprintf(
910
                "DELETE FROM %sfaqchanges WHERE beitrag = %d AND lang = '%s'",
911
                PMF_Db::getTablePrefix(),
912
                $recordId,
913
                $recordLang
914
            ),
915
            sprintf(
916
                "DELETE FROM %sfaqcategoryrelations WHERE record_id = %d AND record_lang = '%s'",
917
                PMF_Db::getTablePrefix(),
918
                $recordId,
919
                $recordLang
920
            ),
921
            sprintf(
922
                "DELETE FROM %sfaqdata WHERE id = %d AND lang = '%s'",
923
                PMF_Db::getTablePrefix(),
924
                $recordId,
925
                $recordLang
926
            ),
927
            sprintf(
928
                "DELETE FROM %sfaqdata_revisions WHERE id = %d AND lang = '%s'",
929
                PMF_Db::getTablePrefix(),
930
                $recordId,
931
                $recordLang
932
            ),
933
            sprintf(
934
                "DELETE FROM %sfaqvisits WHERE id = %d AND lang = '%s'",
935
                PMF_Db::getTablePrefix(),
936
                $recordId,
937
                $recordLang
938
            ),
939
            sprintf(
940
                'DELETE FROM %sfaqdata_user WHERE record_id = %d',
941
                PMF_Db::getTablePrefix(),
942
                $recordId,
943
                $recordLang
944
            ),
945
            sprintf(
946
                'DELETE FROM %sfaqdata_group WHERE record_id = %d',
947
                PMF_Db::getTablePrefix(),
948
                $recordId,
949
                $recordLang
950
            ),
951
            sprintf(
952
                'DELETE FROM %sfaqdata_tags WHERE record_id = %d',
953
                PMF_Db::getTablePrefix(),
954
                $recordId
955
            ),
956
            sprintf(
957
                'DELETE FROM %sfaqdata_tags WHERE %sfaqdata_tags.record_id NOT IN (SELECT %sfaqdata.id FROM %sfaqdata)',
958
                PMF_Db::getTablePrefix(),
959
                PMF_Db::getTablePrefix(),
960
                PMF_Db::getTablePrefix(),
961
                PMF_Db::getTablePrefix()
962
            ),
963
            sprintf(
964
                'DELETE FROM %sfaqcomments WHERE id = %d',
965
                PMF_Db::getTablePrefix(),
966
                $recordId
967
            ),
968
            sprintf(
969
                'DELETE FROM %sfaqvoting WHERE artikel = %d',
970
                PMF_Db::getTablePrefix(),
971
                $recordId
972
            ),
973
        );
974
975
        foreach ($queries as $query) {
976
            $this->_config->getDb()->query($query);
977
        }
978
979
        // Delete possible attachments
980
        $attId = PMF_Attachment_Factory::fetchByRecordId($this->_config, $recordId);
981
        $attachment = PMF_Attachment_Factory::create($attId);
982
        $attachment->delete();
983
984
        // Delete possible Elasticsearch documents
985
        if ($this->_config->get('search.enableElasticsearch')) {
986
            $esInstance = new PMF_Instance_Elasticsearch($this->_config);
987
            $esInstance->delete($solutionId);
988
        }
989
990
        return true;
991
    }
992
993
    /**
994
     * Checks if a record is already translated.
995
     *
996
     * @param int    $record_id   Record id
997
     * @param string $record_lang Record language
998
     *
999
     * @return bool
1000
     */
1001
    public function isAlreadyTranslated($record_id, $record_lang)
1002
    {
1003
        $query = sprintf("
1004
            SELECT
1005
                id, lang
1006
            FROM
1007
                %sfaqdata
1008
            WHERE
1009
                id = %d
1010
            AND
1011
                lang = '%s'",
1012
            PMF_Db::getTablePrefix(),
1013
            $record_id,
1014
            $record_lang);
1015
1016
        $result = $this->_config->getDb()->query($query);
1017
1018
        if ($this->_config->getDb()->numRows($result)) {
1019
            return true;
1020
        }
1021
1022
        return false;
1023
    }
1024
1025
    /**
1026
     * Checks, if comments are disabled for the FAQ record.
1027
     *
1028
     * @param int    $record_id   Id of FAQ or news entry
1029
     * @param string $record_lang Language
1030
     * @param string $record_type Type of comment: faq or news
1031
     *
1032
     * @return bool true, if comments are disabled
1033
     */
1034
    public function commentDisabled($record_id, $record_lang, $record_type = 'faq')
1035
    {
1036
        if ('news' == $record_type) {
1037
            $table = 'faqnews';
1038
        } else {
1039
            $table = 'faqdata';
1040
        }
1041
1042
        $query = sprintf("
1043
            SELECT
1044
                comment
1045
            FROM
1046
                %s%s
1047
            WHERE
1048
                id = %d
1049
            AND
1050
                lang = '%s'",
1051
            PMF_Db::getTablePrefix(),
1052
            $table,
1053
            $record_id,
1054
            $record_lang);
1055
1056
        $result = $this->_config->getDb()->query($query);
1057
1058
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1059
            return ($row->comment === 'y') ? false : true;
1060
        } else {
1061
            return true;
1062
        }
1063
    }
1064
1065
    /**
1066
     * Adds new category relations to a record.
1067
     *
1068
     * @param array  $categories Array of categories
1069
     * @param int    $record_id  Record id
1070
     * @param string $language   Language
1071
     *
1072
     * @return int
1073
     */
1074
    public function addCategoryRelations(Array $categories, $record_id, $language)
1075
    {
1076
        if (!is_array($categories)) {
1077
            return false;
1078
        }
1079
1080
        foreach ($categories as $_category) {
1081
            $this->_config->getDb()->query(sprintf(
1082
                "INSERT INTO
1083
                    %sfaqcategoryrelations
1084
                VALUES
1085
                    (%d, '%s', %d, '%s')",
1086
                PMF_Db::getTablePrefix(),
1087
                $_category,
1088
                $language,
1089
                $record_id,
1090
                $language));
1091
        }
1092
1093
        return true;
1094
    }
1095
1096
    /**
1097
     * Adds new category relation to a record.
1098
     *
1099
     * @param mixed  $category  Category or array of categories
1100
     * @param int    $record_id Record id
1101
     * @param string $language  Language
1102
     *
1103
     * @return bool
1104
     */
1105
    public function addCategoryRelation($category, $record_id, $language)
1106
    {
1107
        // Just a fallback when (wrong case) $category is an array
1108
        if (is_array($category)) {
1109
            $this->addCategoryRelations($category, $record_id, $language);
1110
        }
1111
        $categories[] = $category;
1112
1113
        return $this->addCategoryRelations($categories, $record_id, $language);
1114
    }
1115
1116
    /**
1117
     * Deletes category relations to a record.
1118
     *
1119
     * @param int    $record_id   Record id
1120
     * @param string $record_lang Language
1121
     *
1122
     * @return bool
1123
     */
1124 View Code Duplication
    public function deleteCategoryRelations($record_id, $record_lang)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1125
    {
1126
        $query = sprintf("
1127
            DELETE FROM
1128
                %sfaqcategoryrelations
1129
            WHERE
1130
                record_id = %d
1131
            AND
1132
                record_lang = '%s'",
1133
            PMF_Db::getTablePrefix(),
1134
            $record_id,
1135
            $record_lang);
1136
        $this->_config->getDb()->query($query);
1137
1138
        return true;
1139
    }
1140
1141
    /**
1142
     * Returns an array with all data from a FAQ record.
1143
     *
1144
     * @param int $solutionId Solution ID
1145
     */
1146
    public function getRecordBySolutionId($solutionId)
1147
    {
1148
        $query = sprintf(
1149
            'SELECT
1150
                *
1151
            FROM
1152
                %sfaqdata fd
1153
            LEFT JOIN
1154
                %sfaqdata_group fdg
1155
            ON
1156
                fd.id = fdg.record_id
1157
            LEFT JOIN
1158
                %sfaqdata_user fdu
1159
            ON
1160
                fd.id = fdu.record_id
1161
            WHERE
1162
                fd.solution_id = %d
1163
                %s',
1164
            PMF_Db::getTablePrefix(),
1165
            PMF_Db::getTablePrefix(),
1166
            PMF_Db::getTablePrefix(),
1167
            $solutionId,
1168
            $this->queryPermission($this->groupSupport)
1169
        );
1170
1171
        $result = $this->_config->getDb()->query($query);
1172
1173
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1174
            $question = nl2br($row->thema);
1175
            $content = $row->content;
1176
            $active = ('yes' == $row->active);
1177
            $expired = (date('YmdHis') > $row->date_end);
1178
1179
            if (!$active) {
1180
                $content = $this->pmf_lang['err_inactiveArticle'];
1181
            }
1182
            if ($expired) {
1183
                $content = $this->pmf_lang['err_expiredArticle'];
1184
            }
1185
1186
            $this->faqRecord = array(
1187
                'id' => $row->id,
1188
                'lang' => $row->lang,
1189
                'solution_id' => $row->solution_id,
1190
                'revision_id' => $row->revision_id,
1191
                'active' => $row->active,
1192
                'sticky' => $row->sticky,
1193
                'keywords' => $row->keywords,
1194
                'title' => $question,
1195
                'content' => $content,
1196
                'author' => $row->author,
1197
                'email' => $row->email,
1198
                'comment' => $row->comment,
1199
                'date' => PMF_Date::createIsoDate($row->updated),
1200
                'dateStart' => $row->date_start,
1201
                'dateEnd' => $row->date_end,
1202
                'linkState' => $row->links_state,
1203
                'linkCheckDate' => $row->links_check_date,
1204
            );
1205
        }
1206
    }
1207
1208
    /**
1209
     * Gets the record ID from a given solution ID.
1210
     *
1211
     * @param int $solutionId Solution ID
1212
     *
1213
     * @return array
1214
     */
1215
    public function getIdFromSolutionId($solutionId)
1216
    {
1217
        $query = sprintf('
1218
            SELECT
1219
                id, lang, content
1220
            FROM
1221
                %sfaqdata
1222
            WHERE
1223
                solution_id = %d',
1224
            PMF_Db::getTablePrefix(),
1225
            $solutionId
1226
        );
1227
1228
        $result = $this->_config->getDb()->query($query);
1229
1230
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1231
            return [
1232
                'id' => $row->id,
1233
                'lang' => $row->lang,
1234
                'content' => $row->content
1235
            ];
1236
        }
1237
1238
        return [];
1239
    }
1240
1241
    /**
1242
     * Returns the solution ID from a given ID and language
1243
     *
1244
     * @param integer $faqId
1245
     * @param string $faqLang
1246
     *
1247
     * @return int
1248
     */
1249 View Code Duplication
    public function getSolutionIdFromId($faqId, $faqLang)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1250
    {
1251
        $query = sprintf("
1252
            SELECT
1253
                solution_id
1254
            FROM
1255
                %sfaqdata
1256
            WHERE
1257
                id = %d
1258
                AND
1259
                lang = '%s'",
1260
            PMF_Db::getTablePrefix(),
1261
            (int) $faqId,
1262
            $this->_config->getDb()->escape($faqLang)
1263
        );
1264
1265
        $result = $this->_config->getDb()->query($query);
1266
1267
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1268
            return $row->solution_id;
1269
        }
1270
1271
        return $this->getSolutionId();
1272
    }
1273
1274
    /**
1275
     * Gets the latest solution id for a FAQ record.
1276
     *
1277
     * @return int
1278
     */
1279
    public function getSolutionId()
1280
    {
1281
        $latestId = 0;
1282
1283
        $query = sprintf('
1284
            SELECT
1285
                MAX(solution_id) AS solution_id
1286
            FROM
1287
                %sfaqdata',
1288
            PMF_Db::getTablePrefix()
1289
        );
1290
1291
        $result = $this->_config->getDb()->query($query);
1292
1293
        if ($result && $row = $this->_config->getDb()->fetchObject($result)) {
1294
            $latestId = $row->solution_id;
1295
        }
1296
1297
        if ($latestId < PMF_SOLUTION_ID_START_VALUE) {
1298
            $nextSolutionId = PMF_SOLUTION_ID_START_VALUE;
1299
        } else {
1300
            $nextSolutionId = $latestId + PMF_SOLUTION_ID_INCREMENT_VALUE;
1301
        }
1302
1303
        return $nextSolutionId;
1304
    }
1305
1306
    /**
1307
     * Returns an array with all data from all FAQ records.
1308
     *
1309
     * @param int    $sortType  Sorting type
1310
     * @param array  $condition Condition
1311
     * @param string $sortOrder Sorting order
1312
     */
1313
    public function getAllRecords($sortType = FAQ_SORTING_TYPE_CATID_FAQID, Array $condition = null, $sortOrder = 'ASC')
1314
    {
1315
        $where = '';
1316
        if (!is_null($condition)) {
1317
            $num = count($condition);
1318
            $where = 'WHERE ';
1319
            foreach ($condition as $field => $data) {
1320
                --$num;
1321
                $where .= $field;
1322
                if (is_array($data)) {
1323
                    $where .= ' IN (';
1324
                    $separator = '';
1325
                    foreach ($data as $value) {
1326
                        $where .= $separator."'".$this->_config->getDb()->escape($value)."'";
1327
                        $separator = ', ';
1328
                    }
1329
                    $where .= ')';
1330
                } else {
1331
                    $where .= " = '".$this->_config->getDb()->escape($data)."'";
1332
                }
1333
                if ($num > 0) {
1334
                    $where .= ' AND ';
1335
                }
1336
            }
1337
        }
1338
1339
        switch ($sortType) {
1340
1341
            case FAQ_SORTING_TYPE_CATID_FAQID:
1342
                $orderBy = sprintf('
1343
            ORDER BY
1344
                fcr.category_id,
1345
                fd.id %s',
1346
                    $sortOrder);
1347
                break;
1348
1349
            case FAQ_SORTING_TYPE_FAQID:
1350
                $orderBy = sprintf('
1351
            ORDER BY
1352
                fd.id %s',
1353
                    $sortOrder);
1354
                break;
1355
1356
            case FAQ_SORTING_TYPE_FAQTITLE_FAQID:
1357
                $orderBy = sprintf('
1358
            ORDER BY
1359
                fcr.category_id,
1360
                fd.thema %s',
1361
                    $sortOrder);
1362
                break;
1363
1364
            case FAQ_SORTING_TYPE_DATE_FAQID:
1365
                $orderBy = sprintf('
1366
            ORDER BY
1367
                fcr.category_id,
1368
                fd.updated %s',
1369
                    $sortOrder);
1370
                break;
1371
1372
            default:
1373
                $orderBy = '';
1374
                break;
1375
        }
1376
1377
        $query = sprintf('
1378
            SELECT
1379
                fd.id AS id,
1380
                fd.lang AS lang,
1381
                fcr.category_id AS category_id,
1382
                fd.solution_id AS solution_id,
1383
                fd.revision_id AS revision_id,
1384
                fd.active AS active,
1385
                fd.sticky AS sticky,
1386
                fd.keywords AS keywords,
1387
                fd.thema AS thema,
1388
                fd.content AS content,
1389
                fd.author AS author,
1390
                fd.email AS email,
1391
                fd.comment AS comment,
1392
                fd.updated AS updated,
1393
                fd.links_state AS links_state,
1394
                fd.links_check_date AS links_check_date,
1395
                fd.date_start AS date_start,
1396
                fd.date_end AS date_end,
1397
                fd.sticky AS sticky,
1398
                fd.created AS created
1399
            FROM
1400
                %sfaqdata fd
1401
            LEFT JOIN
1402
                %sfaqcategoryrelations fcr
1403
            ON
1404
                fd.id = fcr.record_id
1405
            AND
1406
                fd.lang = fcr.record_lang
1407
            %s
1408
            %s',
1409
            PMF_Db::getTablePrefix(),
1410
            PMF_Db::getTablePrefix(),
1411
            $where,
1412
            $orderBy
1413
        );
1414
1415
        $result = $this->_config->getDb()->query($query);
1416
1417
        while ($row = $this->_config->getDb()->fetchObject($result)) {
1418
            $content = $row->content;
1419
            $active = ('yes' == $row->active);
1420
            $expired = (date('YmdHis') > $row->date_end);
1421
1422
            if (!$active) {
1423
                $content = $this->pmf_lang['err_inactiveArticle'];
1424
            }
1425
            if ($expired) {
1426
                $content = $this->pmf_lang['err_expiredArticle'];
1427
            }
1428
1429
            $this->faqRecords[] = [
1430
                'id' => $row->id,
1431
                'category_id' => $row->category_id,
1432
                'lang' => $row->lang,
1433
                'solution_id' => $row->solution_id,
1434
                'revision_id' => $row->revision_id,
1435
                'active' => $row->active,
1436
                'sticky' => $row->sticky,
1437
                'keywords' => $row->keywords,
1438
                'title' => $row->thema,
1439
                'content' => $content,
1440
                'author' => $row->author,
1441
                'email' => $row->email,
1442
                'comment' => $row->comment,
1443
                'updated' => PMF_Date::createIsoDate($row->updated, 'Y-m-d H:i:s'),
1444
                'dateStart' => $row->date_start,
1445
                'dateEnd' => $row->date_end,
1446
                'created' => $row->created,
1447
            ];
1448
        }
1449
    }
1450
1451
    /**
1452
     * Returns the FAQ record title from the ID and language.
1453
     *
1454
     * @param int $id Record id
1455
     *
1456
     * @return string
1457
     */
1458
    public function getRecordTitle($id)
1459
    {
1460
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $id)) {
1461
            return $this->faqRecord['title'];
1462
        }
1463
1464
        $query = sprintf(
1465
            "SELECT
1466
                thema
1467
            FROM
1468
                %sfaqdata
1469
            WHERE
1470
                id = %d AND lang = '%s'",
1471
            PMF_Db::getTablePrefix(),
1472
            $id,
1473
            $this->_config->getLanguage()->getLanguage()
1474
            );
1475
        $result = $this->_config->getDb()->query($query);
1476
1477
        if ($this->_config->getDb()->numRows($result) > 0) {
1478
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1479
                $output = $row->thema;
1480
            }
1481
        } else {
1482
            $output = $this->pmf_lang['no_cats'];
1483
        }
1484
1485
        return $output;
1486
    }
1487
1488
    /**
1489
     * Gets all revisions from a given record ID.
1490
     *
1491
     * @param int    $recordId   Record id
1492
     * @param string $recordLang Record language
1493
     *
1494
     * @return array
1495
     */
1496
    public function getRevisionIds($recordId, $recordLang)
1497
    {
1498
        $revisionData = [];
1499
1500
        $query = sprintf("
1501
            SELECT
1502
                revision_id, updated, author
1503
            FROM
1504
                %sfaqdata_revisions
1505
            WHERE
1506
                id = %d
1507
            AND
1508
                lang = '%s'
1509
            ORDER BY
1510
                revision_id",
1511
            PMF_Db::getTablePrefix(),
1512
            $recordId,
1513
            $recordLang
1514
        );
1515
1516
        $result = $this->_config->getDb()->query($query);
1517
1518
        if ($this->_config->getDb()->numRows($result) > 0) {
1519
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1520
                $revisionData[] = [
1521
                    'revision_id' => $row->revision_id,
1522
                    'updated' => $row->updated,
1523
                    'author' => $row->author,
1524
                ];
1525
            }
1526
        }
1527
1528
        return $revisionData;
1529
    }
1530
1531
    /**
1532
     * Adds a new revision from a given record ID.
1533
     *
1534
     * @param int    $record_id   Record id
1535
     * @param string $record_lang Record language
1536
     *
1537
     * @return array
1538
     */
1539 View Code Duplication
    public function addNewRevision($record_id, $record_lang)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1540
    {
1541
        $query = sprintf("
1542
            INSERT INTO
1543
                %sfaqdata_revisions
1544
            SELECT * FROM
1545
                %sfaqdata
1546
            WHERE
1547
                id = %d
1548
            AND
1549
                lang = '%s'",
1550
            PMF_Db::getTablePrefix(),
1551
            PMF_Db::getTablePrefix(),
1552
            $record_id,
1553
            $record_lang);
1554
        $this->_config->getDb()->query($query);
1555
1556
        return true;
1557
    }
1558
1559
    /**
1560
     * Returns the keywords of a FAQ record from the ID and language.
1561
     *
1562
     * @param int $id record id
1563
     *
1564
     * @return string
1565
     */
1566
    public function getRecordKeywords($id)
1567
    {
1568
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $id)) {
1569
            return $this->faqRecord['keywords'];
1570
        }
1571
1572
        $query = sprintf(
1573
            "SELECT
1574
                keywords
1575
            FROM
1576
                %sfaqdata
1577
            WHERE id = %d AND lang = '%s'",
1578
            PMF_Db::getTablePrefix(),
1579
            $id,
1580
            $this->_config->getLanguage()->getLanguage());
1581
1582
        $result = $this->_config->getDb()->query($query);
1583
1584
        if ($this->_config->getDb()->numRows($result) > 0) {
1585
            $row = $this->_config->getDb()->fetchObject($result);
1586
1587
            return PMF_String::htmlspecialchars($row->keywords, ENT_QUOTES, 'utf-8');
1588
        } else {
1589
            return '';
1590
        }
1591
    }
1592
1593
    /**
1594
     * Returns a answer preview of the FAQ record.
1595
     *
1596
     * @param int $recordId  FAQ record ID
1597
     * @param int $wordCount Number of words, default: 12
1598
     *
1599
     * @return string
1600
     */
1601
    public function getRecordPreview($recordId, $wordCount = 12)
1602
    {
1603
        $answerPreview = '';
1604
1605
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $recordId)) {
1606
            $answerPreview = $this->faqRecord['content'];
1607
        }
1608
1609
        $query = sprintf("
1610
            SELECT
1611
                content as answer
1612
            FROM
1613
                %sfaqdata
1614
            WHERE 
1615
                id = %d 
1616
            AND 
1617
                lang = '%s'",
1618
            PMF_Db::getTablePrefix(),
1619
            $recordId,
1620
            $this->_config->getLanguage()->getLanguage());
1621
1622
        $result = $this->_config->getDb()->query($query);
1623
1624
        if ($this->_config->getDb()->numRows($result) > 0) {
1625
            $row = $this->_config->getDb()->fetchObject($result);
1626
            $answerPreview = strip_tags($row->answer);
1627
        } else {
1628
            $answerPreview = $this->_config->get('main.metaDescription');
1629
        }
1630
1631
        return PMF_Utils::makeShorterText($answerPreview, $wordCount);
1632
    }
1633
1634
    /**
1635
     * Returns the number of activated and not expired records, optionally
1636
     * not limited to the current language.
1637
     *
1638
     * @param string $language Language
1639
     *
1640
     * @return int
1641
     */
1642
    public function getNumberOfRecords($language = null)
1643
    {
1644
        $now = date('YmdHis');
1645
1646
        $query = sprintf("
1647
            SELECT
1648
                id
1649
            FROM
1650
                %sfaqdata
1651
            WHERE
1652
                active = 'yes'
1653
            %s
1654
            AND
1655
                date_start <= '%s'
1656
            AND
1657
                date_end   >= '%s'",
1658
            PMF_Db::getTablePrefix(),
1659
            null == $language ? '' : "AND lang = '".$language."'",
1660
            $now,
1661
            $now);
1662
1663
        $num = $this->_config->getDb()->numRows($this->_config->getDb()->query($query));
1664
1665
        if ($num > 0) {
1666
            return $num;
1667
        } else {
1668
            return 0;
1669
        }
1670
    }
1671
1672
    /**
1673
     * This function generates a list with the most voted or most visited records.
1674
     *
1675
     * @param string $type Type definition visits/voted
1676
     *
1677
     * @since  2009-11-03
1678
     *
1679
     * @author Max Köhler <[email protected]>
1680
     *
1681
     * @return array
1682
     */
1683
    public function getTopTen($type = 'visits')
1684
    {
1685
        if ('visits' == $type) {
1686
            $result = $this->getTopTenData(PMF_NUMBER_RECORDS_TOPTEN, 0, $this->_config->getLanguage()->getLanguage());
1687
        } else {
1688
            $result = $this->getTopVotedData(PMF_NUMBER_RECORDS_TOPTEN, 0, $this->_config->getLanguage()->getLanguage());
1689
        }
1690
        $output = [];
1691
1692
        if (count($result) > 0) {
1693
            foreach ($result as $row) {
1694
                if ('visits' == $type) {
1695
                    $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1696
                    $output['preview'][] = $row['question'];
1697
                    $output['url'][] = $row['url'];
1698
                    $output['visits'][] = $this->plr->GetMsg('plmsgViews', $row['visits']);
1699
                } else {
1700
                    $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1701
                    $output['preview'][] = $row['question'];
1702
                    $output['url'][] = $row['url'];
1703
                    $output['voted'][] = sprintf(
1704
                        '%s %s 5 - %s',
1705
                        round($row['avg'], 2),
1706
                        $this->pmf_lang['msgVoteFrom'],
1707
                        $this->plr->GetMsg('plmsgVotes', $row['user'])
1708
                    );
1709
                }
1710
            }
1711
        } else {
1712
            $output['error'] = $this->pmf_lang['err_noTopTen'];
1713
        }
1714
1715
        return $output;
1716
    }
1717
1718
    /**
1719
     * This function generates the list with the latest published records.
1720
     *
1721
     * @return array
1722
     */
1723
    public function getLatest()
1724
    {
1725
        $date = new PMF_Date($this->_config);
1726
        $result = $this->getLatestData(PMF_NUMBER_RECORDS_LATEST, $this->_config->getLanguage()->getLanguage());
1727
        $output = [];
1728
1729
        if (count($result) > 0) {
1730
            foreach ($result as $row) {
1731
                $output['url'][] = $row['url'];
1732
                $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1733
                $output['preview'][] = $row['question'];
1734
                $output['date'][] = $date->format(PMF_Date::createIsoDate($row['date']));
1735
            }
1736
        } else {
1737
            $output['error'] = $this->pmf_lang['err_noArticles'];
1738
        }
1739
1740
        return $output;
1741
    }
1742
1743
    /**
1744
     * Deletes a question for the table faqquestions.
1745
     *
1746
     * @param int $questionId
1747
     *
1748
     * @return bool
1749
     */
1750 View Code Duplication
    public function deleteQuestion($questionId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1751
    {
1752
        $delete = sprintf("
1753
            DELETE FROM
1754
                %sfaqquestions
1755
            WHERE
1756
                id = %d
1757
            AND
1758
                lang = '%s'",
1759
            PMF_Db::getTablePrefix(),
1760
            $questionId,
1761
            $this->_config->getLanguage()->getLanguage()
1762
        );
1763
1764
        $this->_config->getDb()->query($delete);
1765
1766
        return true;
1767
    }
1768
1769
     /**
1770
      * Returns the visibility of a question.
1771
      *
1772
      * @param   int $questionId
1773
      *
1774
      * @return  string
1775
      */
1776 View Code Duplication
     public function getVisibilityOfQuestion($questionId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1777
     {
1778
         $query = sprintf("
1779
            SELECT
1780
                is_visible
1781
            FROM
1782
                %sfaqquestions
1783
            WHERE
1784
                id = %d
1785
            AND
1786
                lang = '%s'",
1787
            PMF_Db::getTablePrefix(),
1788
            $questionId,
1789
            $this->_config->getLanguage()->getLanguage()
1790
        );
1791
1792
         $result = $this->_config->getDb()->query($query);
1793
         if ($this->_config->getDb()->numRows($result) > 0) {
1794
             $row = $this->_config->getDb()->fetchObject($result);
1795
1796
             return $row->is_visible;
1797
         }
1798
1799
         return;
1800
     }
1801
1802
    /**
1803
     * Sets the visibilty of a question.
1804
     *
1805
     * @param int    $questionId
1806
     * @param string $is_visible
0 ignored issues
show
Bug introduced by
There is no parameter named $is_visible. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1807
     *
1808
     * @return bool
1809
     */
1810 View Code Duplication
    public function setVisibilityOfQuestion($questionId, $isVisible)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1811
    {
1812
        $query = sprintf("
1813
            UPDATE
1814
                %sfaqquestions
1815
            SET
1816
                is_visible = '%s'
1817
            WHERE
1818
                id = %d
1819
            AND
1820
                lang = '%s'",
1821
            PMF_Db::getTablePrefix(),
1822
            $isVisible,
1823
            $questionId,
1824
            $this->_config->getLanguage()->getLanguage()
1825
        );
1826
1827
        $this->_config->getDb()->query($query);
1828
1829
        return true;
1830
    }
1831
1832
    /**
1833
     * This function generates a data-set with the mosted voted recors.
1834
     *  
1835
     * @param int    $count    Number of records
1836
     * @param int    $category Category ID
1837
     * @param string $language Language
1838
     *
1839
     * @return array
1840
     */
1841
    public function getTopVotedData($count = PMF_NUMBER_RECORDS_TOPTEN, $category = 0, $language = null)
0 ignored issues
show
Unused Code introduced by
The parameter $category is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1842
    {
1843
        global $sids;
1844
1845
        $now = date('YmdHis');
1846
        $query =
1847
'            SELECT
1848
                fd.id AS id,
1849
                fd.lang AS lang,
1850
                fd.thema AS thema,
1851
                fd.updated AS updated,
1852
                fcr.category_id AS category_id,
1853
                (fv.vote/fv.usr) AS avg,
1854
                fv.usr AS user
1855
            FROM
1856
                '.PMF_Db::getTablePrefix().'faqvoting fv,
1857
                '.PMF_Db::getTablePrefix().'faqdata fd
1858
            LEFT JOIN
1859
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
1860
            ON
1861
                fd.id = fcr.record_id
1862
            AND
1863
                fd.lang = fcr.record_lang
1864
            LEFT JOIN
1865
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
1866
            ON
1867
                fd.id = fdg.record_id
1868
            LEFT JOIN
1869
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
1870
            ON
1871
                fd.id = fdu.record_id
1872
            WHERE
1873
                    fd.date_start <= \''.$now.'\'
1874
                AND fd.date_end   >= \''.$now.'\'
1875
                AND fd.id = fv.artikel
1876
                AND fd.active = \'yes\'';
1877
1878 View Code Duplication
        if (isset($categoryId) && is_numeric($categoryId) && ($categoryId != 0)) {
1879
            $query .= '
1880
            AND
1881
                fcr.category_id = \''.$categoryId.'\'';
1882
        }
1883
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
1884
            $query .= '
1885
            AND
1886
                fd.lang = \''.$language.'\'';
1887
        }
1888
        $query .= '
1889
                '.$this->queryPermission($this->groupSupport).'
1890
            ORDER BY
1891
                avg DESC';
1892
1893
        $result = $this->_config->getDb()->query($query);
1894
        $topten = [];
1895
        $data = [];
1896
1897
        $i = 1;
1898
        $oldId = 0;
1899
        while (($row = $this->_config->getDb()->fetchObject($result)) && $i <= $count) {
1900
            if ($oldId != $row->id) {
1901
                $data['avg'] = $row->avg;
1902
                $data['question'] = $row->thema;
1903
                $data['date'] = $row->updated;
1904
                $data['user'] = $row->user;
1905
1906
                $title = $row->thema;
1907
                $url = sprintf(
1908
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
1909
                    PMF_Link::getSystemRelativeUri(),
1910
                    $sids,
1911
                    $row->category_id,
1912
                    $row->id,
1913
                    $row->lang
1914
                );
1915
                $oLink = new PMF_Link($url, $this->_config);
1916
                $oLink->itemTitle = $row->thema;
1917
                $oLink->tooltip = $title;
1918
                $data['url'] = $oLink->toString();
1919
1920
                $topten[] = $data;
1921
                ++$i;
1922
            }
1923
            $oldId = $row->id;
1924
        }
1925
1926
        return $topten;
1927
    }
1928
1929
    /**
1930
     * This function generates the Top Ten data with the mosted viewed records.
1931
     *
1932
     * @param int    $count      Number of records
1933
     * @param int    $categoryId Category ID
1934
     * @param string $language   Language
1935
     *
1936
     * @return array
1937
     */
1938
    public function getTopTenData($count = PMF_NUMBER_RECORDS_TOPTEN, $categoryId = 0, $language = null)
1939
    {
1940
        global $sids;
1941
1942
        $now = date('YmdHis');
1943
        $query =
1944
'            SELECT
1945
                fd.id AS id,
1946
                fd.lang AS lang,
1947
                fd.thema AS thema,
1948
                fd.updated AS updated,
1949
                fcr.category_id AS category_id,
1950
                fv.visits AS visits,
1951
                fv.last_visit AS last_visit,
1952
                fdg.group_id AS group_id,
1953
                fdu.user_id AS user_id
1954
            FROM
1955
                '.PMF_Db::getTablePrefix().'faqvisits fv,
1956
                '.PMF_Db::getTablePrefix().'faqdata fd
1957
            LEFT JOIN
1958
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
1959
            ON
1960
                fd.id = fcr.record_id
1961
            AND
1962
                fd.lang = fcr.record_lang
1963
            LEFT JOIN
1964
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
1965
            ON
1966
                fd.id = fdg.record_id
1967
            LEFT JOIN
1968
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
1969
            ON
1970
                fd.id = fdu.record_id
1971
            WHERE
1972
                    fd.date_start <= \''.$now.'\'
1973
                AND fd.date_end   >= \''.$now.'\'
1974
                AND fd.id = fv.id
1975
                AND fd.lang = fv.lang
1976
                AND fd.active = \'yes\'';
1977
1978 View Code Duplication
        if (isset($categoryId) && is_numeric($categoryId) && ($categoryId != 0)) {
1979
            $query .= '
1980
            AND
1981
                fcr.category_id = \''.$categoryId.'\'';
1982
        }
1983
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
1984
            $query .= '
1985
            AND
1986
                fd.lang = \''.$language.'\'';
1987
        }
1988
        $query .= '
1989
                '.$this->queryPermission($this->groupSupport).'
1990
1991
            GROUP BY
1992
                fd.id,fd.lang,fcr.category_id,fv.visits,fv.last_visit,fdg.group_id,fdu.user_id
1993
            ORDER BY
1994
                fv.visits DESC';
1995
1996
        $result = $this->_config->getDb()->query($query, 0, $count);
1997
        $topten = [];
1998
        $data = [];
1999
2000 View Code Duplication
        while ($row = $this->_config->getDb()->fetchObject($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2001
            if ($this->groupSupport) {
2002
                if (!in_array($row->user_id, array(-1, $this->user)) || !in_array($row->group_id, $this->groups)) {
2003
                    continue;
2004
                }
2005
            } else {
2006
                if (!in_array($row->user_id, array(-1, $this->user))) {
2007
                    continue;
2008
                }
2009
            }
2010
2011
            $data['visits'] = $row->visits;
2012
            $data['question'] = $row->thema;
2013
            $data['date'] = $row->updated;
2014
            $data['last_visit'] = $row->last_visit;
2015
2016
            $title = $row->thema;
2017
            $url = sprintf(
2018
                '%sindex.php?%saction=artikel&cat=%d&id=%d&artlang=%s',
2019
                $this->_config->getDefaultUrl(),
2020
                $sids,
2021
                $row->category_id,
2022
                $row->id,
2023
                $row->lang
2024
            );
2025
            $oLink = new PMF_Link($url, $this->_config);
2026
            $oLink->itemTitle = $row->thema;
2027
            $oLink->tooltip = $title;
2028
            $data['url'] = $oLink->toString();
2029
2030
            $topten[] = $data;
2031
        }
2032
2033
        return $topten;
2034
    }
2035
2036
    /**
2037
     * This function generates an array with a specified number of most recent
2038
     * published records.
2039
     *
2040
     * @param int    $count    Number of records
2041
     * @param string $language Language
2042
     *
2043
     * @return array
2044
     */
2045
    public function getLatestData($count = PMF_NUMBER_RECORDS_LATEST, $language = null)
2046
    {
2047
        global $sids;
2048
2049
        $now = date('YmdHis');
2050
        $query =
2051
'            SELECT
2052
                fd.id AS id,
2053
                fd.lang AS lang,
2054
                fcr.category_id AS category_id,
2055
                fd.thema AS thema,
2056
                fd.content AS content,
2057
                fd.updated AS updated,
2058
                fv.visits AS visits,
2059
                fdg.group_id AS group_id,
2060
                fdu.user_id AS user_id
2061
            FROM
2062
                '.PMF_Db::getTablePrefix().'faqvisits fv,
2063
                '.PMF_Db::getTablePrefix().'faqdata fd
2064
            LEFT JOIN
2065
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
2066
            ON
2067
                fd.id = fcr.record_id
2068
            AND
2069
                fd.lang = fcr.record_lang
2070
            LEFT JOIN
2071
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
2072
            ON
2073
                fd.id = fdg.record_id
2074
            LEFT JOIN
2075
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
2076
            ON
2077
                fd.id = fdu.record_id
2078
            WHERE
2079
                    fd.date_start <= \''.$now.'\'
2080
                AND fd.date_end   >= \''.$now.'\'
2081
                AND fd.id = fv.id
2082
                AND fd.lang = fv.lang
2083
                AND fd.active = \'yes\'';
2084
2085
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
2086
            $query .= '
2087
            AND
2088
                fd.lang = \''.$language.'\'';
2089
        }
2090
        $query .= '
2091
                '.$this->queryPermission($this->groupSupport).'
2092
            GROUP BY
2093
                fd.id,fd.lang,fcr.category_id,fv.visits,fdg.group_id,fdu.user_id
2094
            ORDER BY
2095
                fd.updated DESC';
2096
2097
        $result = $this->_config->getDb()->query($query, 0, $count);
2098
        $latest = [];
2099
        $data = [];
2100
2101 View Code Duplication
        while (($row = $this->_config->getDb()->fetchObject($result))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2102
            if ($this->groupSupport) {
2103
                if (!in_array($row->user_id, array(-1, $this->user)) || !in_array($row->group_id, $this->groups)) {
2104
                    continue;
2105
                }
2106
            } else {
2107
                if (!in_array($row->user_id, array(-1, $this->user))) {
2108
                    continue;
2109
                }
2110
            }
2111
2112
            $data['date'] = $row->updated;
2113
            $data['question'] = $row->thema;
2114
            $data['answer'] = $row->content;
2115
            $data['visits'] = $row->visits;
2116
2117
            $title = $row->thema;
2118
            $url = sprintf(
2119
                '%sindex.php?%saction=artikel&cat=%d&id=%d&artlang=%s',
2120
                $this->_config->getDefaultUrl(),
2121
                $sids,
2122
                $row->category_id,
2123
                $row->id,
2124
                $row->lang
2125
            );
2126
            $oLink = new PMF_Link($url, $this->_config);
2127
            $oLink->itemTitle = $row->thema;
2128
            $oLink->tooltip = $title;
2129
            $data['url'] = $oLink->toString();
2130
2131
            $latest[] = $data;
2132
        }
2133
2134
        return $latest;
2135
    }
2136
2137
    /**
2138
     * Reload locking for user votings.
2139
     *
2140
     * @param int    $id FAQ record id
2141
     * @param string $ip IP
2142
     *
2143
     * @return bool
2144
     */
2145
    public function votingCheck($id, $ip)
2146
    {
2147
        $check = $_SERVER['REQUEST_TIME'] - 300;
2148
        $query = sprintf(
2149
            "SELECT
2150
                id
2151
            FROM
2152
                %sfaqvoting
2153
            WHERE
2154
                artikel = %d AND (ip = '%s' AND datum > '%s')",
2155
            PMF_Db::getTablePrefix(),
2156
            $id,
2157
            $ip,
2158
            $check);
2159
        if ($this->_config->getDb()->numRows($this->_config->getDb()->query($query))) {
2160
            return false;
2161
        }
2162
2163
        return true;
2164
    }
2165
2166
    /**
2167
     * Returns the number of users from the table faqvotings.
2168
     *
2169
     * @param int $record_id
2170
     *
2171
     * @return int
2172
     *
2173
     * @since   2006-06-18
2174
     *
2175
     * @author  Thorsten Rinne <[email protected]>
2176
     */
2177 View Code Duplication
    public function getNumberOfVotings($record_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2178
    {
2179
        $query = sprintf(
2180
            'SELECT
2181
                usr
2182
            FROM
2183
                %sfaqvoting
2184
            WHERE
2185
                artikel = %d',
2186
            PMF_Db::getTablePrefix(),
2187
            $record_id);
2188
        if ($result = $this->_config->getDb()->query($query)) {
2189
            if ($row = $this->_config->getDb()->fetchObject($result)) {
2190
                return $row->usr;
2191
            }
2192
        }
2193
2194
        return 0;
2195
    }
2196
2197
    /**
2198
     * Adds a new voting record.
2199
     *
2200
     * @param array $votingData
2201
     *
2202
     * @return bool
2203
     *
2204
     * @since    2006-06-18
2205
     *
2206
     * @author   Thorsten Rinne <[email protected]>
2207
     */
2208
    public function addVoting($votingData)
2209
    {
2210
        if (!is_array($votingData)) {
2211
            return false;
2212
        }
2213
2214
        $query = sprintf(
2215
            "INSERT INTO
2216
                %sfaqvoting
2217
            VALUES
2218
                (%d, %d, %d, 1, %d, '%s')",
2219
            PMF_Db::getTablePrefix(),
2220
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqvoting', 'id'),
2221
            $votingData['record_id'],
2222
            $votingData['vote'],
2223
            $_SERVER['REQUEST_TIME'],
2224
            $votingData['user_ip']);
2225
        $this->_config->getDb()->query($query);
2226
2227
        return true;
2228
    }
2229
2230
    /**
2231
     * Adds a new question.
2232
     *
2233
     * @param array $questionData
2234
     *
2235
     * @return bool
2236
     */
2237
    public function addQuestion(Array $questionData)
2238
    {
2239
        $query = sprintf("
2240
            INSERT INTO
2241
                %sfaqquestions
2242
            VALUES
2243
                (%d, '%s', '%s', '%s', %d, '%s', '%s', '%s', %d)",
2244
            PMF_Db::getTablePrefix(),
2245
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqquestions', 'id'),
2246
            $this->_config->getLanguage()->getLanguage(),
2247
            $this->_config->getDb()->escape($questionData['username']),
2248
            $this->_config->getDb()->escape($questionData['email']),
2249
            $questionData['category_id'],
2250
            $this->_config->getDb()->escape($questionData['question']),
2251
            date('YmdHis'),
2252
            $questionData['is_visible'],
2253
            0
2254
        );
2255
        $this->_config->getDb()->query($query);
2256
2257
        return true;
2258
    }
2259
2260
    /**
2261
     * Returns a new question.
2262
     *
2263
     * @param int $questionId
2264
     *
2265
     * @return array
2266
     *
2267
     * @since    2006-11-11
2268
     *
2269
     * @author   Thorsten Rinne <[email protected]>
2270
     */
2271
    public function getQuestion($questionId)
2272
    {
2273
        $question = [
2274
            'id' => 0,
2275
            'lang' => '',
2276
            'username' => '',
2277
            'email' => '',
2278
            'category_id' => '',
2279
            'question' => '',
2280
            'created' => '',
2281
            'is_visible' => '',
2282
        ];
2283
2284
        if (!is_int($questionId)) {
2285
            return $question;
2286
        }
2287
2288
        $question = [];
2289
2290
        $query = sprintf("
2291
            SELECT
2292
                 id, lang, username, email, category_id, question, created, is_visible
2293
            FROM
2294
                %sfaqquestions
2295
            WHERE
2296
                id = %d
2297
            AND
2298
                lang = '%s'",
2299
            PMF_Db::getTablePrefix(),
2300
            $questionId,
2301
            $this->_config->getLanguage()->getLanguage()
2302
        );
2303
2304 View Code Duplication
        if ($result = $this->_config->getDb()->query($query)) {
2305
            if ($row = $this->_config->getDb()->fetchObject($result)) {
2306
                $question = array(
2307
                    'id' => $row->id,
2308
                    'lang' => $row->lang,
2309
                    'username' => $row->username,
2310
                    'email' => $row->email,
2311
                    'category_id' => $row->category_id,
2312
                    'question' => $row->question,
2313
                    'created' => $row->created,
2314
                    'is_visible' => $row->is_visible, );
2315
            }
2316
        }
2317
2318
        return $question;
2319
    }
2320
2321
     /**
2322
      * Returns all open questions.
2323
      *
2324
      * @param  $all boolean If true, then return visible and unvisble questions; otherwise only visible ones
2325
      *
2326
      * @return array
2327
      */
2328
     public function getAllOpenQuestions($all = true)
2329
     {
2330
         $questions = [];
2331
2332
         $query = sprintf("
2333
            SELECT
2334
                id, lang, username, email, category_id, question, created, answer_id, is_visible
2335
            FROM
2336
                %sfaqquestions
2337
            WHERE
2338
                lang = '%s'
2339
                %s
2340
            ORDER BY 
2341
                created ASC",
2342
            PMF_Db::getTablePrefix(),
2343
            $this->_config->getLanguage()->getLanguage(),
2344
            ($all == false ? " AND is_visible = 'Y'" : '')
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
2345
        );
2346
2347 View Code Duplication
         if ($result = $this->_config->getDb()->query($query)) {
2348
             while ($row = $this->_config->getDb()->fetchObject($result)) {
2349
                 $questions[] = array(
2350
                    'id' => $row->id,
2351
                    'lang' => $row->lang,
2352
                    'username' => $row->username,
2353
                    'email' => $row->email,
2354
                    'category_id' => $row->category_id,
2355
                    'question' => $row->question,
2356
                    'created' => $row->created,
2357
                    'answer_id' => $row->answer_id,
2358
                    'is_visible' => $row->is_visible,
2359
                );
2360
             }
2361
         }
2362
2363
         return $questions;
2364
     }
2365
2366
    /**
2367
     * Updates an existing voting record.
2368
     *
2369
     * @param array $votingData
2370
     *
2371
     * @return bool
2372
     *
2373
     * @since    2006-06-18
2374
     *
2375
     * @author   Thorsten Rinne <[email protected]>
2376
     */
2377
    public function updateVoting($votingData)
2378
    {
2379
        if (!is_array($votingData)) {
2380
            return false;
2381
        }
2382
2383
        $query = sprintf(
2384
            "UPDATE
2385
                %sfaqvoting
2386
            SET
2387
                vote    = vote + %d,
2388
                usr     = usr + 1,
2389
                datum   = %d,
2390
                ip      = '%s'
2391
            WHERE
2392
                artikel = %d",
2393
            PMF_Db::getTablePrefix(),
2394
            $votingData['vote'],
2395
            $_SERVER['REQUEST_TIME'],
2396
            $votingData['user_ip'],
2397
            $votingData['record_id']);
2398
        $this->_config->getDb()->query($query);
2399
2400
        return true;
2401
    }
2402
2403
    /**
2404
     * Adds a new changelog entry in the table faqchanges.
2405
     *
2406
     * @param int    $id
2407
     * @param int    $userId
2408
     * @param string $text
2409
     * @param string $lang
2410
     * @param int    $revision_id
2411
     *
2412
     * @return bool
2413
     *
2414
     * @since   2006-08-18
2415
     *
2416
     * @author  Thorsten Rinne <[email protected]>
2417
     * @author  Matteo Scaramuccia <[email protected]>
2418
     */
2419
    public function createChangeEntry($id, $userId, $text, $lang, $revision_id = 0)
2420
    {
2421
        if (!is_numeric($id)
2422
            && !is_numeric($userId)
2423
            && !is_string($text)
2424
            && !is_string($lang)
2425
            ) {
2426
            return false;
2427
        }
2428
2429
        $query = sprintf(
2430
            "INSERT INTO
2431
                %sfaqchanges
2432
            (id, beitrag, lang, revision_id, usr, datum, what)
2433
                VALUES
2434
            (%d, %d, '%s', %d, %d, %d, '%s')",
2435
            PMF_Db::getTablePrefix(),
2436
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqchanges', 'id'),
2437
            $id,
2438
            $lang,
2439
            $revision_id,
2440
            $userId,
2441
            $_SERVER['REQUEST_TIME'],
2442
            $text);
2443
2444
        $this->_config->getDb()->query($query);
2445
2446
        return true;
2447
    }
2448
2449
    /**
2450
     * Returns the changelog of a FAQ record.
2451
     *
2452
     * @param int $record_id
2453
     *
2454
     * @return array
2455
     *
2456
     * @since   2007-03-03
2457
     *
2458
     * @author  Thorsten Rinne <[email protected]>
2459
     */
2460 View Code Duplication
    public function getChangeEntries($record_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2461
    {
2462
        $entries = [];
2463
2464
        $query = sprintf('
2465
            SELECT
2466
                DISTINCT revision_id, usr, datum, what
2467
            FROM
2468
                %sfaqchanges
2469
            WHERE
2470
                beitrag = %d
2471
            ORDER BY id DESC',
2472
            PMF_Db::getTablePrefix(),
2473
            $record_id
2474
            );
2475
2476
        if ($result = $this->_config->getDb()->query($query)) {
2477
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2478
                $entries[] = array(
2479
                    'revision_id' => $row->revision_id,
2480
                    'user' => $row->usr,
2481
                    'date' => $row->datum,
2482
                    'changelog' => $row->what, );
2483
            }
2484
        }
2485
2486
        return $entries;
2487
    }
2488
2489
    /**
2490
     * Retrieve faq records according to the constraints provided.
2491
     *
2492
     * @param string $QueryType
2493
     * @param int    $nCatid
2494
     * @param bool   $bDownwards
2495
     * @param string $lang
2496
     * @param string $date
2497
     *
2498
     * @return array
2499
     */
2500
    public function get($QueryType = FAQ_QUERY_TYPE_DEFAULT, $nCatid = 0, $bDownwards = true, $lang = '', $date = '')
2501
    {
2502
        $faqs = [];
2503
2504
        $result = $this->_config->getDb()->query($this->_getSQLQuery($QueryType, $nCatid, $bDownwards, $lang, $date));
2505
2506
        if ($this->_config->getDb()->numRows($result) > 0) {
2507
            $i = 0;
2508
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2509
                $faq = [];
2510
                $faq['id'] = $row->id;
2511
                $faq['solution_id'] = $row->solution_id;
2512
                $faq['revision_id'] = $row->revision_id;
2513
                $faq['lang'] = $row->lang;
2514
                $faq['category_id'] = $row->category_id;
2515
                $faq['active'] = $row->active;
2516
                $faq['sticky'] = $row->sticky;
2517
                $faq['keywords'] = $row->keywords;
2518
                $faq['topic'] = $row->thema;
2519
                $faq['content'] = $row->content;
2520
                $faq['author_name'] = $row->author;
2521
                $faq['author_email'] = $row->email;
2522
                $faq['comment_enable'] = $row->comment;
2523
                $faq['lastmodified'] = $row->updated;
2524
                $faq['hits'] = $row->visits;
2525
                $faq['hits_last'] = $row->last_visit;
2526
                $faqs[$i] = $faq;
2527
                ++$i;
2528
            }
2529
        }
2530
2531
        return $faqs;
2532
    }
2533
2534
    /**
2535
     * Build a logic sequence, for a WHERE statement, of those category IDs
2536
     * children of the provided category ID, if any.
2537
     *
2538
     * @param   $nCatid
2539
     * @param   $logicOp
2540
     * @param   $oCat
2541
     *
2542
     * @return string
2543
     *
2544
     * @since   2005-11-02
2545
     *
2546
     * @author  Matteo Scaramuccia <[email protected]>
2547
     */
2548
    public function _getCatidWhereSequence($nCatid, $logicOp = 'OR', $oCat = null)
2549
    {
2550
        $sqlWherefilter = '';
2551
2552
        if (!isset($oCat)) {
2553
            $oCat = new PMF_Category($this->_config);
2554
        }
2555
        $aChildren = array_values($oCat->getChildren($nCatid));
2556
2557
        foreach ($aChildren as $catid) {
2558
            $sqlWherefilter .= ' '.$logicOp.' fcr.category_id = '.$catid;
2559
            $sqlWherefilter .= $this->_getCatidWhereSequence($catid, 'OR', $oCat);
2560
        }
2561
2562
        return $sqlWherefilter;
2563
    }
2564
2565
    /**
2566
     * Build the SQL query for retrieving faq records according to the constraints provided.
2567
     *
2568
     * @param   $QueryType
2569
     * @param   $nCatid
2570
     * @param   $bDownwards
2571
     * @param   $lang
2572
     * @param   $date
2573
     * @param   $faqid
2574
     *
2575
     * @return array
2576
     *
2577
     * @since   2005-11-02
2578
     *
2579
     * @author  Matteo Scaramuccia <[email protected]>
2580
     */
2581
    private function _getSQLQuery($QueryType, $nCatid, $bDownwards, $lang, $date, $faqid = 0)
2582
    {
2583
        $now = date('YmdHis');
2584
        $query = sprintf("
2585
            SELECT
2586
                fd.id AS id,
2587
                fd.solution_id AS solution_id,
2588
                fd.revision_id AS revision_id,
2589
                fd.lang AS lang,
2590
                fcr.category_id AS category_id,
2591
                fd.active AS active,
2592
                fd.sticky AS sticky,
2593
                fd.keywords AS keywords,
2594
                fd.thema AS thema,
2595
                fd.content AS content,
2596
                fd.author AS author,
2597
                fd.email AS email,
2598
                fd.comment AS comment,
2599
                fd.updated AS updated,
2600
                fv.visits AS visits,
2601
                fv.last_visit AS last_visit
2602
            FROM
2603
                %sfaqdata fd,
2604
                %sfaqvisits fv,
2605
                %sfaqcategoryrelations fcr
2606
            WHERE
2607
                fd.id = fcr.record_id
2608
            AND
2609
                fd.lang = fcr.record_lang
2610
            AND
2611
                fd.date_start <= '%s'
2612
            AND
2613
                fd.date_end   >= '%s'
2614
            AND ",
2615
            PMF_Db::getTablePrefix(),
2616
            PMF_Db::getTablePrefix(),
2617
            PMF_Db::getTablePrefix(),
2618
            $now,
2619
            $now);
2620
        // faqvisits data selection
2621
        if (!empty($faqid)) {
2622
            // Select ONLY the faq with the provided $faqid
2623
            $query .= "fd.id = '".$faqid."' AND ";
2624
        }
2625
        $query .= 'fd.id = fv.id
2626
            AND
2627
                fd.lang = fv.lang';
2628
        $needAndOp = true;
2629
        if ((!empty($nCatid)) && is_int($nCatid) && $nCatid > 0) {
2630
            if ($needAndOp) {
2631
                $query .= ' AND';
2632
            }
2633
            $query .= ' (fcr.category_id = '.$nCatid;
2634
            if ($bDownwards) {
2635
                $query .= $this->_getCatidWhereSequence($nCatid, 'OR');
2636
            }
2637
            $query .= ')';
2638
            $needAndOp = true;
2639
        }
2640 View Code Duplication
        if ((!empty($date)) && PMF_Utils::isLikeOnPMFDate($date)) {
2641
            if ($needAndOp) {
2642
                $query .= ' AND';
2643
            }
2644
            $query .= " fd.updated LIKE '".$date."'";
2645
            $needAndOp = true;
2646
        }
2647 View Code Duplication
        if ((!empty($lang)) && PMF_Utils::isLanguage($lang)) {
2648
            if ($needAndOp) {
2649
                $query .= ' AND';
2650
            }
2651
            $query .= " fd.lang = '".$lang."'";
2652
            $needAndOp = true;
2653
        }
2654
        switch ($QueryType) {
2655
            case FAQ_QUERY_TYPE_APPROVAL:
2656
                if ($needAndOp) {
2657
                    $query .= ' AND';
2658
                }
2659
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_NO."'";
2660
                $needAndOp = true;
2661
                break;
2662
            case FAQ_QUERY_TYPE_EXPORT_PDF:
2663
            case FAQ_QUERY_TYPE_EXPORT_XHTML:
2664 View Code Duplication
            case FAQ_QUERY_TYPE_EXPORT_XML:
2665
                if ($needAndOp) {
2666
                    $query .= ' AND';
2667
                }
2668
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_YES."'";
2669
                $needAndOp = true;
2670
                break;
2671 View Code Duplication
            default:
2672
                if ($needAndOp) {
2673
                    $query .= ' AND';
2674
                }
2675
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_YES."'";
2676
                $needAndOp = true;
2677
                break;
2678
        }
2679
        // Sort criteria
2680
        switch ($QueryType) {
2681
            case FAQ_QUERY_TYPE_EXPORT_PDF:
2682
            case FAQ_QUERY_TYPE_EXPORT_XHTML:
2683
            case FAQ_QUERY_TYPE_EXPORT_XML:
2684
                $query .= "\nORDER BY fcr.category_id, fd.id";
2685
                break;
2686
            case FAQ_QUERY_TYPE_RSS_LATEST:
2687
                $query .= "\nORDER BY fd.updated DESC";
2688
                break;
2689
            default:
2690
                // Normal ordering
2691
                $query .= "\nORDER BY fcr.category_id, fd.id";
2692
                break;
2693
        }
2694
2695
        return $query;
2696
    }
2697
2698
    /**
2699
     * Adds the record permissions for users and groups.
2700
     *
2701
     * @param string $mode     'group' or 'user'
2702
     * @param int    $recordId ID of the current record
2703
     * @param array  $ids      Array of group or user IDs
2704
     *
2705
     * @return bool
2706
     */
2707
    public function addPermission($mode, $recordId, $ids)
2708
    {
2709
        if ('user' !== $mode && 'group' !== $mode) {
2710
            return false;
2711
        }
2712
2713
        foreach ($ids as $id) {
2714
            $query = sprintf('
2715
            INSERT INTO
2716
                %sfaqdata_%s
2717
            (record_id, %s_id)
2718
                VALUES
2719
            (%d, %d)',
2720
                PMF_Db::getTablePrefix(),
2721
                $mode,
2722
                $mode,
2723
                $recordId,
2724
                $id
2725
            );
2726
2727
            $this->_config->getDb()->query($query);
2728
        }
2729
2730
        return true;
2731
    }
2732
2733
    /**
2734
     * Deletes the record permissions for users and groups.
2735
     *
2736
     * @param string $mode      'group' or 'user'
2737
     * @param int    $record_id ID of the current record
2738
     *
2739
     * @return bool
2740
     *
2741
     * @author  Thorsten Rinne <[email protected]>
2742
     */
2743 View Code Duplication
    public function deletePermission($mode, $record_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2744
    {
2745
        if (!($mode == 'user' || $mode == 'group')) {
2746
            return false;
2747
        }
2748
        if (!is_int($record_id)) {
2749
            return false;
2750
        }
2751
2752
        $query = sprintf('
2753
            DELETE FROM
2754
                %sfaqdata_%s
2755
            WHERE
2756
                record_id = %d',
2757
            PMF_Db::getTablePrefix(),
2758
            $mode,
2759
            $record_id);
2760
        $this->_config->getDb()->query($query);
2761
2762
        return true;
2763
    }
2764
2765
    /**
2766
     * Returns the record permissions for users and groups.
2767
     *
2768
     * @param string $mode     'group' or 'user'
2769
     * @param int    $recordId
2770
     *
2771
     * @return array
2772
     *
2773
     * @author  Thorsten Rinne <[email protected]>
2774
     */
2775
    public function getPermission($mode, $recordId)
2776
    {
2777
        $permissions = [];
2778
2779
        if (!($mode == 'user' || $mode == 'group')) {
2780
            return false;
2781
        }
2782
2783
        $query = sprintf('
2784
            SELECT
2785
                %s_id AS permission
2786
            FROM
2787
                %sfaqdata_%s
2788
            WHERE
2789
                record_id = %d',
2790
            $mode,
2791
            PMF_Db::getTablePrefix(),
2792
            $mode,
2793
            (int) $recordId);
2794
2795
        $result = $this->_config->getDb()->query($query);
2796
2797
        if ($this->_config->getDb()->numRows($result) > 0) {
2798
            while (($row = $this->_config->getDb()->fetchObject($result))) {
2799
                $permissions[] = (int) $row->permission;
2800
            }
2801
        }
2802
2803
        return $permissions;
2804
    }
2805
2806
    /**
2807
     * Returns all records of one category.
2808
     *
2809
     * @param int $category
2810
     *
2811
     * @return string
2812
     *
2813
     * @since   2007-04-04
2814
     *
2815
     * @author  Georgi Korchev <[email protected]>
2816
     */
2817
    public function showAllRecordsWoPaging($category)
2818
    {
2819
        global $sids;
2820
2821
        $now = date('YmdHis');
2822
        $query = '
2823
            SELECT
2824
                fd.id AS id,
2825
                fd.lang AS lang,
2826
                fd.thema AS thema,
2827
                fcr.category_id AS category_id,
2828
                fv.visits AS visits
2829
            FROM
2830
                '.PMF_Db::getTablePrefix().'faqdata fd
2831
            LEFT JOIN
2832
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
2833
            ON
2834
                fd.id = fcr.record_id
2835
            AND
2836
                fd.lang = fcr.record_lang
2837
            LEFT JOIN
2838
                '.PMF_Db::getTablePrefix().'faqvisits fv
2839
            ON
2840
                fd.id = fv.id
2841
            AND
2842
                fv.lang = fd.lang
2843
            LEFT JOIN
2844
                '.PMF_Db::getTablePrefix().'faqdata_group fdg
2845
            ON
2846
                fd.id = fdg.record_id
2847
            LEFT JOIN
2848
                '.PMF_Db::getTablePrefix().'faqdata_user fdu
2849
            ON
2850
                fd.id = fdu.record_id
2851
            WHERE
2852
                fd.date_start <= \''.$now.'\'
2853
            AND
2854
                fd.date_end   >= \''.$now.'\'
2855
            AND
2856
                fd.active = \'yes\'
2857
            AND
2858
                fcr.category_id = '.$category.'
2859
            AND
2860
                fd.lang = \''.$this->_config->getLanguage()->getLanguage().'\'
2861
            GROUP BY
2862
                fd.id,fd.lang,fcr.category_id,fv.visits
2863
            ORDER BY
2864
                fd.id';
2865
2866
        $result = $this->_config->getDb()->query($query);
2867
2868
        $output = '<ul class="phpmyfaq_ul">';
2869
2870
        while (($row = $this->_config->getDb()->fetchObject($result))) {
2871
            $title = $row->thema;
2872
            $url = sprintf(
2873
                '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
2874
                PMF_Link::getSystemRelativeUri(),
2875
                $sids,
2876
                $row->category_id,
2877
                $row->id,
2878
                $row->lang
2879
            );
2880
2881
            $oLink = new PMF_Link($url, $this->_config);
2882
            $oLink->itemTitle = $row->thema;
2883
            $oLink->text = $title;
2884
            $oLink->tooltip = $title;
2885
            $listItem = sprintf('<li>%s</li>', $oLink->toHtmlAnchor(), $this->pmf_lang['msgViews']);
2886
            $listItem = '<li>'.$oLink->toHtmlAnchor().'</li>';
2887
2888
            $output .= $listItem;
2889
        }
2890
2891
        $output .= '</ul>';
2892
2893
        return $output;
2894
    }
2895
2896
    /**
2897
     * Prints the open questions as a XHTML table.
2898
     *
2899
     * @return string
2900
     *
2901
     * @since   2002-09-17
2902
     *
2903
     * @author  Thorsten Rinne <[email protected]>
2904
     */
2905
    public function printOpenQuestions()
2906
    {
2907
        global $sids, $category;
2908
2909
        $date = new PMF_Date($this->_config);
2910
        $mail = new PMF_Mail($this->_config);
2911
2912
        $query = sprintf("
2913
            SELECT
2914
                COUNT(id) AS num
2915
            FROM
2916
                %sfaqquestions
2917
            WHERE
2918
                lang = '%s'
2919
            AND
2920
                is_visible != 'Y'",
2921
            PMF_Db::getTablePrefix(),
2922
            $this->_config->getLanguage()->getLanguage()
2923
        );
2924
2925
        $result = $this->_config->getDb()->query($query);
2926
        $row = $this->_config->getDb()->fetchObject($result);
2927
        $numOfInvisibles = $row->num;
2928
2929
        if ($numOfInvisibles > 0) {
2930
            $extraout = sprintf(
2931
                '<tr><td colspan="3"><small>%s %s</small></td></tr>',
2932
                $this->pmf_lang['msgQuestionsWaiting'],
2933
                $numOfInvisibles
2934
            );
2935
        } else {
2936
            $extraout = '';
2937
        }
2938
2939
        $query = sprintf("
2940
            SELECT
2941
                *
2942
            FROM
2943
                %sfaqquestions
2944
            WHERE
2945
                lang = '%s'
2946
            AND
2947
                is_visible = 'Y'
2948
            ORDER BY
2949
                created ASC",
2950
            PMF_Db::getTablePrefix(),
2951
            $this->_config->getLanguage()->getLanguage()
2952
        );
2953
2954
        $result = $this->_config->getDb()->query($query);
2955
        $output = '';
2956
2957
        if ($result && $this->_config->getDb()->numRows($result) > 0) {
2958
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2959
                $output .= '<tr class="openquestions">';
2960
                $output .= sprintf(
2961
                    '<td><small>%s</small><br /><a href="mailto:%s">%s</a></td>',
2962
                    $date->format(PMF_Date::createIsoDate($row->created)),
2963
                    $mail->safeEmail($row->email),
2964
                    $row->username
2965
                );
2966
                $output .= sprintf(
2967
                    '<td><strong>%s:</strong><br />%s</td>',
2968
                    isset($category->categoryName[$row->category_id]['name']) ? $category->categoryName[$row->category_id]['name'] : '',
2969
                    strip_tags($row->question)
2970
                );
2971
                if ($this->_config->get('records.enableCloseQuestion') && $row->answer_id) {
2972
                    $output .= sprintf(
2973
                        '<td><a id="PMF_openQuestionAnswered" href="?%saction=artikel&amp;cat=%d&amp;id=%d">%s</a></td>',
2974
                        $sids,
2975
                        $row->category_id,
2976
                        $row->answer_id,
2977
                        $this->pmf_lang['msg2answerFAQ']
2978
                    );
2979
                } else {
2980
                    $output .= sprintf(
2981
                        '<td><a class="btn btn-primary" href="?%saction=add&amp;question=%d&amp;cat=%d">%s</a></td>',
2982
                        $sids,
2983
                        $row->id,
2984
                        $row->category_id,
2985
                        $this->pmf_lang['msg2answer']
2986
                    );
2987
                }
2988
                $output .= '</tr>';
2989
            }
2990
        } else {
2991
            $output = sprintf(
2992
                '<tr><td colspan="3">%s</td></tr>',
2993
                $this->pmf_lang['msgNoQuestionsAvailable']
2994
            );
2995
        }
2996
2997
        return $output.$extraout;
2998
    }
2999
3000
    /**
3001
     * Set or unset a faq item flag.
3002
     *
3003
     * @param int    $id   Record id
3004
     * @param string $lang language code which is valid with Language::isASupportedLanguage
3005
     * @param bool   $flag weither or not the record is set to sticky
3006
     * @param string $type type of the flag to set, use the column name
3007
     *
3008
     * @return bool
3009
     */
3010
    public function updateRecordFlag($id, $lang, $flag, $type)
3011
    {
3012
        $retval = false;
3013
3014
        switch ($type) {
3015
            case 'sticky':
3016
                $flag = ($flag === 'checked' ? 1 : 0);
3017
                break;
3018
3019
            case 'active':
3020
                $flag = ($flag === 'checked' ? "'yes'" : "'no'");
3021
                break;
3022
3023
            default:
3024
                // This is because we would run into unknown db column
3025
                $flag = null;
3026
                break;
3027
        }
3028
3029
        if (null !== $flag) {
3030
            $update = sprintf("
3031
                UPDATE 
3032
                    %sfaqdata 
3033
                SET 
3034
                    %s = %s 
3035
                WHERE 
3036
                    id = %d 
3037
                AND 
3038
                    lang = '%s'",
3039
                PMF_Db::getTablePrefix(),
3040
                $type,
3041
                $flag,
3042
                $id,
3043
                $lang
3044
            );
3045
3046
            $retval = (bool) $this->_config->getDb()->query($update);
3047
        }
3048
3049
        return $retval;
3050
    }
3051
3052
    /**
3053
     * Returns the sticky records with URL and Title.
3054
     *
3055
     * @return array
3056
     */
3057
    private function getStickyRecordsData()
3058
    {
3059
        global $sids;
3060
3061
        $now = date('YmdHis');
3062
        $query = sprintf("
3063
            SELECT
3064
                fd.id AS id,
3065
                fd.lang AS lang,
3066
                fd.thema AS thema,
3067
                fcr.category_id AS category_id
3068
            FROM
3069
                %sfaqdata fd
3070
            LEFT JOIN
3071
                %sfaqcategoryrelations fcr
3072
            ON
3073
                fd.id = fcr.record_id
3074
            AND
3075
                fd.lang = fcr.record_lang
3076
            LEFT JOIN
3077
                %sfaqdata_group AS fdg
3078
            ON
3079
                fd.id = fdg.record_id
3080
            LEFT JOIN
3081
                %sfaqdata_user AS fdu
3082
            ON
3083
                fd.id = fdu.record_id
3084
            WHERE
3085
                fd.lang = '%s'
3086
            AND 
3087
                fd.date_start <= '%s'
3088
            AND 
3089
                fd.date_end   >= '%s'
3090
            AND 
3091
                fd.active = 'yes'
3092
            AND 
3093
                fd.sticky = 1
3094
            %s",
3095
            PMF_Db::getTablePrefix(),
3096
            PMF_Db::getTablePrefix(),
3097
            PMF_Db::getTablePrefix(),
3098
            PMF_Db::getTablePrefix(),
3099
            $this->_config->getLanguage()->getLanguage(),
3100
            $now,
3101
            $now,
3102
            $this->queryPermission($this->groupSupport)
3103
        );
3104
3105
        $result = $this->_config->getDb()->query($query);
3106
        $sticky = [];
3107
        $data = [];
3108
3109
        $oldId = 0;
3110
        while (($row = $this->_config->getDb()->fetchObject($result))) {
3111
            if ($oldId != $row->id) {
3112
                $data['thema'] = $row->thema;
3113
3114
                $title = $row->thema;
3115
                $url = sprintf(
3116
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
3117
                    PMF_Link::getSystemRelativeUri(),
3118
                    $sids,
3119
                    $row->category_id,
3120
                    $row->id,
3121
                    $row->lang
3122
                );
3123
                $oLink = new PMF_Link($url, $this->_config);
3124
                $oLink->itemTitle = $row->thema;
3125
                $oLink->tooltip = $title;
3126
                $data['url'] = $oLink->toString();
3127
3128
                $sticky[] = $data;
3129
            }
3130
            $oldId = $row->id;
3131
        }
3132
3133
        return $sticky;
3134
    }
3135
3136
    /**
3137
     * Prepares and returns the sticky records for the frontend.
3138
     *
3139
     * @return array
3140
     */
3141
    public function getStickyRecords()
3142
    {
3143
        $result = $this->getStickyRecordsData();
3144
        $output = [];
3145
3146
        if (count($result) > 0) {
3147
            foreach ($result as $row) {
3148
                $output[] = array(
3149
                    'title' => PMF_Utils::makeShorterText($row['thema'], 8),
3150
                    'preview' => $row['thema'],
3151
                    'url' => $row['url'],
3152
                );
3153
            }
3154
        } else {
3155
            $output['error'] = sprintf('<li>%s</li>', $this->pmf_lang['err_noTopTen']);
3156
        }
3157
        if (!isset($output['error'])) {
3158
            $html = '';
3159
            foreach ($output as $entry) {
3160
                $html .= sprintf(
3161
                    '<li><a class="sticky-faqs" data-toggle="tooltip" data-placement="top" title="%s" href="%s">%s</a></li>',
3162
                    $entry['preview'],
3163
                    $entry['url'],
3164
                    $entry['title']
3165
                );
3166
            }
3167
            $output['html'] = $html;
3168
        }
3169
3170
        return $output;
3171
    }
3172
3173
    /**
3174
     * Updates field answer_id in faqquestion.
3175
     *
3176
     * @param int $openQuestionId
3177
     * @param int $faqId
3178
     * @param int $categoryId
3179
     *
3180
     * @return bool
3181
     */
3182 View Code Duplication
    public function updateQuestionAnswer($openQuestionId, $faqId, $categoryId)
3183
    {
3184
        $query = sprintf(
3185
            'UPDATE %sfaqquestions SET answer_id = %d, category_id= %d WHERE id= %d',
3186
            PMF_Db::getTablePrefix(),
3187
            $faqId,
3188
            $categoryId,
3189
            $openQuestionId
3190
        );
3191
3192
        return $this->_config->getDb()->query($query);
3193
    }
3194
3195
    /**
3196
     * Returns a part of a query to check permissions.
3197
     *
3198
     * @param bool $hasGroupSupport
3199
     *
3200
     * @return string
3201
     */
3202
    protected function queryPermission($hasGroupSupport = false)
3203
    {
3204
        if ($hasGroupSupport) {
3205
            if (-1 === $this->user) {
3206
                return sprintf(
3207
                    'AND fdg.group_id IN (%s)',
3208
                    implode(', ', $this->groups),
3209
                    $this->user,
3210
                    implode(', ', $this->groups));
3211 View Code Duplication
            } else {
3212
                return sprintf(
3213
                    'AND ( fdg.group_id IN (%s) OR (fdu.user_id = %d OR fdg.group_id IN (%s)) )',
3214
                    implode(', ', $this->groups),
3215
                    $this->user,
3216
                    implode(', ', $this->groups)
3217
                );
3218
            }
3219
        } else {
3220
            if (-1 !== $this->user) {
3221
                return sprintf(
3222
                    'AND ( fdu.user_id = %d OR fdu.user_id = -1 )',
3223
                    $this->user
3224
                );
3225
            } else {
3226
                return sprintf(
3227
                    'AND fdu.user_id = -1',
3228
                    $this->user
3229
                );
3230
            }
3231
        }
3232
    }
3233
}
3234