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
Pull Request — 2.9 (#1384)
by
unknown
11:04
created

PMF_Faq::printOpenQuestions()   D

Complexity

Conditions 10
Paths 4

Size

Total Lines 100
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 59
nc 4
nop 1
dl 0
loc 100
rs 4.8196
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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-2017 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-2017 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
            $faqHelper = new PMF_Helper_Faq($this->_config);
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
                $faqdata[] = array(
270
                    'record_id' => $row->id,
271
                    'record_lang' => $row->lang,
272
                    'category_id' => $row->category_id,
273
                    'record_title' => $row->thema,
274
                    'record_preview' => $faqHelper->renderAnswerPreview($row->record_content, 25),
275
                    'record_link' => $oLink->toString(),
276
                    'record_updated' => $row->updated,
277
                    'visits' => $visits,
278
                    'record_created' => $row->created,
279
                );
280
            }
281
        } else {
282
            return $faqdata;
283
        }
284
285
        return $faqdata;
286
    }
287
288
    /**
289
     * This function returns all not expired records from one category.
290
     *
291
     * @param int    $categoryId Category ID
292
     * @param string $orderby    Order by
293
     * @param string $sortby     Sorty by
294
     *
295
     * @return string
296
     */
297
    public function showAllRecords($categoryId, $orderby = 'id', $sortby = 'ASC')
298
    {
299
        global $sids;
300
301
        $numPerPage = $this->_config->get('records.numberOfRecordsPerPage');
302
        $page = PMF_Filter::filterInput(INPUT_GET, 'seite', FILTER_VALIDATE_INT, 1);
303
        $output = '';
304
        $title = '';
305
306
        if ($orderby == 'visits') {
307
            $currentTable = 'fv';
308
        } else {
309
            $currentTable = 'fd';
310
        }
311
312
        // If random FAQs are activated, we don't need an order
313
        if (true === $this->_config->get('records.randomSort')) {
314
            $order = '';
315
        } else {
316
            $order = sprintf(
317
                'ORDER BY fd.sticky DESC, %s.%s %s',
318
                $currentTable,
319
                $this->_config->getDb()->escape($orderby),
320
                $this->_config->getDb()->escape($sortby)
321
            );
322
        }
323
324
        $now = date('YmdHis');
325
        $query = sprintf("
326
            SELECT
327
                fd.id AS id,
328
                fd.lang AS lang,
329
                fd.sticky AS sticky,
330
                fd.thema AS thema,
331
                fcr.category_id AS category_id,
332
                fv.visits AS visits
333
            FROM
334
                %sfaqdata AS fd
335
            LEFT JOIN
336
                %sfaqcategoryrelations AS fcr
337
            ON
338
                fd.id = fcr.record_id
339
            AND
340
                fd.lang = fcr.record_lang
341
            LEFT JOIN
342
                %sfaqvisits AS fv
343
            ON
344
                fd.id = fv.id
345
            AND
346
                fv.lang = fd.lang
347
            LEFT JOIN
348
                %sfaqdata_group AS fdg
349
            ON
350
                fd.id = fdg.record_id
351
            LEFT JOIN
352
                %sfaqdata_user AS fdu
353
            ON
354
                fd.id = fdu.record_id
355
            WHERE
356
                fd.date_start <= '%s'
357
            AND
358
                fd.date_end   >= '%s'
359
            AND
360
                fd.active = 'yes'
361
            AND
362
                fcr.category_id = %d
363
            AND
364
                fd.lang = '%s'
365
            %s
366
            %s",
367
            PMF_Db::getTablePrefix(),
368
            PMF_Db::getTablePrefix(),
369
            PMF_Db::getTablePrefix(),
370
            PMF_Db::getTablePrefix(),
371
            PMF_Db::getTablePrefix(),
372
            $now,
373
            $now,
374
            $categoryId,
375
            $this->_config->getLanguage()->getLanguage(),
376
            $this->queryPermission($this->groupSupport),
377
            $order
378
        );
379
380
        $result = $this->_config->getDb()->query($query);
381
        $num = $this->_config->getDb()->numRows($result);
382
        $pages = (int) ceil($num / $numPerPage);
383
384
        if ($page == 1) {
385
            $first = 0;
386
        } else {
387
            $first = $page * $numPerPage - $numPerPage;
388
        }
389
390
        if ($num > 0) {
391 View Code Duplication
            if ($pages > 1) {
392
                $output .= sprintf('<p><strong>%s %s %s</strong></p>',
393
                    $this->pmf_lang['msgPage'].$page,
394
                    $this->pmf_lang['msgVoteFrom'],
395
                    $pages.$this->pmf_lang['msgPages']);
396
            }
397
            $output .= '<ul class="phpmyfaq_ul">';
398
399
            $counter = 0;
400
            $displayedCounter = 0;
401
            $renderedItems = [];
402
            while (($row = $this->_config->getDb()->fetchObject($result)) && $displayedCounter < $numPerPage) {
403
                ++$counter;
404
                if ($counter <= $first) {
405
                    continue;
406
                }
407
                ++$displayedCounter;
408
409
                if (empty($row->visits)) {
410
                    $visits = 0;
411
                } else {
412
                    $visits = $row->visits;
413
                }
414
415
                $title = $row->thema;
416
                $url = sprintf(
417
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
418
                    PMF_Link::getSystemRelativeUri(),
419
                    $sids,
420
                    $row->category_id,
421
                    $row->id,
422
                    $row->lang
423
                );
424
425
                $oLink = new PMF_Link($url, $this->_config);
426
                $oLink->itemTitle = $oLink->text = $oLink->tooltip = $title;
427
428
                // If random FAQs are activated, we don't need sticky FAQs
429
                if (true === $this->_config->get('records.randomSort')) {
430
                    $row->sticky = 0;
431
                }
432
433
                $renderedItems[$row->id] = sprintf(
434
                    '<li%s>%s<span id="viewsPerRecord"><br /><small>(%s)</small></span></li>',
435
                    ($row->sticky == 1) ? ' class="sticky-faqs"' : '',
436
                    $oLink->toHtmlAnchor(),
437
                    $this->plr->GetMsg('plmsgViews', $visits)
438
                );
439
            }
440
441
            // If random FAQs are activated, shuffle the FAQs :-)
442
            if (true === $this->_config->get('records.randomSort')) {
443
                shuffle($renderedItems);
444
            }
445
446
            $output .= implode("\n", $renderedItems);
447
            $output .= '</ul><span class="totalFaqRecords hide">'.$num.'</span>';
448
        } else {
449
            return false;
450
        }
451
452
        if ($pages > 1) {
453
            // Set rewrite URL, if needed
454
            if ($this->_config->get('main.enableRewriteRules')) {
455
                $link = new PMF_Link(PMF_Link::getSystemRelativeUri('index.php'), $this->_config);
456
                $useRewrite = true;
457
                $rewriteUrl = sprintf(
458
                    '%scategory/%d/%%d/%s.html',
459
                    PMF_Link::getSystemRelativeUri('index.php'),
460
                    $categoryId,
461
                    $link->getSEOItemTitle($title)
462
                );
463
            } else {
464
                $useRewrite = false;
465
                $rewriteUrl = '';
466
            }
467
            $baseUrl = sprintf(
468
                '%s?%saction=show&amp;cat=%d&amp;seite=%d',
469
                PMF_Link::getSystemRelativeUri(),
470
                (empty($sids) ? '' : $sids),
471
                $categoryId,
472
                $page
473
            );
474
475
            $options = array(
476
                'baseUrl' => $baseUrl,
477
                'total' => $num,
478
                'perPage' => $this->_config->get('records.numberOfRecordsPerPage'),
479
                'useRewrite' => $useRewrite,
480
                'rewriteUrl' => $rewriteUrl,
481
                'pageParamName' => 'seite',
482
            );
483
484
            $pagination = new PMF_Pagination($this->_config, $options);
485
            $output    .= $pagination->render();
486
        }
487
488
        return $output;
489
    }
490
491
    /**
492
     * This function returns all not expired records from the given record ids.
493
     *
494
     * @param array  $recordIds Array of record ids
495
     * @param string $orderby    Order by
0 ignored issues
show
Documentation introduced by
There is no parameter named $orderby. Did you maybe mean $orderBy?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
496
     * @param string $sortBy     Sort by
497
     *
498
     * @return string
499
     */
500
    public function showAllRecordsByIds(Array $recordIds, $orderBy = 'fd.id', $sortBy = 'ASC')
501
    {
502
        global $sids;
503
504
        $records = implode(', ', $recordIds);
505
        $page = PMF_Filter::filterInput(INPUT_GET, 'seite', FILTER_VALIDATE_INT, 1);
506
        $taggingId = PMF_Filter::filterInput(INPUT_GET, 'tagging_id', FILTER_DEFAULT);
507
        $output = '';
508
509
        $now = date('YmdHis');
510
        $query = sprintf("
511
            SELECT
512
                fd.id AS id,
513
                fd.lang AS lang,
514
                fd.thema AS thema,
515
                fcr.category_id AS category_id,
516
                fv.visits AS visits
517
            FROM
518
                %sfaqdata AS fd
519
            LEFT JOIN
520
                %sfaqcategoryrelations AS fcr
521
            ON
522
                fd.id = fcr.record_id
523
            AND
524
                fd.lang = fcr.record_lang
525
            LEFT JOIN
526
                %sfaqvisits AS fv
527
            ON
528
                fd.id = fv.id
529
            AND
530
                fv.lang = fd.lang
531
            LEFT JOIN
532
                %sfaqdata_group AS fdg
533
            ON
534
                fd.id = fdg.record_id
535
            LEFT JOIN
536
                %sfaqdata_user AS fdu
537
            ON
538
                fd.id = fdu.record_id
539
            WHERE
540
                fd.date_start <= '%s'
541
            AND
542
                fd.date_end   >= '%s'
543
            AND
544
                fd.active = 'yes'
545
            AND
546
                fd.id IN (%s)
547
            AND
548
                fd.lang = '%s'
549
                %s
550
            ORDER BY
551
                %s %s",
552
            PMF_Db::getTablePrefix(),
553
            PMF_Db::getTablePrefix(),
554
            PMF_Db::getTablePrefix(),
555
            PMF_Db::getTablePrefix(),
556
            PMF_Db::getTablePrefix(),
557
            $now,
558
            $now,
559
            $records,
560
            $this->_config->getLanguage()->getLanguage(),
561
            $this->queryPermission($this->groupSupport),
562
            $this->_config->getDb()->escape($orderBy),
563
            $this->_config->getDb()->escape($sortBy));
564
565
        $result = $this->_config->getDb()->query($query);
566
567
        $num = $this->_config->getDb()->numRows($result);
568
        $pages = ceil($num / $this->_config->get('records.numberOfRecordsPerPage'));
569
570
        if ($page == 1) {
571
            $first = 0;
572
        } else {
573
            $first = ($page * $this->_config->get('records.numberOfRecordsPerPage')) - $this->_config->get('records.numberOfRecordsPerPage');
574
        }
575
576
        if ($num > 0) {
577 View Code Duplication
            if ($pages > 1) {
578
                $output .= sprintf('<p><strong>%s %s %s</strong></p>',
579
                    $this->pmf_lang['msgPage'].$page,
580
                    $this->pmf_lang['msgVoteFrom'],
581
                    $pages.$this->pmf_lang['msgPages']);
582
            }
583
            $output .= '<ul class="phpmyfaq_ul">';
584
            $counter = 0;
585
            $displayedCounter = 0;
586
587
            $lastFaqId = 0;
588
            while (($row = $this->_config->getDb()->fetchObject($result)) && $displayedCounter < $this->_config->get('records.numberOfRecordsPerPage')) {
589
                ++$counter;
590
                if ($counter <= $first) {
591
                    continue;
592
                }
593
                ++$displayedCounter;
594
595
                if ($lastFaqId == $row->id) {
596
                    continue; // Don't show multiple FAQs
597
                }
598
599
                if (empty($row->visits)) {
600
                    $visits = 0;
601
                } else {
602
                    $visits = $row->visits;
603
                }
604
605
                $title = $row->thema;
606
                $url = sprintf(
607
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
608
                    PMF_Link::getSystemRelativeUri(),
609
                    $sids,
610
                    $row->category_id,
611
                    $row->id,
612
                    $row->lang
613
                );
614
                $oLink = new PMF_Link($url, $this->_config);
615
                $oLink->itemTitle = $row->thema;
616
                $oLink->text = $title;
617
                $oLink->tooltip = $title;
618
                $listItem = sprintf(
619
                    '<li>%s<br /><small>(%s)</small></li>',
620
                    $oLink->toHtmlAnchor(),
621
                    $this->plr->GetMsg('plmsgViews', $visits)
622
                );
623
624
                $output .= $listItem;
625
626
                $lastFaqId = $row->id;
627
            }
628
            $output .= '</ul><span id="totFaqRecords" style="display: none;">'.$num.'</span>';
629
        } else {
630
            return false;
631
        }
632
633
        if ($num > $this->_config->get('records.numberOfRecordsPerPage')) {
634
            $output .= '<p class="text-center"><strong>';
635
            if (!isset($page)) {
636
                $page = 1;
637
            }
638
            $vor = $page - 1;
639
            $next = $page + 1;
640 View Code Duplication
            if ($vor != 0) {
641
                $url = $sids.'&amp;action=search&amp;tagging_id='.$taggingId.'&amp;seite='.$vor;
642
                $oLink = new PMF_Link(PMF_Link::getSystemRelativeUri().'?'.$url, $this->_config);
643
                $oLink->itemTitle = 'tag';
644
                $oLink->text = $this->pmf_lang['msgPrevious'];
645
                $oLink->tooltip = $this->pmf_lang['msgPrevious'];
646
                $output          .= '[ '.$oLink->toHtmlAnchor().' ]';
647
            }
648
            $output .= ' ';
649 View Code Duplication
            if ($next <= $pages) {
650
                $url = $sids.'&amp;action=search&amp;tagging_id='.$taggingId.'&amp;seite='.$next;
651
                $oLink = new PMF_Link(PMF_Link::getSystemRelativeUri().'?'.$url, $this->_config);
652
                $oLink->itemTitle = 'tag';
653
                $oLink->text = $this->pmf_lang['msgNext'];
654
                $oLink->tooltip = $this->pmf_lang['msgNext'];
655
                $output          .= '[ '.$oLink->toHtmlAnchor().' ]';
656
            }
657
            $output .= '</strong></p>';
658
        }
659
660
        return $output;
661
    }
662
663
    /**
664
     * Returns an array with all data from a FAQ record.
665
     *
666
     * @param int  $faqId         FAQ ID
667
     * @param int  $faqRevisionId Revision ID
668
     * @param bool $isAdmin       Must be true if it is called by an admin/author context
669
     */
670
    public function getRecord($faqId, $faqRevisionId = null, $isAdmin = false)
671
    {
672
        global $PMF_LANG;
673
674
        $currentLanguage = $this->_config->getLanguage()->getLanguage();
675
        $defaultLanguage = $this->_config->getDefaultLanguage();
676
677
        $result = $this->getRecordResult($faqId, $currentLanguage, $faqRevisionId, $isAdmin);
678
679
        if (0 === $this->_config->getDb()->numRows($result)) {
680
            $result = $this->getRecordResult($faqId, $defaultLanguage, $faqRevisionId, $isAdmin);
681
        }
682
683
        if ($row = $this->_config->getDb()->fetchObject($result)) {
684
            $question = nl2br($row->thema);
685
            $answer = $row->content;
686
            $active = ('yes' === $row->active);
687
            $expired = (date('YmdHis') > $row->date_end);
688
689
            if (!$isAdmin) {
690
                if (!$active) {
691
                    $answer = $this->pmf_lang['err_inactiveArticle'];
692
                }
693
                if ($expired) {
694
                    $answer = $this->pmf_lang['err_expiredArticle'];
695
                }
696
            }
697
698
            $this->faqRecord = [
699
                'id' => $row->id,
700
                'lang' => $row->lang,
701
                'solution_id' => $row->solution_id,
702
                'revision_id' => $row->revision_id,
703
                'active' => $row->active,
704
                'sticky' => $row->sticky,
705
                'keywords' => $row->keywords,
706
                'title' => $question,
707
                'content' => $answer,
708
                'author' => $row->author,
709
                'email' => $row->email,
710
                'comment' => $row->comment,
711
                'date' => PMF_Date::createIsoDate($row->updated),
712
                'dateStart' => $row->date_start,
713
                'dateEnd' => $row->date_end,
714
                'linkState' => $row->links_state,
715
                'linkCheckDate' => $row->links_check_date,
716
                'notes' => $row->notes,
717
                'created' => $row->created,
718
            ];
719
        } else {
720
            $this->faqRecord = [
721
                'id' => $faqId,
722
                'lang' => $currentLanguage,
723
                'solution_id' => 42,
724
                'revision_id' => $faqRevisionId,
725
                'active' => 'no',
726
                'sticky' => 0,
727
                'keywords' => '',
728
                'title' => '',
729
                'content' => $PMF_LANG['msgAccessDenied'],
730
                'author' => '',
731
                'email' => '',
732
                'comment' => '',
733
                'date' => PMF_Date::createIsoDate(date('YmdHis')),
734
                'dateStart' => '',
735
                'dateEnd' => '',
736
                'linkState' => '',
737
                'linkCheckDate' => '',
738
                'notes' => '',
739
                'created' => date('c'),
740
            ];
741
        }
742
    }
743
744
    /**
745
     * Executes a query to retrieve a single FAQ.
746
     *
747
     * @param int    $faqId
748
     * @param string $faqLanguage
749
     * @param int    $faqRevisionId
750
     * @param bool   $isAdmin
751
     *
752
     * @return mixed
753
     */
754
    public function getRecordResult($faqId, $faqLanguage, $faqRevisionId = null, $isAdmin = false)
755
    {
756
        $query = sprintf(
757
            "SELECT
758
                 id, lang, solution_id, revision_id, active, sticky, keywords,
759
                 thema, content, author, email, comment, updated, links_state,
760
                 links_check_date, date_start, date_end, created, notes
761
            FROM
762
                %s%s fd
763
            LEFT JOIN
764
                %sfaqdata_group fdg
765
            ON
766
                fd.id = fdg.record_id
767
            LEFT JOIN
768
                %sfaqdata_user fdu
769
            ON
770
                fd.id = fdu.record_id
771
            WHERE
772
                fd.id = %d
773
            %s
774
            AND
775
                fd.lang = '%s'
776
                %s",
777
            PMF_Db::getTablePrefix(),
778
            isset($faqRevisionId) ? 'faqdata_revisions' : 'faqdata',
779
            PMF_Db::getTablePrefix(),
780
            PMF_Db::getTablePrefix(),
781
            $faqId,
782
            isset($faqRevisionId) ? 'AND revision_id = '.$faqRevisionId : '',
783
            $faqLanguage,
784
            ($isAdmin) ? 'AND 1=1' : $this->queryPermission($this->groupSupport)
785
        );
786
787
        return $this->_config->getDb()->query($query);
788
    }
789
790
    /**
791
     * Return records from given IDs
792
     *
793
     * @param array $faqIds
794
     *
795
     * @return array
796
     */
797
    public function getRecordsByIds(Array $faqIds)
798
    {
799
        $faqRecords = [];
800
801
        $query = sprintf(
802
            "SELECT
803
                 fd.id AS id,
804
                 fd.lang AS lang,
805
                 fd.thema AS question,
806
                 fd.content AS answer,
807
                 fd.updated AS updated,
808
                 fd.created AS created,
809
                 fcr.category_id AS category_id,
810
                 fv.visits AS visits
811
            FROM
812
                %sfaqdata fd
813
            LEFT JOIN
814
                %sfaqcategoryrelations fcr
815
            ON
816
                fd.id = fcr.record_id
817
            AND
818
                fd.lang = fcr.record_lang
819
            LEFT JOIN
820
                %sfaqdata_group fdg
821
            ON
822
                fd.id = fdg.record_id
823
            LEFT JOIN
824
                %sfaqvisits AS fv
825
            ON
826
                fd.id = fv.id
827
            AND
828
                fv.lang = fd.lang
829
            LEFT JOIN
830
                %sfaqdata_user fdu
831
            ON
832
                fd.id = fdu.record_id
833
            WHERE
834
                fd.id IN (%s)
835
            AND
836
                fd.lang = '%s'
837
                %s",
838
            PMF_Db::getTablePrefix(),
839
            PMF_Db::getTablePrefix(),
840
            PMF_Db::getTablePrefix(),
841
            PMF_Db::getTablePrefix(),
842
            PMF_Db::getTablePrefix(),
843
            implode(',', $faqIds),
844
            $this->_config->getLanguage()->getLanguage(),
845
            $this->queryPermission($this->groupSupport)
846
        );
847
848
        $result = $this->_config->getDb()->query($query);
849
850
        $faqHelper = new PMF_Helper_Faq($this->_config);
851
        while ($row = $this->_config->getDb()->fetchObject($result)) {
852
            if (empty($row->visits)) {
853
                $visits = 0;
854
            } else {
855
                $visits = $row->visits;
856
            }
857
858
            $url = sprintf(
859
                '%sindex.php?action=artikel&cat=%d&id=%d&artlang=%s',
860
                $this->_config->getDefaultUrl(),
861
                $row->category_id,
862
                $row->id,
863
                $row->lang
864
            );
865
            $oLink = new PMF_Link($url, $this->_config);
866
            $oLink->itemTitle = $oLink->text = $oLink->tooltip = $row->question;
867
868
            $faqRecords[] = [
869
                'record_id' => (int)$row->id,
870
                'record_lang' => $row->lang,
871
                'category_id' => (int)$row->category_id,
872
                'record_title' => $row->question,
873
                'record_preview' => $faqHelper->renderAnswerPreview($row->answer, 25),
874
                'record_link' => $oLink->toString(),
875
                'record_updated' => PMF_Date::createIsoDate($row->updated).':00',
876
                'visits' => (int)$visits,
877
                'record_created' => $row->created
878
            ];
879
        }
880
881
        return $faqRecords;
882
    }
883
884
    /**
885
     * Adds a new record.
886
     *
887
     * @param array $data      Array of FAQ data
888
     * @param bool  $newRecord Do not create a new ID if false
889
     *
890
     * @return int
891
     */
892
    public function addRecord(Array $data, $newRecord = true)
893
    {
894
        if ($newRecord) {
895
            $recordId = $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqdata', 'id');
896
        } else {
897
            $recordId = $data['id'];
898
        }
899
900
        // Add new entry
901
        $query = sprintf("
902
            INSERT INTO
903
                %sfaqdata
904
            VALUES
905
                (%d, '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s')",
906
            PMF_Db::getTablePrefix(),
907
            $recordId,
908
            $data['lang'],
909
            $this->getSolutionId(),
910
            0,
911
            $data['active'],
912
            $data['sticky'],
913
            $this->_config->getDb()->escape($data['keywords']),
914
            $this->_config->getDb()->escape($data['thema']),
915
            $this->_config->getDb()->escape($data['content']),
916
            $this->_config->getDb()->escape($data['author']),
917
            $data['email'],
918
            $data['comment'],
919
            $data['date'],
920
            $data['linkState'],
921
            $data['linkDateCheck'],
922
            $data['dateStart'],
923
            $data['dateEnd'],
924
            date('Y-m-d H:i:s'),
925
            $data['notes']
926
        );
927
928
        $this->_config->getDb()->query($query);
929
930
        return $recordId;
931
    }
932
933
    /**
934
     * Updates a record.
935
     *
936
     * @param array $data Array of FAQ data
937
     *
938
     * @return bool
939
     */
940
    public function updateRecord(Array $data)
941
    {
942
        // Update entry
943
        $query = sprintf("
944
            UPDATE
945
                %sfaqdata
946
            SET
947
                revision_id = %d,
948
                active = '%s',
949
                sticky = %d,
950
                keywords = '%s',
951
                thema = '%s',
952
                content = '%s',
953
                author = '%s',
954
                email = '%s',
955
                comment = '%s',
956
                updated = '%s',
957
                links_state = '%s',
958
                links_check_date = %d,
959
                date_start = '%s',
960
                date_end = '%s',
961
                notes = '%s'
962
            WHERE
963
                id = %d
964
            AND
965
                lang = '%s'",
966
            PMF_Db::getTablePrefix(),
967
            $data['revision_id'],
968
            $data['active'],
969
            $data['sticky'],
970
            $this->_config->getDb()->escape($data['keywords']),
971
            $this->_config->getDb()->escape($data['thema']),
972
            $this->_config->getDb()->escape($data['content']),
973
            $this->_config->getDb()->escape($data['author']),
974
            $data['email'],
975
            $data['comment'],
976
            $data['date'],
977
            $data['linkState'],
978
            $data['linkDateCheck'],
979
            $data['dateStart'],
980
            $data['dateEnd'],
981
            $data['notes'],
982
            $data['id'],
983
            $data['lang']
984
        );
985
986
        $this->_config->getDb()->query($query);
987
988
        return true;
989
    }
990
991
    /**
992
     * Deletes a record and all the dependencies.
993
     *
994
     * @param int    $recordId   Record id
995
     * @param string $recordLang Record language
996
     *
997
     * @return bool
998
     */
999
    public function deleteRecord($recordId, $recordLang)
1000
    {
1001
        $solutionId = $this->getSolutionIdFromId($recordId, $recordLang);
1002
1003
        $queries = array(
1004
            sprintf(
1005
                "DELETE FROM %sfaqchanges WHERE beitrag = %d AND lang = '%s'",
1006
                PMF_Db::getTablePrefix(),
1007
                $recordId,
1008
                $recordLang
1009
            ),
1010
            sprintf(
1011
                "DELETE FROM %sfaqcategoryrelations WHERE record_id = %d AND record_lang = '%s'",
1012
                PMF_Db::getTablePrefix(),
1013
                $recordId,
1014
                $recordLang
1015
            ),
1016
            sprintf(
1017
                "DELETE FROM %sfaqdata WHERE id = %d AND lang = '%s'",
1018
                PMF_Db::getTablePrefix(),
1019
                $recordId,
1020
                $recordLang
1021
            ),
1022
            sprintf(
1023
                "DELETE FROM %sfaqdata_revisions WHERE id = %d AND lang = '%s'",
1024
                PMF_Db::getTablePrefix(),
1025
                $recordId,
1026
                $recordLang
1027
            ),
1028
            sprintf(
1029
                "DELETE FROM %sfaqvisits WHERE id = %d AND lang = '%s'",
1030
                PMF_Db::getTablePrefix(),
1031
                $recordId,
1032
                $recordLang
1033
            ),
1034
            sprintf(
1035
                'DELETE FROM %sfaqdata_user WHERE record_id = %d',
1036
                PMF_Db::getTablePrefix(),
1037
                $recordId,
1038
                $recordLang
1039
            ),
1040
            sprintf(
1041
                'DELETE FROM %sfaqdata_group WHERE record_id = %d',
1042
                PMF_Db::getTablePrefix(),
1043
                $recordId,
1044
                $recordLang
1045
            ),
1046
            sprintf(
1047
                'DELETE FROM %sfaqdata_tags WHERE record_id = %d',
1048
                PMF_Db::getTablePrefix(),
1049
                $recordId
1050
            ),
1051
            sprintf(
1052
                'DELETE FROM %sfaqdata_tags WHERE %sfaqdata_tags.record_id NOT IN (SELECT %sfaqdata.id FROM %sfaqdata)',
1053
                PMF_Db::getTablePrefix(),
1054
                PMF_Db::getTablePrefix(),
1055
                PMF_Db::getTablePrefix(),
1056
                PMF_Db::getTablePrefix()
1057
            ),
1058
            sprintf(
1059
                'DELETE FROM %sfaqcomments WHERE id = %d',
1060
                PMF_Db::getTablePrefix(),
1061
                $recordId
1062
            ),
1063
            sprintf(
1064
                'DELETE FROM %sfaqvoting WHERE artikel = %d',
1065
                PMF_Db::getTablePrefix(),
1066
                $recordId
1067
            ),
1068
        );
1069
1070
        foreach ($queries as $query) {
1071
            $this->_config->getDb()->query($query);
1072
        }
1073
1074
        // Delete possible attachments
1075
        $attId = PMF_Attachment_Factory::fetchByRecordId($this->_config, $recordId);
1076
        $attachment = PMF_Attachment_Factory::create($attId);
1077
        $attachment->delete();
1078
1079
        // Delete possible Elasticsearch documents
1080
        if ($this->_config->get('search.enableElasticsearch')) {
1081
            $esInstance = new PMF_Instance_Elasticsearch($this->_config);
1082
            $esInstance->delete($solutionId);
1083
        }
1084
1085
        return true;
1086
    }
1087
1088
    /**
1089
     * Checks if a record is already translated.
1090
     *
1091
     * @param int    $record_id   Record id
1092
     * @param string $record_lang Record language
1093
     *
1094
     * @return bool
1095
     */
1096
    public function isAlreadyTranslated($record_id, $record_lang)
1097
    {
1098
        $query = sprintf("
1099
            SELECT
1100
                id, lang
1101
            FROM
1102
                %sfaqdata
1103
            WHERE
1104
                id = %d
1105
            AND
1106
                lang = '%s'",
1107
            PMF_Db::getTablePrefix(),
1108
            $record_id,
1109
            $record_lang);
1110
1111
        $result = $this->_config->getDb()->query($query);
1112
1113
        if ($this->_config->getDb()->numRows($result)) {
1114
            return true;
1115
        }
1116
1117
        return false;
1118
    }
1119
1120
    /**
1121
     * Checks, if comments are disabled for the FAQ record.
1122
     *
1123
     * @param int    $record_id   Id of FAQ or news entry
1124
     * @param string $record_lang Language
1125
     * @param string $record_type Type of comment: faq or news
1126
     *
1127
     * @return bool true, if comments are disabled
1128
     */
1129
    public function commentDisabled($record_id, $record_lang, $record_type = 'faq')
1130
    {
1131
        if ('news' == $record_type) {
1132
            $table = 'faqnews';
1133
        } else {
1134
            $table = 'faqdata';
1135
        }
1136
1137
        $query = sprintf("
1138
            SELECT
1139
                comment
1140
            FROM
1141
                %s%s
1142
            WHERE
1143
                id = %d
1144
            AND
1145
                lang = '%s'",
1146
            PMF_Db::getTablePrefix(),
1147
            $table,
1148
            $record_id,
1149
            $record_lang
1150
        );
1151
1152
        $result = $this->_config->getDb()->query($query);
1153
1154
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1155
            return ($row->comment === 'y') ? false : true;
1156
        } else {
1157
            return true;
1158
        }
1159
    }
1160
1161
    /**
1162
     * Adds new category relations to a record.
1163
     *
1164
     * @param array  $categories Array of categories
1165
     * @param int    $record_id  Record id
1166
     * @param string $language   Language
1167
     *
1168
     * @return int
1169
     */
1170
    public function addCategoryRelations(Array $categories, $record_id, $language)
1171
    {
1172
        if (!is_array($categories)) {
1173
            return false;
1174
        }
1175
1176
        foreach ($categories as $_category) {
1177
            $this->_config->getDb()->query(sprintf(
1178
                "INSERT INTO
1179
                    %sfaqcategoryrelations
1180
                VALUES
1181
                    (%d, '%s', %d, '%s')",
1182
                PMF_Db::getTablePrefix(),
1183
                $_category,
1184
                $language,
1185
                $record_id,
1186
                $language));
1187
        }
1188
1189
        return true;
1190
    }
1191
1192
    /**
1193
     * Adds new category relation to a record.
1194
     *
1195
     * @param mixed  $category  Category or array of categories
1196
     * @param int    $record_id Record id
1197
     * @param string $language  Language
1198
     *
1199
     * @return bool
1200
     */
1201
    public function addCategoryRelation($category, $record_id, $language)
1202
    {
1203
        // Just a fallback when (wrong case) $category is an array
1204
        if (is_array($category)) {
1205
            $this->addCategoryRelations($category, $record_id, $language);
1206
        }
1207
        $categories[] = $category;
1208
1209
        return $this->addCategoryRelations($categories, $record_id, $language);
1210
    }
1211
1212
    /**
1213
     * Deletes category relations to a record.
1214
     *
1215
     * @param int    $record_id   Record id
1216
     * @param string $record_lang Language
1217
     *
1218
     * @return bool
1219
     */
1220 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...
1221
    {
1222
        $query = sprintf("
1223
            DELETE FROM
1224
                %sfaqcategoryrelations
1225
            WHERE
1226
                record_id = %d
1227
            AND
1228
                record_lang = '%s'",
1229
            PMF_Db::getTablePrefix(),
1230
            $record_id,
1231
            $record_lang);
1232
        $this->_config->getDb()->query($query);
1233
1234
        return true;
1235
    }
1236
1237
    /**
1238
     * Returns an array with all data from a FAQ record.
1239
     *
1240
     * @param int $solutionId Solution ID
1241
     */
1242
    public function getRecordBySolutionId($solutionId)
1243
    {
1244
        $query = sprintf(
1245
            'SELECT
1246
                *
1247
            FROM
1248
                %sfaqdata fd
1249
            LEFT JOIN
1250
                %sfaqdata_group fdg
1251
            ON
1252
                fd.id = fdg.record_id
1253
            LEFT JOIN
1254
                %sfaqdata_user fdu
1255
            ON
1256
                fd.id = fdu.record_id
1257
            WHERE
1258
                fd.solution_id = %d
1259
                %s',
1260
            PMF_Db::getTablePrefix(),
1261
            PMF_Db::getTablePrefix(),
1262
            PMF_Db::getTablePrefix(),
1263
            $solutionId,
1264
            $this->queryPermission($this->groupSupport)
1265
        );
1266
1267
        $result = $this->_config->getDb()->query($query);
1268
1269
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1270
            $question = nl2br($row->thema);
1271
            $content = $row->content;
1272
            $active = ('yes' == $row->active);
1273
            $expired = (date('YmdHis') > $row->date_end);
1274
1275
            if (!$active) {
1276
                $content = $this->pmf_lang['err_inactiveArticle'];
1277
            }
1278
            if ($expired) {
1279
                $content = $this->pmf_lang['err_expiredArticle'];
1280
            }
1281
1282
            $this->faqRecord = array(
1283
                'id' => $row->id,
1284
                'lang' => $row->lang,
1285
                'solution_id' => $row->solution_id,
1286
                'revision_id' => $row->revision_id,
1287
                'active' => $row->active,
1288
                'sticky' => $row->sticky,
1289
                'keywords' => $row->keywords,
1290
                'title' => $question,
1291
                'content' => $content,
1292
                'author' => $row->author,
1293
                'email' => $row->email,
1294
                'comment' => $row->comment,
1295
                'date' => PMF_Date::createIsoDate($row->updated),
1296
                'dateStart' => $row->date_start,
1297
                'dateEnd' => $row->date_end,
1298
                'linkState' => $row->links_state,
1299
                'linkCheckDate' => $row->links_check_date,
1300
                'notes' => $row->notes
1301
            );
1302
        }
1303
    }
1304
1305
    /**
1306
     * Gets the record ID from a given solution ID.
1307
     *
1308
     * @param int $solutionId Solution ID
1309
     *
1310
     * @return array
1311
     */
1312
    public function getIdFromSolutionId($solutionId)
1313
    {
1314
        $query = sprintf('
1315
            SELECT
1316
                fd.id,
1317
                fd.lang,
1318
                fd.thema AS question,
1319
                fd.content, 
1320
                fcr.category_id AS category_id
1321
            FROM
1322
                %sfaqdata fd
1323
            LEFT JOIN
1324
                %sfaqcategoryrelations fcr
1325
            ON
1326
                fd.id = fcr.record_id
1327
            AND
1328
                fd.lang = fcr.record_lang
1329
            WHERE
1330
                fd.solution_id = %d',
1331
            PMF_Db::getTablePrefix(),
1332
            PMF_Db::getTablePrefix(),
1333
            $solutionId
1334
        );
1335
1336
        $result = $this->_config->getDb()->query($query);
1337
1338
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1339
            return [
1340
                'id' => $row->id,
1341
                'lang' => $row->lang,
1342
                'question' => $row->question,
1343
                'content' => $row->content,
1344
                'category_id' => $row->category_id
1345
            ];
1346
        }
1347
1348
        return [];
1349
    }
1350
1351
    /**
1352
     * Returns the solution ID from a given ID and language
1353
     *
1354
     * @param integer $faqId
1355
     * @param string $faqLang
1356
     *
1357
     * @return int
1358
     */
1359
    public function getSolutionIdFromId($faqId, $faqLang)
1360
    {
1361
        $query = sprintf("
1362
            SELECT
1363
                solution_id
1364
            FROM
1365
                %sfaqdata
1366
            WHERE
1367
                id = %d
1368
                AND
1369
                lang = '%s'",
1370
            PMF_Db::getTablePrefix(),
1371
            (int) $faqId,
1372
            $this->_config->getDb()->escape($faqLang)
1373
        );
1374
1375
        $result = $this->_config->getDb()->query($query);
1376
1377
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1378
            return $row->solution_id;
1379
        }
1380
1381
        return $this->getSolutionId();
1382
    }
1383
1384
    /**
1385
     * Gets the latest solution id for a FAQ record.
1386
     *
1387
     * @return int
1388
     */
1389
    public function getSolutionId()
1390
    {
1391
        $latestId = 0;
1392
1393
        $query = sprintf('
1394
            SELECT
1395
                MAX(solution_id) AS solution_id
1396
            FROM
1397
                %sfaqdata',
1398
            PMF_Db::getTablePrefix()
1399
        );
1400
1401
        $result = $this->_config->getDb()->query($query);
1402
1403
        if ($result && $row = $this->_config->getDb()->fetchObject($result)) {
1404
            $latestId = $row->solution_id;
1405
        }
1406
1407
        if ($latestId < PMF_SOLUTION_ID_START_VALUE) {
1408
            $nextSolutionId = PMF_SOLUTION_ID_START_VALUE;
1409
        } else {
1410
            $nextSolutionId = $latestId + PMF_SOLUTION_ID_INCREMENT_VALUE;
1411
        }
1412
1413
        return $nextSolutionId;
1414
    }
1415
1416
    /**
1417
     * Returns an array with all data from all FAQ records.
1418
     *
1419
     * @param int    $sortType  Sorting type
1420
     * @param array  $condition Condition
1421
     * @param string $sortOrder Sorting order
1422
     */
1423
    public function getAllRecords($sortType = FAQ_SORTING_TYPE_CATID_FAQID, Array $condition = null, $sortOrder = 'ASC')
1424
    {
1425
        $where = '';
1426
        if (!is_null($condition)) {
1427
            $num = count($condition);
1428
            $where = 'WHERE ';
1429
            foreach ($condition as $field => $data) {
1430
                --$num;
1431
                $where .= $field;
1432
                if (is_array($data)) {
1433
                    $where .= ' IN (';
1434
                    $separator = '';
1435
                    foreach ($data as $value) {
1436
                        $where .= $separator."'".$this->_config->getDb()->escape($value)."'";
1437
                        $separator = ', ';
1438
                    }
1439
                    $where .= ')';
1440
                } else {
1441
                    $where .= " = '".$this->_config->getDb()->escape($data)."'";
1442
                }
1443
                if ($num > 0) {
1444
                    $where .= ' AND ';
1445
                }
1446
            }
1447
        }
1448
1449
        switch ($sortType) {
1450
1451
            case FAQ_SORTING_TYPE_CATID_FAQID:
1452
                $orderBy = sprintf('
1453
            ORDER BY
1454
                fcr.category_id,
1455
                fd.id %s',
1456
                    $sortOrder);
1457
                break;
1458
1459
            case FAQ_SORTING_TYPE_FAQID:
1460
                $orderBy = sprintf('
1461
            ORDER BY
1462
                fd.id %s',
1463
                    $sortOrder);
1464
                break;
1465
1466
            case FAQ_SORTING_TYPE_FAQTITLE_FAQID:
1467
                $orderBy = sprintf('
1468
            ORDER BY
1469
                fcr.category_id,
1470
                fd.thema %s',
1471
                    $sortOrder);
1472
                break;
1473
1474
            case FAQ_SORTING_TYPE_DATE_FAQID:
1475
                $orderBy = sprintf('
1476
            ORDER BY
1477
                fcr.category_id,
1478
                fd.updated %s',
1479
                    $sortOrder);
1480
                break;
1481
1482
            default:
1483
                $orderBy = '';
1484
                break;
1485
        }
1486
1487
        $query = sprintf('
1488
            SELECT
1489
                fd.id AS id,
1490
                fd.lang AS lang,
1491
                fcr.category_id AS category_id,
1492
                fd.solution_id AS solution_id,
1493
                fd.revision_id AS revision_id,
1494
                fd.active AS active,
1495
                fd.sticky AS sticky,
1496
                fd.keywords AS keywords,
1497
                fd.thema AS thema,
1498
                fd.content AS content,
1499
                fd.author AS author,
1500
                fd.email AS email,
1501
                fd.comment AS comment,
1502
                fd.updated AS updated,
1503
                fd.links_state AS links_state,
1504
                fd.links_check_date AS links_check_date,
1505
                fd.date_start AS date_start,
1506
                fd.date_end AS date_end,
1507
                fd.sticky AS sticky,
1508
                fd.created AS created,
1509
                fd.notes AS notes
1510
            FROM
1511
                %sfaqdata fd
1512
            LEFT JOIN
1513
                %sfaqcategoryrelations fcr
1514
            ON
1515
                fd.id = fcr.record_id
1516
            AND
1517
                fd.lang = fcr.record_lang
1518
            LEFT JOIN
1519
                %sfaqdata_group AS fdg
1520
            ON
1521
                fd.id = fdg.record_id
1522
            LEFT JOIN
1523
                %sfaqdata_user AS fdu
1524
            ON
1525
                fd.id = fdu.record_id
1526
            %s
1527
            %s
1528
            %s',
1529
            PMF_Db::getTablePrefix(),
1530
            PMF_Db::getTablePrefix(),
1531
            PMF_Db::getTablePrefix(),
1532
            PMF_Db::getTablePrefix(),
1533
            $where,
1534
            $this->queryPermission($this->groupSupport),
1535
            $orderBy
1536
        );
1537
1538
        $result = $this->_config->getDb()->query($query);
1539
1540
        while ($row = $this->_config->getDb()->fetchObject($result)) {
1541
            $content = $row->content;
1542
            $active = ('yes' == $row->active);
1543
            $expired = (date('YmdHis') > $row->date_end);
1544
1545
            if (!$active) {
1546
                $content = $this->pmf_lang['err_inactiveArticle'];
1547
            }
1548
            if ($expired) {
1549
                $content = $this->pmf_lang['err_expiredArticle'];
1550
            }
1551
1552
            $this->faqRecords[] = [
1553
                'id' => $row->id,
1554
                'category_id' => $row->category_id,
1555
                'lang' => $row->lang,
1556
                'solution_id' => $row->solution_id,
1557
                'revision_id' => $row->revision_id,
1558
                'active' => $row->active,
1559
                'sticky' => $row->sticky,
1560
                'keywords' => $row->keywords,
1561
                'title' => $row->thema,
1562
                'content' => $content,
1563
                'author' => $row->author,
1564
                'email' => $row->email,
1565
                'comment' => $row->comment,
1566
                'updated' => PMF_Date::createIsoDate($row->updated, 'Y-m-d H:i:s'),
1567
                'dateStart' => $row->date_start,
1568
                'dateEnd' => $row->date_end,
1569
                'created' => $row->created,
1570
                'notes' => $row->notes
1571
            ];
1572
        }
1573
    }
1574
1575
    /**
1576
     * Returns the FAQ record title from the ID and language.
1577
     *
1578
     * @param int $id Record id
1579
     *
1580
     * @return string
1581
     */
1582
    public function getRecordTitle($id)
1583
    {
1584
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $id)) {
1585
            return $this->faqRecord['title'];
1586
        }
1587
1588
        $question = '';
1589
1590
        $query = sprintf(
1591
            "SELECT
1592
                thema AS question
1593
            FROM
1594
                %sfaqdata
1595
            WHERE
1596
                id = %d AND lang = '%s'",
1597
            PMF_Db::getTablePrefix(),
1598
            $id,
1599
            $this->_config->getLanguage()->getLanguage()
1600
            );
1601
        $result = $this->_config->getDb()->query($query);
1602
1603
        if ($this->_config->getDb()->numRows($result) > 0) {
1604
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1605
                $question = PMF_String::htmlspecialchars($row->question);
1606
            }
1607
        } else {
1608
            $question = $this->pmf_lang['no_cats'];
1609
        }
1610
1611
        return $question;
1612
    }
1613
1614
    /**
1615
     * Gets all revisions from a given record ID.
1616
     *
1617
     * @param int    $recordId   Record id
1618
     * @param string $recordLang Record language
1619
     *
1620
     * @return array
1621
     */
1622
    public function getRevisionIds($recordId, $recordLang)
1623
    {
1624
        $revisionData = [];
1625
1626
        $query = sprintf("
1627
            SELECT
1628
                revision_id, updated, author
1629
            FROM
1630
                %sfaqdata_revisions
1631
            WHERE
1632
                id = %d
1633
            AND
1634
                lang = '%s'
1635
            ORDER BY
1636
                revision_id",
1637
            PMF_Db::getTablePrefix(),
1638
            $recordId,
1639
            $recordLang
1640
        );
1641
1642
        $result = $this->_config->getDb()->query($query);
1643
1644
        if ($this->_config->getDb()->numRows($result) > 0) {
1645
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1646
                $revisionData[] = [
1647
                    'revision_id' => $row->revision_id,
1648
                    'updated' => $row->updated,
1649
                    'author' => $row->author,
1650
                ];
1651
            }
1652
        }
1653
1654
        return $revisionData;
1655
    }
1656
1657
    /**
1658
     * Adds a new revision from a given record ID.
1659
     *
1660
     * @param int    $record_id   Record id
1661
     * @param string $record_lang Record language
1662
     *
1663
     * @return array
1664
     */
1665 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...
1666
    {
1667
        $query = sprintf("
1668
            INSERT INTO
1669
                %sfaqdata_revisions
1670
            SELECT * FROM
1671
                %sfaqdata
1672
            WHERE
1673
                id = %d
1674
            AND
1675
                lang = '%s'",
1676
            PMF_Db::getTablePrefix(),
1677
            PMF_Db::getTablePrefix(),
1678
            $record_id,
1679
            $record_lang);
1680
        $this->_config->getDb()->query($query);
1681
1682
        return true;
1683
    }
1684
1685
    /**
1686
     * Returns the keywords of a FAQ record from the ID and language.
1687
     *
1688
     * @param int $id record id
1689
     *
1690
     * @return string
1691
     */
1692
    public function getRecordKeywords($id)
1693
    {
1694
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $id)) {
1695
            return $this->faqRecord['keywords'];
1696
        }
1697
1698
        $query = sprintf(
1699
            "SELECT
1700
                keywords
1701
            FROM
1702
                %sfaqdata
1703
            WHERE id = %d AND lang = '%s'",
1704
            PMF_Db::getTablePrefix(),
1705
            $id,
1706
            $this->_config->getLanguage()->getLanguage());
1707
1708
        $result = $this->_config->getDb()->query($query);
1709
1710
        if ($this->_config->getDb()->numRows($result) > 0) {
1711
            $row = $this->_config->getDb()->fetchObject($result);
1712
1713
            return PMF_String::htmlspecialchars($row->keywords, ENT_QUOTES, 'utf-8');
1714
        } else {
1715
            return '';
1716
        }
1717
    }
1718
1719
    /**
1720
     * Returns a answer preview of the FAQ record.
1721
     *
1722
     * @param int $recordId  FAQ record ID
1723
     * @param int $wordCount Number of words, default: 12
1724
     *
1725
     * @return string
1726
     */
1727
    public function getRecordPreview($recordId, $wordCount = 12)
1728
    {
1729
        if (isset($this->faqRecord['id']) && ((int)$this->faqRecord['id'] === (int)$recordId)) {
1730
            $answerPreview = $this->faqRecord['content'];
1731
1732
            return PMF_Utils::makeShorterText($answerPreview, $wordCount);
1733
        }
1734
1735
        $query = sprintf("
1736
            SELECT
1737
                content as answer
1738
            FROM
1739
                %sfaqdata
1740
            WHERE 
1741
                id = %d 
1742
            AND 
1743
                lang = '%s'",
1744
            PMF_Db::getTablePrefix(),
1745
            $recordId,
1746
            $this->_config->getLanguage()->getLanguage()
1747
        );
1748
1749
        $result = $this->_config->getDb()->query($query);
1750
1751
        if ($this->_config->getDb()->numRows($result) > 0) {
1752
            $row = $this->_config->getDb()->fetchObject($result);
1753
            $answerPreview = strip_tags($row->answer);
1754
        } else {
1755
            $answerPreview = $this->_config->get('main.metaDescription');
1756
        }
1757
1758
        return PMF_Utils::makeShorterText($answerPreview, $wordCount);
1759
    }
1760
1761
    /**
1762
     * Returns the number of activated and not expired records, optionally
1763
     * not limited to the current language.
1764
     *
1765
     * @param string $language Language
1766
     *
1767
     * @return int
1768
     */
1769
    public function getNumberOfRecords($language = null)
1770
    {
1771
        $now = date('YmdHis');
1772
1773
        $query = sprintf("
1774
            SELECT
1775
                id
1776
            FROM
1777
                %sfaqdata
1778
            WHERE
1779
                active = 'yes'
1780
            %s
1781
            AND
1782
                date_start <= '%s'
1783
            AND
1784
                date_end >= '%s'",
1785
            PMF_Db::getTablePrefix(),
1786
            null == $language ? '' : "AND lang = '".$language."'",
1787
            $now,
1788
            $now
1789
        );
1790
1791
        $num = $this->_config->getDb()->numRows($this->_config->getDb()->query($query));
1792
1793
        if ($num > 0) {
1794
            return $num;
1795
        } else {
1796
            return 0;
1797
        }
1798
    }
1799
1800
    /**
1801
     * This function generates a list with the most voted or most visited records.
1802
     *
1803
     * @param string $type Type definition visits/voted
1804
     *
1805
     * @since  2009-11-03
1806
     *
1807
     * @author Max Köhler <[email protected]>
1808
     *
1809
     * @return array
1810
     */
1811
    public function getTopTen($type = 'visits')
1812
    {
1813
        if ('visits' == $type) {
1814
            $result = $this->getTopTenData(PMF_NUMBER_RECORDS_TOPTEN, 0, $this->_config->getLanguage()->getLanguage());
1815
        } else {
1816
            $result = $this->getTopVotedData(PMF_NUMBER_RECORDS_TOPTEN, $this->_config->getLanguage()->getLanguage());
1817
        }
1818
        $output = [];
1819
1820
        if (count($result) > 0) {
1821
            foreach ($result as $row) {
1822
                if ('visits' == $type) {
1823
                    $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1824
                    $output['preview'][] = $row['question'];
1825
                    $output['url'][] = $row['url'];
1826
                    $output['visits'][] = $this->plr->GetMsg('plmsgViews', $row['visits']);
1827
                } else {
1828
                    $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1829
                    $output['preview'][] = $row['question'];
1830
                    $output['url'][] = $row['url'];
1831
                    $output['voted'][] = sprintf(
1832
                        '%s %s 5 - %s',
1833
                        round($row['avg'], 2),
1834
                        $this->pmf_lang['msgVoteFrom'],
1835
                        $this->plr->GetMsg('plmsgVotes', $row['user'])
1836
                    );
1837
                }
1838
            }
1839
        } else {
1840
            $output['error'] = $this->pmf_lang['err_noTopTen'];
1841
        }
1842
1843
        return $output;
1844
    }
1845
1846
    /**
1847
     * This function generates the list with the latest published records.
1848
     *
1849
     * @return array
1850
     */
1851
    public function getLatest()
1852
    {
1853
        $date = new PMF_Date($this->_config);
1854
        $result = $this->getLatestData(PMF_NUMBER_RECORDS_LATEST, $this->_config->getLanguage()->getLanguage());
1855
        $output = [];
1856
1857
        if (count($result) > 0) {
1858
            foreach ($result as $row) {
1859
                $output['url'][] = $row['url'];
1860
                $output['title'][] = PMF_Utils::makeShorterText($row['question'], 8);
1861
                $output['preview'][] = $row['question'];
1862
                $output['date'][] = $date->format(PMF_Date::createIsoDate($row['date']));
1863
            }
1864
        } else {
1865
            $output['error'] = $this->pmf_lang['err_noArticles'];
1866
        }
1867
1868
        return $output;
1869
    }
1870
1871
    /**
1872
     * Deletes a question for the table faqquestions.
1873
     *
1874
     * @param int $questionId
1875
     *
1876
     * @return bool
1877
     */
1878 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...
1879
    {
1880
        $delete = sprintf("
1881
            DELETE FROM
1882
                %sfaqquestions
1883
            WHERE
1884
                id = %d
1885
            AND
1886
                lang = '%s'",
1887
            PMF_Db::getTablePrefix(),
1888
            $questionId,
1889
            $this->_config->getLanguage()->getLanguage()
1890
        );
1891
1892
        $this->_config->getDb()->query($delete);
1893
1894
        return true;
1895
    }
1896
1897
     /**
1898
      * Returns the visibility of a question.
1899
      *
1900
      * @param   int $questionId
1901
      *
1902
      * @return  string
1903
      */
1904 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...
1905
     {
1906
         $query = sprintf("
1907
            SELECT
1908
                is_visible
1909
            FROM
1910
                %sfaqquestions
1911
            WHERE
1912
                id = %d
1913
            AND
1914
                lang = '%s'",
1915
            PMF_Db::getTablePrefix(),
1916
            $questionId,
1917
            $this->_config->getLanguage()->getLanguage()
1918
        );
1919
1920
         $result = $this->_config->getDb()->query($query);
1921
         if ($this->_config->getDb()->numRows($result) > 0) {
1922
             $row = $this->_config->getDb()->fetchObject($result);
1923
1924
             return $row->is_visible;
1925
         }
1926
1927
         return;
1928
     }
1929
1930
    /**
1931
     * Sets the visibility of a question.
1932
     *
1933
     * @param int    $questionId
1934
     * @param string $isVisible
1935
     *
1936
     * @return bool
1937
     */
1938 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...
1939
    {
1940
        $query = sprintf("
1941
            UPDATE
1942
                %sfaqquestions
1943
            SET
1944
                is_visible = '%s'
1945
            WHERE
1946
                id = %d
1947
            AND
1948
                lang = '%s'",
1949
            PMF_Db::getTablePrefix(),
1950
            $isVisible,
1951
            $questionId,
1952
            $this->_config->getLanguage()->getLanguage()
1953
        );
1954
1955
        $this->_config->getDb()->query($query);
1956
1957
        return true;
1958
    }
1959
1960
    /**
1961
     * This function generates a data-set with the most voted FAQs.
1962
     *  
1963
     * @param int    $count    Number of records
1964
     * @param string $language Language
1965
     *
1966
     * @return array
1967
     */
1968
    public function getTopVotedData($count = PMF_NUMBER_RECORDS_TOPTEN, $language = null)
1969
    {
1970
        global $sids;
1971
1972
        $topten = $data = [];
1973
1974
        $now = date('YmdHis');
1975
        $query =
1976
'            SELECT
1977
                fd.id AS id,
1978
                fd.lang AS lang,
1979
                fd.thema AS thema,
1980
                fd.updated AS updated,
1981
                fcr.category_id AS category_id,
1982
                (fv.vote/fv.usr) AS avg,
1983
                fv.usr AS user
1984
            FROM
1985
                '.PMF_Db::getTablePrefix().'faqvoting fv,
1986
                '.PMF_Db::getTablePrefix().'faqdata fd
1987
            LEFT JOIN
1988
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
1989
            ON
1990
                fd.id = fcr.record_id
1991
            AND
1992
                fd.lang = fcr.record_lang
1993
            LEFT JOIN
1994
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
1995
            ON
1996
                fd.id = fdg.record_id
1997
            LEFT JOIN
1998
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
1999
            ON
2000
                fd.id = fdu.record_id
2001
            WHERE
2002
                    fd.date_start <= \''.$now.'\'
2003
                AND fd.date_end   >= \''.$now.'\'
2004
                AND fd.id = fv.artikel
2005
                AND fd.active = \'yes\'';
2006
2007 View Code Duplication
        if (isset($categoryId) && is_numeric($categoryId) && ($categoryId != 0)) {
0 ignored issues
show
Bug introduced by
The variable $categoryId seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
2008
            $query .= '
2009
            AND
2010
                fcr.category_id = \''.$categoryId.'\'';
2011
        }
2012
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
2013
            $query .= '
2014
            AND
2015
                fd.lang = \''.$language.'\'';
2016
        }
2017
        $query .= '
2018
                '.$this->queryPermission($this->groupSupport).'
2019
            ORDER BY
2020
                avg DESC';
2021
2022
        $result = $this->_config->getDb()->query($query);
2023
2024
        $i = 1;
2025
        $oldId = 0;
2026
        while (($row = $this->_config->getDb()->fetchObject($result)) && $i <= $count) {
2027
            if ($oldId != $row->id) {
2028
                $data['avg'] = $row->avg;
2029
                $data['question'] = $row->thema;
2030
                $data['date'] = $row->updated;
2031
                $data['user'] = $row->user;
2032
2033
                $title = $row->thema;
2034
                $url = sprintf(
2035
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
2036
                    PMF_Link::getSystemRelativeUri(),
2037
                    $sids,
2038
                    $row->category_id,
2039
                    $row->id,
2040
                    $row->lang
2041
                );
2042
                $oLink = new PMF_Link($url, $this->_config);
2043
                $oLink->itemTitle = $row->thema;
2044
                $oLink->tooltip = $title;
2045
                $data['url'] = $oLink->toString();
2046
2047
                $topten[] = $data;
2048
                ++$i;
2049
            }
2050
            $oldId = $row->id;
2051
        }
2052
2053
        return $topten;
2054
    }
2055
2056
    /**
2057
     * This function generates the Top Ten data with the mosted viewed records.
2058
     *
2059
     * @param int    $count      Number of records
2060
     * @param int    $categoryId Category ID
2061
     * @param string $language   Language
2062
     *
2063
     * @return array
2064
     */
2065
    public function getTopTenData($count = PMF_NUMBER_RECORDS_TOPTEN, $categoryId = 0, $language = null)
2066
    {
2067
        global $sids;
2068
2069
        $now = date('YmdHis');
2070
        $query =
2071
'            SELECT
2072
                fd.id AS id,
2073
                fd.lang AS lang,
2074
                fd.thema AS question,
2075
                fd.updated AS updated,
2076
                fcr.category_id AS category_id,
2077
                fv.visits AS visits,
2078
                fv.last_visit AS last_visit,
2079
                fdg.group_id AS group_id,
2080
                fdu.user_id AS user_id
2081
            FROM
2082
                '.PMF_Db::getTablePrefix().'faqvisits fv,
2083
                '.PMF_Db::getTablePrefix().'faqdata fd
2084
            LEFT JOIN
2085
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
2086
            ON
2087
                fd.id = fcr.record_id
2088
            AND
2089
                fd.lang = fcr.record_lang
2090
            LEFT JOIN
2091
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
2092
            ON
2093
                fd.id = fdg.record_id
2094
            LEFT JOIN
2095
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
2096
            ON
2097
                fd.id = fdu.record_id
2098
            WHERE
2099
                    fd.date_start <= \''.$now.'\'
2100
                AND fd.date_end   >= \''.$now.'\'
2101
                AND fd.id = fv.id
2102
                AND fd.lang = fv.lang
2103
                AND fd.active = \'yes\'';
2104
2105 View Code Duplication
        if (isset($categoryId) && is_numeric($categoryId) && ($categoryId != 0)) {
2106
            $query .= '
2107
            AND
2108
                fcr.category_id = \''.$categoryId.'\'';
2109
        }
2110
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
2111
            $query .= '
2112
            AND
2113
                fd.lang = \''.$language.'\'';
2114
        }
2115
        $query .= '
2116
                '.$this->queryPermission($this->groupSupport).'
2117
2118
            GROUP BY
2119
                fd.id, fd.lang, fd.thema, fd.updated, fcr.category_id, fv.visits, fv.last_visit, fdg.group_id, fdu.user_id
2120
            ORDER BY
2121
                fv.visits DESC';
2122
2123
        $result = $this->_config->getDb()->query($query);
2124
        $topten = [];
2125
        $data = [];
2126
2127 View Code Duplication
        if ($result) {
2128
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2129
                if ($this->groupSupport) {
2130
                    if (!in_array($row->user_id, array(-1, $this->user)) || !in_array($row->group_id, $this->groups)) {
2131
                        continue;
2132
                    }
2133
                } else {
2134
                    if (!in_array($row->user_id, array(-1, $this->user))) {
2135
                        continue;
2136
                    }
2137
                }
2138
2139
                $data['visits'] = (int)$row->visits;
2140
                $data['question'] = PMF_Filter::filterVar($row->question, FILTER_SANITIZE_STRING);
2141
                $data['date'] = $row->updated;
2142
                $data['last_visit'] = $row->last_visit;
2143
2144
                $title = $row->question;
2145
                $url = sprintf(
2146
                    '%sindex.php?%saction=artikel&cat=%d&id=%d&artlang=%s',
2147
                    $this->_config->getDefaultUrl(),
2148
                    $sids,
2149
                    $row->category_id,
2150
                    $row->id,
2151
                    $row->lang
2152
                );
2153
                $oLink = new PMF_Link($url, $this->_config);
2154
                $oLink->itemTitle = $row->question;
2155
                $oLink->tooltip = $title;
2156
                $data['url'] = $oLink->toString();
2157
2158
                $topten[$row->id] = $data;
2159
2160
                if (count($topten) === $count) {
2161
                    break;
2162
                }
2163
            }
2164
2165
            array_multisort($topten, SORT_DESC);
2166
        }
2167
2168
        return $topten;
2169
    }
2170
2171
    /**
2172
     * This function generates an array with a specified number of most recent
2173
     * published records.
2174
     *
2175
     * @param int    $count    Number of records
2176
     * @param string $language Language
2177
     *
2178
     * @return array
2179
     */
2180
    public function getLatestData($count = PMF_NUMBER_RECORDS_LATEST, $language = null)
2181
    {
2182
        global $sids;
2183
2184
        $now = date('YmdHis');
2185
        $query =
2186
'            SELECT
2187
                fd.id AS id,
2188
                fd.lang AS lang,
2189
                fcr.category_id AS category_id,
2190
                fd.thema AS question,
2191
                fd.content AS content,
2192
                fd.updated AS updated,
2193
                fv.visits AS visits,
2194
                fdg.group_id AS group_id,
2195
                fdu.user_id AS user_id
2196
            FROM
2197
                '.PMF_Db::getTablePrefix().'faqvisits fv,
2198
                '.PMF_Db::getTablePrefix().'faqdata fd
2199
            LEFT JOIN
2200
                '.PMF_Db::getTablePrefix().'faqcategoryrelations fcr
2201
            ON
2202
                fd.id = fcr.record_id
2203
            AND
2204
                fd.lang = fcr.record_lang
2205
            LEFT JOIN
2206
                '.PMF_Db::getTablePrefix().'faqdata_group AS fdg
2207
            ON
2208
                fd.id = fdg.record_id
2209
            LEFT JOIN
2210
                '.PMF_Db::getTablePrefix().'faqdata_user AS fdu
2211
            ON
2212
                fd.id = fdu.record_id
2213
            WHERE
2214
                    fd.date_start <= \''.$now.'\'
2215
                AND fd.date_end   >= \''.$now.'\'
2216
                AND fd.id = fv.id
2217
                AND fd.lang = fv.lang
2218
                AND fd.active = \'yes\'';
2219
2220
        if (isset($language) && PMF_Language::isASupportedLanguage($language)) {
2221
            $query .= '
2222
            AND
2223
                fd.lang = \''.$language.'\'';
2224
        }
2225
        $query .= '
2226
                '.$this->queryPermission($this->groupSupport).'
2227
            GROUP BY
2228
                fd.id, fd.lang, fcr.category_id, fd.thema, fd.content, fd.updated, fv.visits, fdg.group_id, fdu.user_id
2229
            ORDER BY
2230
                fd.updated DESC';
2231
2232
        $result = $this->_config->getDb()->query($query);
2233
        $latest = [];
2234
        $data = [];
2235
2236 View Code Duplication
        if ($result) {
2237
            while (($row = $this->_config->getDb()->fetchObject($result))) {
2238
                if ($this->groupSupport) {
2239
                    if (!in_array($row->user_id, array(-1, $this->user)) || !in_array($row->group_id, $this->groups)) {
2240
                        continue;
2241
                    }
2242
                } else {
2243
                    if (!in_array($row->user_id, array(-1, $this->user))) {
2244
                        continue;
2245
                    }
2246
                }
2247
2248
                $data['date'] = $row->updated;
2249
                $data['question'] = PMF_Filter::filterVar($row->question, FILTER_SANITIZE_STRING);
2250
                $data['answer'] = $row->content;
2251
                $data['visits'] = $row->visits;
2252
2253
                $title = $row->question;
2254
                $url = sprintf(
2255
                    '%sindex.php?%saction=artikel&cat=%d&id=%d&artlang=%s',
2256
                    $this->_config->getDefaultUrl(),
2257
                    $sids,
2258
                    $row->category_id,
2259
                    $row->id,
2260
                    $row->lang
2261
                );
2262
                $oLink = new PMF_Link($url, $this->_config);
2263
                $oLink->itemTitle = $title;
2264
                $oLink->tooltip = $title;
2265
                $data['url'] = $oLink->toString();
2266
2267
                $latest[$row->id] = $data;
2268
2269
                if (count($latest) === $count) {
2270
                    break;
2271
                }
2272
            }
2273
        }
2274
        
2275
        return $latest;
2276
    }
2277
2278
    /**
2279
     * Reload locking for user votings.
2280
     *
2281
     * @param int    $id FAQ record id
2282
     * @param string $ip IP
2283
     *
2284
     * @return bool
2285
     */
2286
    public function votingCheck($id, $ip)
2287
    {
2288
        $check = $_SERVER['REQUEST_TIME'] - 300;
2289
        $query = sprintf(
2290
            "SELECT
2291
                id
2292
            FROM
2293
                %sfaqvoting
2294
            WHERE
2295
                artikel = %d AND (ip = '%s' AND datum > '%s')",
2296
            PMF_Db::getTablePrefix(),
2297
            $id,
2298
            $ip,
2299
            $check);
2300
        if ($this->_config->getDb()->numRows($this->_config->getDb()->query($query))) {
2301
            return false;
2302
        }
2303
2304
        return true;
2305
    }
2306
2307
    /**
2308
     * Returns the number of users from the table faqvotings.
2309
     *
2310
     * @param integer $record_id
2311
     *
2312
     * @return integer
2313
     */
2314 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...
2315
    {
2316
        $query = sprintf(
2317
            'SELECT
2318
                usr
2319
            FROM
2320
                %sfaqvoting
2321
            WHERE
2322
                artikel = %d',
2323
            PMF_Db::getTablePrefix(),
2324
            $record_id);
2325
        if ($result = $this->_config->getDb()->query($query)) {
2326
            if ($row = $this->_config->getDb()->fetchObject($result)) {
2327
                return $row->usr;
2328
            }
2329
        }
2330
2331
        return 0;
2332
    }
2333
2334
    /**
2335
     * Adds a new voting record.
2336
     *
2337
     * @param array $votingData
2338
     *
2339
     * @return bool
2340
     */
2341
    public function addVoting($votingData)
2342
    {
2343
        if (!is_array($votingData)) {
2344
            return false;
2345
        }
2346
2347
        $query = sprintf(
2348
            "INSERT INTO
2349
                %sfaqvoting
2350
            VALUES
2351
                (%d, %d, %d, 1, %d, '%s')",
2352
            PMF_Db::getTablePrefix(),
2353
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqvoting', 'id'),
2354
            $votingData['record_id'],
2355
            $votingData['vote'],
2356
            $_SERVER['REQUEST_TIME'],
2357
            $votingData['user_ip']);
2358
        $this->_config->getDb()->query($query);
2359
2360
        return true;
2361
    }
2362
2363
    /**
2364
     * Adds a new question.
2365
     *
2366
     * @param array $questionData
2367
     *
2368
     * @return bool
2369
     */
2370
    public function addQuestion(Array $questionData)
2371
    {
2372
        $query = sprintf("
2373
            INSERT INTO
2374
                %sfaqquestions
2375
            (id, lang, username, email, category_id, question, created, is_visible, answer_id)
2376
                VALUES
2377
            (%d, '%s', '%s', '%s', %d, '%s', '%s', '%s', %d)",
2378
            PMF_Db::getTablePrefix(),
2379
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqquestions', 'id'),
2380
            $this->_config->getLanguage()->getLanguage(),
2381
            $this->_config->getDb()->escape($questionData['username']),
2382
            $this->_config->getDb()->escape($questionData['email']),
2383
            $questionData['category_id'],
2384
            $this->_config->getDb()->escape($questionData['question']),
2385
            date('YmdHis'),
2386
            $questionData['is_visible'],
2387
            0
2388
        );
2389
        $this->_config->getDb()->query($query);
2390
2391
        return true;
2392
    }
2393
2394
    /**
2395
     * Returns a new question.
2396
     *
2397
     * @param int $questionId
2398
     *
2399
     * @return array
2400
     */
2401
    public function getQuestion($questionId)
2402
    {
2403
        $question = [
2404
            'id' => 0,
2405
            'lang' => '',
2406
            'username' => '',
2407
            'email' => '',
2408
            'category_id' => '',
2409
            'question' => '',
2410
            'created' => '',
2411
            'is_visible' => '',
2412
        ];
2413
2414
        if (!is_int($questionId)) {
2415
            return $question;
2416
        }
2417
2418
        $question = [];
2419
2420
        $query = sprintf("
2421
            SELECT
2422
                 id, lang, username, email, category_id, question, created, is_visible
2423
            FROM
2424
                %sfaqquestions
2425
            WHERE
2426
                id = %d
2427
            AND
2428
                lang = '%s'",
2429
            PMF_Db::getTablePrefix(),
2430
            $questionId,
2431
            $this->_config->getLanguage()->getLanguage()
2432
        );
2433
2434 View Code Duplication
        if ($result = $this->_config->getDb()->query($query)) {
2435
            if ($row = $this->_config->getDb()->fetchObject($result)) {
2436
                $question = array(
2437
                    'id' => $row->id,
2438
                    'lang' => $row->lang,
2439
                    'username' => $row->username,
2440
                    'email' => $row->email,
2441
                    'category_id' => $row->category_id,
2442
                    'question' => $row->question,
2443
                    'created' => $row->created,
2444
                    'is_visible' => $row->is_visible, );
2445
            }
2446
        }
2447
2448
        return $question;
2449
    }
2450
2451
    /**
2452
     * Returns all open questions.
2453
     *
2454
     * @param boolean $all If true, then return visible and non-visible
2455
     *                     questions; otherwise only visible ones
2456
     *
2457
     * @return array
2458
     */
2459
    public function getAllOpenQuestions($all = true)
2460
    {
2461
        $questions = [];
2462
2463
        $query = sprintf("
2464
            SELECT
2465
                id, lang, username, email, category_id, question, created, answer_id, is_visible
2466
            FROM
2467
                %sfaqquestions
2468
            WHERE
2469
                lang = '%s'
2470
                %s
2471
            ORDER BY 
2472
                created ASC",
2473
            PMF_Db::getTablePrefix(),
2474
            $this->_config->getLanguage()->getLanguage(),
2475
            ($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...
2476
        );
2477
2478 View Code Duplication
        if ($result = $this->_config->getDb()->query($query)) {
2479
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2480
                $questions[] = array(
2481
                    'id' => $row->id,
2482
                    'lang' => $row->lang,
2483
                    'username' => $row->username,
2484
                    'email' => $row->email,
2485
                    'category_id' => $row->category_id,
2486
                    'question' => $row->question,
2487
                    'created' => $row->created,
2488
                    'answer_id' => $row->answer_id,
2489
                    'is_visible' => $row->is_visible,
2490
                );
2491
             }
2492
        }
2493
2494
        return $questions;
2495
    }
2496
2497
    /**
2498
     * Updates an existing voting record.
2499
     *
2500
     * @param array $votingData
2501
     *
2502
     * @return bool
2503
     */
2504
    public function updateVoting($votingData)
2505
    {
2506
        if (!is_array($votingData)) {
2507
            return false;
2508
        }
2509
2510
        $query = sprintf(
2511
            "UPDATE
2512
                %sfaqvoting
2513
            SET
2514
                vote    = vote + %d,
2515
                usr     = usr + 1,
2516
                datum   = %d,
2517
                ip      = '%s'
2518
            WHERE
2519
                artikel = %d",
2520
            PMF_Db::getTablePrefix(),
2521
            $votingData['vote'],
2522
            $_SERVER['REQUEST_TIME'],
2523
            $votingData['user_ip'],
2524
            $votingData['record_id']);
2525
        $this->_config->getDb()->query($query);
2526
2527
        return true;
2528
    }
2529
2530
    /**
2531
     * Adds a new changelog entry in the table faqchanges.
2532
     *
2533
     * @param int    $id
2534
     * @param int    $userId
2535
     * @param string $text
2536
     * @param string $lang
2537
     * @param int    $revision_id
2538
     *
2539
     * @return bool
2540
     */
2541
    public function createChangeEntry($id, $userId, $text, $lang, $revision_id = 0)
2542
    {
2543
        if (!is_numeric($id)
2544
            && !is_numeric($userId)
2545
            && !is_string($text)
2546
            && !is_string($lang)
2547
            ) {
2548
            return false;
2549
        }
2550
2551
        $query = sprintf(
2552
            "INSERT INTO
2553
                %sfaqchanges
2554
            (id, beitrag, lang, revision_id, usr, datum, what)
2555
                VALUES
2556
            (%d, %d, '%s', %d, %d, %d, '%s')",
2557
            PMF_Db::getTablePrefix(),
2558
            $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqchanges', 'id'),
2559
            $id,
2560
            $lang,
2561
            $revision_id,
2562
            $userId,
2563
            $_SERVER['REQUEST_TIME'],
2564
            $text);
2565
2566
        $this->_config->getDb()->query($query);
2567
2568
        return true;
2569
    }
2570
2571
    /**
2572
     * Returns the changelog of a FAQ record.
2573
     *
2574
     * @param int $recordId
2575
     *
2576
     * @return array
2577
     */
2578 View Code Duplication
    public function getChangeEntries($recordId)
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...
2579
    {
2580
        $entries = [];
2581
2582
        $query = sprintf('
2583
            SELECT
2584
                DISTINCT revision_id, usr, datum, what
2585
            FROM
2586
                %sfaqchanges
2587
            WHERE
2588
                beitrag = %d
2589
            ORDER BY revision_id DESC',
2590
            PMF_Db::getTablePrefix(),
2591
            $recordId
2592
        );
2593
2594
        if ($result = $this->_config->getDb()->query($query)) {
2595
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2596
                $entries[] = array(
2597
                    'revision_id' => $row->revision_id,
2598
                    'user' => $row->usr,
2599
                    'date' => $row->datum,
2600
                    'changelog' => $row->what, );
2601
            }
2602
        }
2603
2604
        return $entries;
2605
    }
2606
2607
    /**
2608
     * Retrieve faq records according to the constraints provided.
2609
     *
2610
     * @param string $queryType
2611
     * @param int    $nCatid
2612
     * @param bool   $bDownwards
2613
     * @param string $lang
2614
     * @param string $date
2615
     *
2616
     * @return array
2617
     */
2618
    public function get($queryType = FAQ_QUERY_TYPE_DEFAULT, $nCatid = 0, $bDownwards = true, $lang = '', $date = '')
2619
    {
2620
        $faqs = [];
2621
2622
        $result = $this->_config->getDb()->query($this->_getSQLQuery($queryType, $nCatid, $bDownwards, $lang, $date));
2623
2624
        if ($this->_config->getDb()->numRows($result) > 0) {
2625
            $i = 0;
2626
            while ($row = $this->_config->getDb()->fetchObject($result)) {
2627
                $faq = [];
2628
                $faq['id'] = $row->id;
2629
                $faq['solution_id'] = $row->solution_id;
2630
                $faq['revision_id'] = $row->revision_id;
2631
                $faq['lang'] = $row->lang;
2632
                $faq['category_id'] = $row->category_id;
2633
                $faq['active'] = $row->active;
2634
                $faq['sticky'] = $row->sticky;
2635
                $faq['keywords'] = $row->keywords;
2636
                $faq['topic'] = $row->thema;
2637
                $faq['content'] = $row->content;
2638
                $faq['author_name'] = $row->author;
2639
                $faq['author_email'] = $row->email;
2640
                $faq['comment_enable'] = $row->comment;
2641
                $faq['lastmodified'] = $row->updated;
2642
                $faq['hits'] = $row->visits;
2643
                $faq['hits_last'] = $row->last_visit;
2644
                $faq['notes'] = $row->notes;
2645
                $faqs[$i] = $faq;
2646
                ++$i;
2647
            }
2648
        }
2649
2650
        return $faqs;
2651
    }
2652
2653
    /**
2654
     * Build a logic sequence, for a WHERE statement, of those category IDs
2655
     * children of the provided category ID, if any.
2656
     *
2657
     * @param   $nCatid
2658
     * @param   $logicOp
2659
     * @param   $oCat
2660
     *
2661
     * @return string
2662
     */
2663
    public function _getCatidWhereSequence($nCatid, $logicOp = 'OR', $oCat = null)
2664
    {
2665
        $sqlWherefilter = '';
2666
2667
        if (!isset($oCat)) {
2668
            $oCat = new PMF_Category($this->_config);
2669
        }
2670
        $aChildren = array_values($oCat->getChildren($nCatid));
2671
2672
        foreach ($aChildren as $catid) {
2673
            $sqlWherefilter .= ' '.$logicOp.' fcr.category_id = '.$catid;
2674
            $sqlWherefilter .= $this->_getCatidWhereSequence($catid, 'OR', $oCat);
2675
        }
2676
2677
        return $sqlWherefilter;
2678
    }
2679
2680
    /**
2681
     * Build the SQL query for retrieving faq records according to the constraints provided.
2682
     *
2683
     * @param   $QueryType
2684
     * @param   $nCatid
2685
     * @param   $bDownwards
2686
     * @param   $lang
2687
     * @param   $date
2688
     * @param   $faqid
2689
     *
2690
     * @return array
2691
     */
2692
    private function _getSQLQuery($QueryType, $nCatid, $bDownwards, $lang, $date, $faqid = 0)
2693
    {
2694
        $now = date('YmdHis');
2695
        $query = sprintf("
2696
            SELECT
2697
                fd.id AS id,
2698
                fd.solution_id AS solution_id,
2699
                fd.revision_id AS revision_id,
2700
                fd.lang AS lang,
2701
                fcr.category_id AS category_id,
2702
                fd.active AS active,
2703
                fd.sticky AS sticky,
2704
                fd.keywords AS keywords,
2705
                fd.thema AS thema,
2706
                fd.content AS content,
2707
                fd.author AS author,
2708
                fd.email AS email,
2709
                fd.comment AS comment,
2710
                fd.updated AS updated,
2711
                fd.notes AS notes,
2712
                fv.visits AS visits,
2713
                fv.last_visit AS last_visit
2714
            FROM
2715
                %sfaqdata fd,
2716
                %sfaqvisits fv,
2717
                %sfaqcategoryrelations fcr
2718
            WHERE
2719
                fd.id = fcr.record_id
2720
            AND
2721
                fd.lang = fcr.record_lang
2722
            AND
2723
                fd.date_start <= '%s'
2724
            AND
2725
                fd.date_end   >= '%s'
2726
            AND ",
2727
            PMF_Db::getTablePrefix(),
2728
            PMF_Db::getTablePrefix(),
2729
            PMF_Db::getTablePrefix(),
2730
            $now,
2731
            $now);
2732
        // faqvisits data selection
2733
        if (!empty($faqid)) {
2734
            // Select ONLY the faq with the provided $faqid
2735
            $query .= "fd.id = '".$faqid."' AND ";
2736
        }
2737
        $query .= 'fd.id = fv.id
2738
            AND
2739
                fd.lang = fv.lang';
2740
        $needAndOp = true;
2741
        if ((!empty($nCatid)) && is_int($nCatid) && $nCatid > 0) {
2742
            if ($needAndOp) {
2743
                $query .= ' AND';
2744
            }
2745
            $query .= ' (fcr.category_id = '.$nCatid;
2746
            if ($bDownwards) {
2747
                $query .= $this->_getCatidWhereSequence($nCatid, 'OR');
2748
            }
2749
            $query .= ')';
2750
            $needAndOp = true;
2751
        }
2752 View Code Duplication
        if ((!empty($date)) && PMF_Utils::isLikeOnPMFDate($date)) {
2753
            if ($needAndOp) {
2754
                $query .= ' AND';
2755
            }
2756
            $query .= " fd.updated LIKE '".$date."'";
2757
            $needAndOp = true;
2758
        }
2759 View Code Duplication
        if ((!empty($lang)) && PMF_Utils::isLanguage($lang)) {
2760
            if ($needAndOp) {
2761
                $query .= ' AND';
2762
            }
2763
            $query .= " fd.lang = '".$lang."'";
2764
            $needAndOp = true;
2765
        }
2766
        switch ($QueryType) {
2767
            case FAQ_QUERY_TYPE_APPROVAL:
2768
                if ($needAndOp) {
2769
                    $query .= ' AND';
2770
                }
2771
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_NO."'";
2772
                break;
2773
            case FAQ_QUERY_TYPE_EXPORT_PDF:
2774
            case FAQ_QUERY_TYPE_EXPORT_XHTML:
2775
            case FAQ_QUERY_TYPE_EXPORT_XML:
2776
                if ($needAndOp) {
2777
                    $query .= ' AND';
2778
                }
2779
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_YES."'";
2780
                break;
2781
            default:
2782
                if ($needAndOp) {
2783
                    $query .= ' AND';
2784
                }
2785
                $query .= " fd.active = '".FAQ_SQL_ACTIVE_YES."'";
2786
                break;
2787
        }
2788
        // Sort criteria
2789
        switch ($QueryType) {
2790
            case FAQ_QUERY_TYPE_EXPORT_PDF:
2791
            case FAQ_QUERY_TYPE_EXPORT_XHTML:
2792
            case FAQ_QUERY_TYPE_EXPORT_XML:
2793
                $query .= "\nORDER BY fcr.category_id, fd.id";
2794
                break;
2795
            case FAQ_QUERY_TYPE_RSS_LATEST:
2796
                $query .= "\nORDER BY fd.updated DESC";
2797
                break;
2798
            default:
2799
                // Normal ordering
2800
                $query .= "\nORDER BY fcr.category_id, fd.id";
2801
                break;
2802
        }
2803
2804
        return $query;
2805
    }
2806
2807
    /**
2808
     * Adds the record permissions for users and groups.
2809
     *
2810
     * @param string $mode     'group' or 'user'
2811
     * @param int    $recordId ID of the current record
2812
     * @param array  $ids      Array of group or user IDs
2813
     *
2814
     * @return bool
2815
     */
2816
    public function addPermission($mode, $recordId, $ids)
2817
    {
2818
        if ('user' !== $mode && 'group' !== $mode) {
2819
            return false;
2820
        }
2821
2822
        foreach ($ids as $id) {
2823
            $query = sprintf('
2824
            INSERT INTO
2825
                %sfaqdata_%s
2826
            (record_id, %s_id)
2827
                VALUES
2828
            (%d, %d)',
2829
                PMF_Db::getTablePrefix(),
2830
                $mode,
2831
                $mode,
2832
                $recordId,
2833
                $id
2834
            );
2835
2836
            $this->_config->getDb()->query($query);
2837
        }
2838
2839
        return true;
2840
    }
2841
2842
    /**
2843
     * Deletes the record permissions for users and groups.
2844
     *
2845
     * @param string $mode      'group' or 'user'
2846
     * @param int    $record_id ID of the current record
2847
     *
2848
     * @return bool
2849
     *
2850
     * @author  Thorsten Rinne <[email protected]>
2851
     */
2852 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...
2853
    {
2854
        if (!($mode == 'user' || $mode == 'group')) {
2855
            return false;
2856
        }
2857
        if (!is_int($record_id)) {
2858
            return false;
2859
        }
2860
2861
        $query = sprintf('
2862
            DELETE FROM
2863
                %sfaqdata_%s
2864
            WHERE
2865
                record_id = %d',
2866
            PMF_Db::getTablePrefix(),
2867
            $mode,
2868
            $record_id);
2869
        $this->_config->getDb()->query($query);
2870
2871
        return true;
2872
    }
2873
2874
    /**
2875
     * Returns the record permissions for users and groups.
2876
     *
2877
     * @param string $mode     'group' or 'user'
2878
     * @param int    $recordId
2879
     *
2880
     * @return array
2881
     */
2882
    public function getPermission($mode, $recordId)
2883
    {
2884
        $permissions = [];
2885
2886
        if (!($mode == 'user' || $mode == 'group')) {
2887
            return false;
2888
        }
2889
2890
        $query = sprintf('
2891
            SELECT
2892
                %s_id AS permission
2893
            FROM
2894
                %sfaqdata_%s
2895
            WHERE
2896
                record_id = %d',
2897
            $mode,
2898
            PMF_Db::getTablePrefix(),
2899
            $mode,
2900
            (int) $recordId);
2901
2902
        $result = $this->_config->getDb()->query($query);
2903
2904
        if ($this->_config->getDb()->numRows($result) > 0) {
2905
            while (($row = $this->_config->getDb()->fetchObject($result))) {
2906
                $permissions[] = (int) $row->permission;
2907
            }
2908
        }
2909
2910
        return $permissions;
2911
    }
2912
2913
    /**
2914
     * Returns all records of one category.
2915
     *
2916
     * @param int $category
2917
     *
2918
     * @return string
2919
     */
2920
    public function showAllRecordsWoPaging($category)
2921
    {
2922
        global $sids;
2923
2924
        $now = date('YmdHis');
2925
        $query = sprintf("
2926
            SELECT
2927
                fd.id AS id,
2928
                fd.lang AS lang,
2929
                fd.thema AS thema,
2930
                fcr.category_id AS category_id,
2931
                fv.visits AS visits
2932
            FROM
2933
                %sfaqdata fd
2934
            LEFT JOIN
2935
                %sfaqcategoryrelations fcr
2936
            ON
2937
                fd.id = fcr.record_id
2938
            AND
2939
                fd.lang = fcr.record_lang
2940
            LEFT JOIN
2941
                %sfaqvisits fv
2942
            ON
2943
                fd.id = fv.id
2944
            AND
2945
                fv.lang = fd.lang
2946
            LEFT JOIN
2947
                %sfaqdata_group fdg
2948
            ON
2949
                fd.id = fdg.record_id
2950
            LEFT JOIN
2951
                %sfaqdata_user fdu
2952
            ON
2953
                fd.id = fdu.record_id
2954
            WHERE
2955
                fd.date_start <= '%s'
2956
            AND
2957
                fd.date_end   >= '%s'
2958
            AND
2959
                fd.active = 'yes'
2960
            AND
2961
                fcr.category_id = %d
2962
            AND
2963
                fd.lang = '%s'
2964
            GROUP BY
2965
                fd.id, fd.lang, fd.thema, fcr.category_id, fv.visits
2966
            ORDER BY
2967
                %s %s",
2968
            PMF_Db::getTablePrefix(),
2969
            PMF_Db::getTablePrefix(),
2970
            PMF_Db::getTablePrefix(),
2971
            PMF_Db::getTablePrefix(),
2972
            PMF_Db::getTablePrefix(),
2973
            $now,
2974
            $now,
2975
            $category,
2976
            $this->_config->getLanguage()->getLanguage(),
2977
            $this->_config->get('records.orderby'),
2978
            $this->_config->get('records.sortby')
2979
        );
2980
2981
        $result = $this->_config->getDb()->query($query);
2982
        $output = '';
2983
        
2984
        if ($result) {
2985
            $output = '<ul class="phpmyfaq_ul">';
2986
            while (($row = $this->_config->getDb()->fetchObject($result))) {
2987
                $title = PMF_Filter::filterVar($row->thema, FILTER_SANITIZE_STRING);
2988
                $url = sprintf(
2989
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
2990
                    PMF_Link::getSystemRelativeUri(),
2991
                    $sids,
2992
                    $row->category_id,
2993
                    $row->id,
2994
                    $row->lang
2995
                );
2996
2997
                $oLink = new PMF_Link($url, $this->_config);
2998
                $oLink->itemTitle = $title;
2999
                $oLink->text = $title;
3000
                $oLink->tooltip = $title;
3001
                $listItem = '<li>' . $oLink->toHtmlAnchor() . '</li>';
3002
3003
                $output .= $listItem;
3004
            }
3005
            $output .= '</ul>';
3006
        }
3007
3008
        return $output;
3009
    }
3010
3011
    /**
3012
     * Prints the open questions as a XHTML table.
3013
     *
3014
     * @return string
3015
     */
3016
    public function printOpenQuestions($user)
3017
    {
3018
        global $sids, $category;
3019
3020
        $date = new PMF_Date($this->_config);
3021
        $mail = new PMF_Mail($this->_config);
3022
3023
        $query = sprintf("
3024
            SELECT
3025
                COUNT(id) AS num
3026
            FROM
3027
                %sfaqquestions
3028
            WHERE
3029
                lang = '%s'
3030
            AND
3031
                is_visible != 'Y'",
3032
            PMF_Db::getTablePrefix(),
3033
            $this->_config->getLanguage()->getLanguage()
3034
        );
3035
3036
        $result = $this->_config->getDb()->query($query);
3037
        $row = $this->_config->getDb()->fetchObject($result);
3038
        $numOfInvisibles = $row->num;
3039
3040
        if ($numOfInvisibles > 0) {
3041
            $extraout = sprintf(
3042
                '<tr><td colspan="3"><small>%s %s</small></td></tr>',
3043
                $this->pmf_lang['msgQuestionsWaiting'],
3044
                $numOfInvisibles
3045
            );
3046
        } else {
3047
            $extraout = '';
3048
        }
3049
3050
        $query = sprintf("
3051
            SELECT
3052
                *
3053
            FROM
3054
                %sfaqquestions
3055
            WHERE
3056
                lang = '%s'
3057
            AND
3058
                is_visible = 'Y'
3059
            ORDER BY
3060
                created ASC",
3061
            PMF_Db::getTablePrefix(),
3062
            $this->_config->getLanguage()->getLanguage()
3063
        );
3064
3065
        $result = $this->_config->getDb()->query($query);
3066
        $output = '';
3067
3068
        if ($result && $this->_config->getDb()->numRows($result) > 0) {
3069
            while ($row = $this->_config->getDb()->fetchObject($result)) {
3070
                $output .= '<tr class="openquestions">';
3071
                $output .= sprintf(
3072
                    '<td><small>%s</small><br /><a href="mailto:%s">%s</a></td>',
3073
                    $date->format(PMF_Date::createIsoDate($row->created)),
3074
                    $mail->safeEmail($row->email),
3075
                    $row->username
3076
                );
3077
                $output .= sprintf(
3078
                    '<td><strong>%s:</strong><br />%s</td>',
3079
                    isset($category->categoryName[$row->category_id]['name']) ? $category->categoryName[$row->category_id]['name'] : '',
3080
                    strip_tags($row->question)
3081
                );
3082
                if ($this->_config->get('records.enableCloseQuestion') && $row->answer_id) {
3083
                    $output .= sprintf(
3084
                        '<td><a id="PMF_openQuestionAnswered" href="?%saction=artikel&amp;cat=%d&amp;id=%d">%s</a></td>',
3085
                        $sids,
3086
                        $row->category_id,
3087
                        $row->answer_id,
3088
                        $this->pmf_lang['msg2answerFAQ']
3089
                    );
3090
                } else if(!$this->_config->get('records.allowNewFaqsForGuests') &&
3091
                          !$user->perm->checkRight($user->getUserId(), 'addfaq')) {
3092
                    $output .= sprintf(
3093
                        '<td>%s</td>',
3094
                        $this->pmf_lang['msg2unanswerFAQ']
3095
                    );
3096
                } else {
3097
                    $output .= sprintf(
3098
                        '<td><a class="btn btn-primary" href="?%saction=add&amp;question=%d&amp;cat=%d">%s</a></td>',
3099
                        $sids,
3100
                        $row->id,
3101
                        $row->category_id,
3102
                        $this->pmf_lang['msg2answer']
3103
                    );
3104
                }
3105
                $output .= '</tr>';
3106
            }
3107
        } else {
3108
            $output = sprintf(
3109
                '<tr><td colspan="3">%s</td></tr>',
3110
                $this->pmf_lang['msgNoQuestionsAvailable']
3111
            );
3112
        }
3113
3114
        return $output.$extraout;
3115
    }
3116
3117
    /**
3118
     * Set or unset a faq item flag.
3119
     *
3120
     * @param int    $id   Record id
3121
     * @param string $lang language code which is valid with Language::isASupportedLanguage
3122
     * @param bool   $flag weither or not the record is set to sticky
3123
     * @param string $type type of the flag to set, use the column name
3124
     *
3125
     * @return bool
3126
     */
3127
    public function updateRecordFlag($id, $lang, $flag, $type)
3128
    {
3129
        $retval = false;
3130
3131
        switch ($type) {
3132
            case 'sticky':
3133
                $flag = ($flag === 'checked' ? 1 : 0);
3134
                break;
3135
3136
            case 'active':
3137
                $flag = ($flag === 'checked' ? "'yes'" : "'no'");
3138
                break;
3139
3140
            default:
3141
                // This is because we would run into unknown db column
3142
                $flag = null;
3143
                break;
3144
        }
3145
3146
        if (null !== $flag) {
3147
            $update = sprintf("
3148
                UPDATE 
3149
                    %sfaqdata 
3150
                SET 
3151
                    %s = %s 
3152
                WHERE 
3153
                    id = %d 
3154
                AND 
3155
                    lang = '%s'",
3156
                PMF_Db::getTablePrefix(),
3157
                $type,
3158
                $flag,
3159
                $id,
3160
                $lang
3161
            );
3162
3163
            $retval = (bool) $this->_config->getDb()->query($update);
3164
        }
3165
3166
        return $retval;
3167
    }
3168
3169
    /**
3170
     * Returns the sticky records with URL and Title.
3171
     *
3172
     * @return array
3173
     */
3174
    private function getStickyRecordsData()
3175
    {
3176
        global $sids;
3177
3178
        $now = date('YmdHis');
3179
        $query = sprintf("
3180
            SELECT
3181
                fd.id AS id,
3182
                fd.lang AS lang,
3183
                fd.thema AS thema,
3184
                fcr.category_id AS category_id
3185
            FROM
3186
                %sfaqdata fd
3187
            LEFT JOIN
3188
                %sfaqcategoryrelations fcr
3189
            ON
3190
                fd.id = fcr.record_id
3191
            AND
3192
                fd.lang = fcr.record_lang
3193
            LEFT JOIN
3194
                %sfaqdata_group AS fdg
3195
            ON
3196
                fd.id = fdg.record_id
3197
            LEFT JOIN
3198
                %sfaqdata_user AS fdu
3199
            ON
3200
                fd.id = fdu.record_id
3201
            WHERE
3202
                fd.lang = '%s'
3203
            AND 
3204
                fd.date_start <= '%s'
3205
            AND 
3206
                fd.date_end   >= '%s'
3207
            AND 
3208
                fd.active = 'yes'
3209
            AND 
3210
                fd.sticky = 1
3211
            %s",
3212
            PMF_Db::getTablePrefix(),
3213
            PMF_Db::getTablePrefix(),
3214
            PMF_Db::getTablePrefix(),
3215
            PMF_Db::getTablePrefix(),
3216
            $this->_config->getLanguage()->getLanguage(),
3217
            $now,
3218
            $now,
3219
            $this->queryPermission($this->groupSupport)
3220
        );
3221
3222
        $result = $this->_config->getDb()->query($query);
3223
        $sticky = [];
3224
        $data = [];
3225
3226
        $oldId = 0;
3227
        while (($row = $this->_config->getDb()->fetchObject($result))) {
3228
            if ($oldId != $row->id) {
3229
                $data['thema'] = $row->thema;
3230
3231
                $title = $row->thema;
3232
                $url = sprintf(
3233
                    '%s?%saction=artikel&amp;cat=%d&amp;id=%d&amp;artlang=%s',
3234
                    PMF_Link::getSystemRelativeUri(),
3235
                    $sids,
3236
                    $row->category_id,
3237
                    $row->id,
3238
                    $row->lang
3239
                );
3240
                $oLink = new PMF_Link($url, $this->_config);
3241
                $oLink->itemTitle = $row->thema;
3242
                $oLink->tooltip = $title;
3243
                $data['url'] = $oLink->toString();
3244
3245
                $sticky[] = $data;
3246
            }
3247
            $oldId = $row->id;
3248
        }
3249
3250
        return $sticky;
3251
    }
3252
3253
    /**
3254
     * Prepares and returns the sticky records for the frontend.
3255
     *
3256
     * @return array
3257
     */
3258
    public function getStickyRecords()
3259
    {
3260
        $result = $this->getStickyRecordsData();
3261
        $output = [];
3262
3263
        if (count($result) > 0) {
3264
            foreach ($result as $row) {
3265
                $output[] = array(
3266
                    'title' => PMF_Utils::makeShorterText($row['thema'], 8),
3267
                    'preview' => $row['thema'],
3268
                    'url' => $row['url'],
3269
                );
3270
            }
3271
        } else {
3272
            $output['error'] = sprintf('<li>%s</li>', $this->pmf_lang['err_noTopTen']);
3273
        }
3274
        if (!isset($output['error'])) {
3275
            $html = '';
3276
            foreach ($output as $entry) {
3277
                $html .= sprintf(
3278
                    '<li><a class="sticky-faqs" data-toggle="tooltip" data-placement="top" title="%s" href="%s">%s</a></li>',
3279
                    $entry['preview'],
3280
                    $entry['url'],
3281
                    $entry['title']
3282
                );
3283
            }
3284
            $output['html'] = $html;
3285
        }
3286
3287
        return $output;
3288
    }
3289
3290
    /**
3291
     * Updates field answer_id in faqquestion.
3292
     *
3293
     * @param int $openQuestionId
3294
     * @param int $faqId
3295
     * @param int $categoryId
3296
     *
3297
     * @return bool
3298
     */
3299 View Code Duplication
    public function updateQuestionAnswer($openQuestionId, $faqId, $categoryId)
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...
3300
    {
3301
        $query = sprintf(
3302
            'UPDATE %sfaqquestions SET answer_id = %d, category_id= %d WHERE id= %d',
3303
            PMF_Db::getTablePrefix(),
3304
            $faqId,
3305
            $categoryId,
3306
            $openQuestionId
3307
        );
3308
3309
        return $this->_config->getDb()->query($query);
3310
    }
3311
3312
    /**
3313
     * Returns a part of a query to check permissions.
3314
     *
3315
     * @param bool $hasGroupSupport
3316
     *
3317
     * @return string
3318
     */
3319
    protected function queryPermission($hasGroupSupport = false)
3320
    {
3321
        if ($hasGroupSupport) {
3322
            if (-1 === $this->user) {
3323
                return sprintf(
3324
                    'AND fdg.group_id IN (%s)',
3325
                    implode(', ', $this->groups),
3326
                    $this->user,
3327
                    implode(', ', $this->groups));
3328 View Code Duplication
            } else {
3329
                return sprintf(
3330
                    'AND ( fdg.group_id IN (%s) OR (fdu.user_id = %d OR fdg.group_id IN (%s)) )',
3331
                    implode(', ', $this->groups),
3332
                    $this->user,
3333
                    implode(', ', $this->groups)
3334
                );
3335
            }
3336
        } else {
3337
            if (-1 !== $this->user) {
3338
                return sprintf(
3339
                    'AND ( fdu.user_id = %d OR fdu.user_id = -1 )',
3340
                    $this->user
3341
                );
3342
            } else {
3343
                return sprintf(
3344
                    'AND fdu.user_id = -1',
3345
                    $this->user
3346
                );
3347
            }
3348
        }
3349
    }
3350
}
3351