Passed
Branch master (a5e4e1)
by Michael
12:01
created

class/Item.php (1 issue)

Labels
Severity
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Publisher;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
/**
16
 * @copyright       The XUUPS Project https://sourceforge.net/projects/xuups/
17
 * @license         https://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @since           1.0
19
 * @author          trabis <[email protected]>
20
 * @author          The SmartFactory <www.smartfactory.ca>
21
 */
22
23
use Xmf\Request;
24
25
/** @var \XoopsMemberHandler $memberHandler */
26
/** @var \XoopsImageHandler $imageHandler */
27
require_once \dirname(__DIR__) . '/include/common.php';
28
29
/**
30
 * Class Item
31
 */
32
class Item extends \XoopsObject
33
{
34
    public const PAGEWRAP = '[pagewrap=';
35
    public const BODYTAG  = '<body>';
36
    /**
37
     * @var Helper
38
     */
39
    public $helper;
40
    /** @var \XoopsMySQLDatabase */
41
    public $db;
42
    public $groupsRead = [];
43
    /**
44
     * @var Category
45
     */
46
    public $category;
47
48
    /**
49
     * @param int|null $id
50
     */
51
    public function __construct($id = null)
52
    {
53
        //        $this->helper = Helper::getInstance();
54
        $this->db = \XoopsDatabaseFactory::getDatabaseConnection();
55
        $this->initVar('itemid', \XOBJ_DTYPE_INT, 0);
56
        $this->initVar('categoryid', \XOBJ_DTYPE_INT, 0, false);
57
        $this->initVar('title', \XOBJ_DTYPE_TXTBOX, '', true, 255);
58
        $this->initVar('subtitle', \XOBJ_DTYPE_TXTBOX, '', false, 255);
59
        $this->initVar('summary', \XOBJ_DTYPE_TXTAREA, '', false);
60
        $this->initVar('body', \XOBJ_DTYPE_TXTAREA, '', false);
61
        $this->initVar('uid', \XOBJ_DTYPE_INT, 0, false);
62
        $this->initVar('author_alias', \XOBJ_DTYPE_TXTBOX, '', false, 255);
63
        $this->initVar('datesub', \XOBJ_DTYPE_INT, '', false);
64
        $this->initVar('dateexpire', \XOBJ_DTYPE_INT, '', false);
65
        $this->initVar('status', \XOBJ_DTYPE_INT, -1, false);
66
        $this->initVar('image', \XOBJ_DTYPE_INT, 0, false);
67
        $this->initVar('images', \XOBJ_DTYPE_TXTBOX, '', false, 255);
68
        $this->initVar('counter', \XOBJ_DTYPE_INT, 0, false);
69
        $this->initVar('rating', \XOBJ_DTYPE_OTHER, 0, false);
70
        $this->initVar('votes', \XOBJ_DTYPE_INT, 0, false);
71
        $this->initVar('weight', \XOBJ_DTYPE_INT, 0, false);
72
        $this->initVar('dohtml', \XOBJ_DTYPE_INT, 1, true);
73
        $this->initVar('dosmiley', \XOBJ_DTYPE_INT, 1, true);
74
        $this->initVar('doimage', \XOBJ_DTYPE_INT, 1, true);
75
        $this->initVar('dobr', \XOBJ_DTYPE_INT, 1, false);
76
        $this->initVar('doxcode', \XOBJ_DTYPE_INT, 1, true);
77
        $this->initVar('cancomment', \XOBJ_DTYPE_INT, 1, true);
78
        $this->initVar('comments', \XOBJ_DTYPE_INT, 0, false);
79
        $this->initVar('notifypub', \XOBJ_DTYPE_INT, 1, false);
80
        $this->initVar('meta_keywords', \XOBJ_DTYPE_TXTAREA, '', false);
81
        $this->initVar('meta_description', \XOBJ_DTYPE_TXTAREA, '', false);
82
        $this->initVar('short_url', \XOBJ_DTYPE_TXTBOX, '', false, 255);
83
        $this->initVar('item_tag', \XOBJ_DTYPE_TXTAREA, '', false);
84
        $this->initVar('votetype', \XOBJ_DTYPE_INT, 0, false);
85
        // Non consistent values
86
        $this->initVar('pagescount', \XOBJ_DTYPE_INT, 0, false);
87
        if (null !== $id) {
88
            $item = $this->helper->getHandler('Item')->get($id);
89
            foreach ($item->vars as $k => $v) {
90
                $this->assignVar($k, $v['value']);
91
            }
92
        }
93
    }
94
95
    /**
96
     * @param string $method
97
     * @param array  $args
98
     *
99
     * @return mixed
100
     */
101
    public function __call($method, $args)
102
    {
103
        $arg = $args[0] ?? ''; //mb changed to empty string as in PHP 8.1 Passing null to parameter of type string is deprecated (in object.php on line 441)
104
105
        return $this->getVar($method, $arg);
106
    }
107
108
    /**
109
     * @return null|Category
110
     */
111
    public function getCategory()
112
    {
113
        if (null === $this->category) {
114
            $this->category = $this->helper->getHandler('Category')->get($this->getVar('categoryid'));
115
        }
116
117
        return $this->category;
118
    }
119
120
    /**
121
     * @param int    $maxLength
122
     * @param string $format
123
     *
124
     * @return mixed|string
125
     */
126
    public function getTitle($maxLength = 0, $format = 'S')
127
    {
128
        $ret = $this->getVar('title', $format);
129
        if (0 != $maxLength) {
130
            if (!XOOPS_USE_MULTIBYTES) {
131
                if (\mb_strlen($ret) >= $maxLength) {
132
                    $ret = Utility::substr($ret, 0, $maxLength);
133
                }
134
            }
135
        }
136
137
        return $ret;
138
    }
139
140
    /**
141
     * @param int    $maxLength
142
     * @param string $format
143
     *
144
     * @return mixed|string
145
     */
146
    public function getSubtitle($maxLength = 0, $format = 'S')
147
    {
148
        $ret = $this->getVar('subtitle', $format);
149
        if (0 != $maxLength) {
150
            if (!XOOPS_USE_MULTIBYTES) {
151
                if (\mb_strlen($ret) >= $maxLength) {
152
                    $ret = Utility::substr($ret, 0, $maxLength);
153
                }
154
            }
155
        }
156
157
        return $ret;
158
    }
159
160
    /**
161
     * @param int    $maxLength
162
     * @param string $format
163
     * @param string $stripTags
164
     *
165
     * @return mixed|string
166
     */
167
    public function getSummary($maxLength = 0, $format = 'S', $stripTags = '')
168
    {
169
        $ret = $this->getVar('summary', $format);
170
        if (!empty($stripTags)) {
171
            $ret = \strip_tags($ret, $stripTags);
172
        }
173
        if (0 != $maxLength) {
174
            if (!XOOPS_USE_MULTIBYTES) {
175
                if (\mb_strlen($ret) >= $maxLength) {
176
                    //$ret = Utility::substr($ret , 0, $maxLength);
177
                    //                    $ret = Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false);
178
                    $ret = Utility::truncateHtml($ret, $maxLength, $etc = '...', $breakWords = false);
179
                }
180
            }
181
        }
182
183
        return $ret;
184
    }
185
186
    /**
187
     * @param int  $maxLength
188
     * @param bool $fullSummary
189
     *
190
     * @return mixed|string
191
     */
192
    public function getBlockSummary($maxLength = 0, $fullSummary = false)
193
    {
194
        if ($fullSummary) {
195
            $ret = $this->getSummary(0, 's', '<br><br>');
196
        } else {
197
            $ret = $this->getSummary($maxLength, 's', '<br><br>');
198
        }
199
        //no summary? get body!
200
        if ('' === $ret) {
201
            $ret = $this->getBody($maxLength, 's', '<br><br>');
202
        }
203
204
        return $ret;
205
    }
206
207
    /**
208
     * @param string $fileName
209
     *
210
     * @return string
211
     */
212
    public function wrapPage($fileName)
213
    {
214
        $content = '';
215
        $page    = Utility::getUploadDir(true, 'content') . $fileName;
216
        if (\is_file($page)) {
217
            // this page uses smarty template
218
            \ob_start();
219
            require $page;
220
            $content = \ob_get_clean();
221
            // Cleaning the content
222
            $bodyStartPos = \mb_strpos($content, self::BODYTAG);
223
            if ($bodyStartPos) {
224
                $bodyEndPos = \mb_strpos($content, '</body>', $bodyStartPos);
225
                $content    = \mb_substr($content, $bodyStartPos + \mb_strlen(self::BODYTAG), $bodyEndPos - \mb_strlen(self::BODYTAG) - $bodyStartPos);
226
            }
227
            // Check if ML Hack is installed, and if yes, parse the $content in formatForML
228
            $myts = \MyTextSanitizer::getInstance();
229
            if (\method_exists($myts, 'formatForML')) {
230
                $content = $myts->formatForML($content);
231
            }
232
        }
233
234
        return $content;
235
    }
236
237
    /**
238
     * This method returns the body to be displayed. Not to be used for editing
239
     *
240
     * @param int    $maxLength
241
     * @param string $format
242
     * @param string $stripTags
243
     *
244
     * @return mixed|string
245
     */
246
    public function getBody($maxLength = 0, $format = 'S', $stripTags = '')
247
    {
248
        $ret     = $this->getVar('body', $format);
249
        $wrapPos = \mb_strpos($ret, self::PAGEWRAP);
250
        if (!(false === $wrapPos)) {
251
            $wrapPages      = [];
252
            $wrapCodeLength = \mb_strlen(self::PAGEWRAP);
253
            while (!(false === $wrapPos)) {
254
                $endWrapPos = \mb_strpos($ret, ']', $wrapPos);
255
                if ($endWrapPos) {
256
                    $wrapPagename = \mb_substr($ret, $wrapPos + $wrapCodeLength, $endWrapPos - $wrapCodeLength - $wrapPos);
257
                    $wrapPages[]  = $wrapPagename;
258
                }
259
                $wrapPos = \mb_strpos($ret, self::PAGEWRAP, $endWrapPos - 1);
260
            }
261
            foreach ($wrapPages as $page) {
262
                $wrapPageContent = $this->wrapPage($page);
263
                $ret             = \str_replace("[pagewrap={$page}]", $wrapPageContent, $ret);
264
            }
265
        }
266
        if ($this->helper->getConfig('item_disp_blocks_summary')) {
267
            $summary = $this->getSummary($maxLength, $format, $stripTags);
268
            if ($summary) {
269
                $ret = $this->getSummary() . '<br><br>' . $ret;
270
            }
271
        }
272
        if (!empty($stripTags)) {
273
            $ret = \strip_tags($ret, $stripTags);
274
        }
275
        if (0 != $maxLength) {
276
            if (!XOOPS_USE_MULTIBYTES) {
277
                if (\mb_strlen($ret) >= $maxLength) {
278
                    //$ret = Utility::substr($ret , 0, $maxLength);
279
                    $ret = Utility::truncateHtml($ret, $maxLength, $etc = '...', $breakWords = false);
280
                }
281
            }
282
        }
283
284
        return $ret;
285
    }
286
287
    /**
288
     * @param string $dateFormat
289
     * @param string $format
290
     *
291
     * @return string
292
     */
293
    public function getDatesub($dateFormat = '', $format = 'S')
294
    {
295
        if (empty($dateFormat)) {
296
            $dateFormat = $this->helper->getConfig('format_date');
297
        }
298
299
        return \formatTimestamp($this->getVar('datesub', $format), $dateFormat);
300
    }
301
302
    /**
303
     * @param string $dateFormat
304
     * @param string $format
305
     *
306
     * @return string|false
307
     */
308
    public function getDateExpire($dateFormat = '', $format = 'S')
309
    {
310
        if (empty($dateFormat)) {
311
            $dateFormat = $this->helper->getConfig('format_date');
312
        }
313
        if (0 == $this->getVar('dateexpire')) {
314
            return false;
315
        }
316
317
        return \formatTimestamp($this->getVar('dateexpire', $format), $dateFormat);
318
    }
319
320
    /**
321
     * @param int $realName
322
     *
323
     * @return string
324
     */
325
    public function posterName($realName = -1)
326
    {
327
        \xoops_load('XoopsUserUtility');
328
        if (-1 == $realName) {
329
            $realName = $this->helper->getConfig('format_realname');
330
        }
331
        $ret = $this->author_alias();
332
        if ('' == $ret) {
333
            $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $realName);
334
        }
335
336
        return $ret;
337
    }
338
339
    /**
340
     * @return string
341
     */
342
    public function posterAvatar()
343
    {
344
        $ret = 'blank.gif';
345
        /** @var \XoopsMemberHandler $memberHandler */
346
        $memberHandler = \xoops_getHandler('member');
347
        $thisUser      = $memberHandler->getUser($this->uid());
348
        if (\is_object($thisUser)) {
349
            $ret = $thisUser->getVar('user_avatar');
350
        }
351
352
        return $ret;
353
    }
354
355
    /**
356
     * @return string
357
     */
358
    public function getLinkedPosterName()
359
    {
360
        \xoops_load('XoopsUserUtility');
361
        $ret = $this->author_alias();
362
        if ('' === $ret) {
363
            $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $this->helper->getConfig('format_realname'), true);
364
        }
365
366
        return $ret;
367
    }
368
369
    /**
370
     * @return mixed
371
     */
372
    public function updateCounter()
373
    {
374
        return $this->helper->getHandler('Item')->updateCounter($this->itemid());
375
    }
376
377
    /**
378
     * @param bool $force
379
     *
380
     * @return bool
381
     */
382
    public function store($force = true)
383
    {
384
        $isNew = $this->isNew();
385
        if (!$this->helper->getHandler('Item')->insert($this, $force)) {
386
            return false;
387
        }
388
        if ($isNew && Constants::PUBLISHER_STATUS_PUBLISHED == $this->getVar('status')) {
389
            // Increment user posts
390
            $userHandler = \xoops_getHandler('user');
391
            /** @var \XoopsMemberHandler $memberHandler */
392
            $memberHandler = \xoops_getHandler('member');
393
            $poster        = $userHandler->get($this->uid());
394
            if (\is_object($poster) && !$poster->isNew()) {
395
                $poster->setVar('posts', $poster->getVar('posts') + 1);
396
                if (!$memberHandler->insertUser($poster, true)) {
397
                    $this->setErrors('Article created but could not increment user posts.');
398
399
                    return false;
400
                }
401
            }
402
        }
403
404
        return true;
405
    }
406
407
    /**
408
     * @return string
409
     */
410
    public function getCategoryName()
411
    {
412
        return $this->getCategory()->name();
413
    }
414
415
    /**
416
     * @return string
417
     */
418
    public function getCategoryUrl()
419
    {
420
        return $this->getCategory()->getCategoryUrl();
421
    }
422
423
    /**
424
     * @return string
425
     */
426
    public function getCategoryLink()
427
    {
428
        return $this->getCategory()->getCategoryLink();
429
    }
430
431
    /**
432
     * @param bool $withAllLink
433
     *
434
     * @return array|bool|string
435
     */
436
    public function getCategoryPath($withAllLink = true)
437
    {
438
        return $this->getCategory()->getCategoryPath($withAllLink);
439
    }
440
441
    /**
442
     * @return string
443
     */
444
    public function getCategoryImagePath()
445
    {
446
        return Utility::getImageDir('category', false) . $this->getCategory()->getImage();
447
    }
448
449
    /**
450
     * @return mixed
451
     */
452
    public function getFiles()
453
    {
454
        return $this->helper->getHandler('File')->getAllFiles($this->itemid(), Constants::PUBLISHER_STATUS_FILE_ACTIVE);
455
    }
456
457
    /**
458
     * @param $icons
459
     * @return string
460
     */
461
    public function getAdminLinks($icons)
462
    {
463
        $adminLinks = '';
464
        if (\is_object($GLOBALS['xoopsUser'])
465
            && (Utility::userIsAdmin() || Utility::userIsAuthor($this)
466
                || $this->helper->getHandler('Permission')->isGranted('item_submit', $this->categoryid()))) {
467
            if (Utility::userIsAdmin() || Utility::userIsAuthor($this) || Utility::userIsModerator($this)) {
468
                if ($this->helper->getConfig('perm_edit') || Utility::userIsModerator($this) || Utility::userIsAdmin()) {
469
                    // Edit button
470
                    $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?itemid=' . $this->itemid() . "'>" . $icons['edit'] . '</a>';
471
                    $adminLinks .= ' ';
472
                }
473
                if ($this->helper->getConfig('perm_delete') || Utility::userIsModerator($this) || Utility::userIsAdmin()) {
474
                    // Delete button
475
                    $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?op=del&amp;itemid=' . $this->itemid() . "'>" . $icons['delete'] . '</a>';
476
                    $adminLinks .= ' ';
477
                }
478
            }
479
            if ($this->helper->getConfig('perm_clone') || Utility::userIsModerator($this) || Utility::userIsAdmin()) {
480
                // Duplicate button
481
                $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?op=clone&amp;itemid=' . $this->itemid() . "'>" . $icons['clone'] . '</a>';
482
                $adminLinks .= ' ';
483
            }
484
        }
485
486
        return $adminLinks;
487
    }
488
489
    /**
490
     * @param $icons
491
     * @return string
492
     */
493
    public function getPdfButton($icons)
494
    {
495
        $pdfButton = '';
496
        // PDF button
497
        if (\is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) {
498
            $pdfButton .= "<a href='" . PUBLISHER_URL . '/makepdf.php?itemid=' . $this->itemid() . "' rel='nofollow' target='_blank'>" . $icons['pdf'] . '</a>&nbsp;';
499
            $pdfButton .= ' ';
500
        }
501
//        if (is_object($GLOBALS['xoopsUser']) && Utility::userIsAdmin()) {
502
//            $GLOBALS['xoTheme']->addStylesheet('/modules/system/css/jquery.jgrowl.min.css');
503
//            $GLOBALS['xoTheme']->addScript('browse.php?Frameworks/jquery/plugins/jquery.jgrowl.js');
504
//            $adminLinks .= '<script type="text/javascript">
505
//                            (function($){
506
//                                $(document).ready(function(){
507
//                                    $.jGrowl("' . _MD_PUBLISHER_ERROR_NO_PDF . '");});
508
//                                })(jQuery);
509
//                                </script>';
510
//        }
511
512
        return $pdfButton;
513
    }
514
515
    /**
516
     * @param $icons
517
     * @return string
518
     */
519
    public function getPrintLinks($icons)
520
    {
521
        $printLinks = '';
522
        // Print button
523
        $printLinks .= "<a href='" . Seo::generateUrl('print', $this->itemid(), $this->short_url()) . "' rel='nofollow' target='_blank'>" . $icons['print'] . '</a>&nbsp;';
524
        $printLinks .= ' ';
525
526
        return $printLinks;
527
    }
528
529
    /**
530
     * @param array $notifications
531
     */
532
    public function sendNotifications($notifications = []): void
533
    {
534
        /** @var \XoopsNotificationHandler $notificationHandler */
535
        $notificationHandler = \xoops_getHandler('notification');
536
        $tags                = [];
537
538
        $tags['MODULE_NAME']   = $this->helper->getModule()->getVar('name');
539
        $tags['ITEM_NAME']     = $this->getTitle();
540
        $tags['ITEM_SUBNAME']  = $this->getSubtitle();
541
        $tags['CATEGORY_NAME'] = $this->getCategoryName();
542
        $tags['CATEGORY_URL']  = PUBLISHER_URL . '/category.php?categoryid=' . $this->categoryid();
543
        $tags['ITEM_BODY']     = $this->body();
544
        $tags['DATESUB']       = $this->getDatesub();
545
        foreach ($notifications as $notification) {
546
            switch ($notification) {
547
                case Constants::PUBLISHER_NOTIFY_ITEM_PUBLISHED:
548
                    $tags['ITEM_URL'] = PUBLISHER_URL . '/item.php?itemid=' . $this->itemid();
549
                    $notificationHandler->triggerEvent('global_item', 0, 'published', $tags, [], $this->helper->getModule()->getVar('mid'));
550
                    $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'published', $tags, [], $this->helper->getModule()->getVar('mid'));
551
                    $notificationHandler->triggerEvent('item', $this->itemid(), 'approved', $tags, [], $this->helper->getModule()->getVar('mid'));
552
                    break;
553
                case Constants::PUBLISHER_NOTIFY_ITEM_SUBMITTED:
554
                    $tags['WAITINGFILES_URL'] = PUBLISHER_URL . '/admin/item.php?itemid=' . $this->itemid();
555
                    $notificationHandler->triggerEvent('global_item', 0, 'submitted', $tags, [], $this->helper->getModule()->getVar('mid'));
556
                    $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'submitted', $tags, [], $this->helper->getModule()->getVar('mid'));
557
                    break;
558
                case Constants::PUBLISHER_NOTIFY_ITEM_REJECTED:
559
                    $notificationHandler->triggerEvent('item', $this->itemid(), 'rejected', $tags, [], $this->helper->getModule()->getVar('mid'));
560
                    break;
561
                case -1:
562
                default:
563
                    break;
564
            }
565
        }
566
    }
567
568
    /**
569
     * Sets default permissions for this item
570
     */
571
    public function setDefaultPermissions(): void
572
    {
573
        $memberHandler = \xoops_getHandler('member');
574
        $groups        = $memberHandler->getGroupList();
575
        $groupIds      = \count($groups) > 0 ? \array_keys($groups) : [];
576
        /*
577
        $j             = 0;
578
        $groupIds      = [];
579
        foreach (array_keys($groups) as $i) {
580
            $groupIds[$j] = $i;
581
            ++$j;
582
        }
583
        */
584
        $this->groupsRead = $groupIds;
585
    }
586
587
    /**
588
     * @param $groupIds
589
     * @deprecated - NOT USED
590
     *
591
     * @todo       look at this
592
     */
593
    public function setPermissions($groupIds): void
594
    {
595
        if (!isset($groupIds)) {
596
            $this->setDefaultPermissions();
597
            /*
598
            $memberHandler = xoops_getHandler('member');
599
            $groups        = $memberHandler->getGroupList();
600
            $j             = 0;
601
            $groupIds      = [];
602
            foreach (array_keys($groups) as $i) {
603
                $groupIds[$j] = $i;
604
                ++$j;
605
            }
606
            */
607
        }
608
    }
609
610
    /**
611
     * @return bool
612
     */
613
    public function notLoaded()
614
    {
615
        return -1 == $this->getVar('itemid');
616
    }
617
618
    /**
619
     * @return string
620
     */
621
    public function getItemUrl()
622
    {
623
        return Seo::generateUrl('item', $this->itemid(), $this->short_url());
624
    }
625
626
    /**
627
     * @param bool $class
628
     * @param int  $maxsize
629
     *
630
     * @return string
631
     */
632
    public function getItemLink($class = false, $maxsize = 0)
633
    {
634
        if ($class) {
635
            return '<a class="' . $class . '" href="' . $this->getItemUrl() . '">' . $this->getTitle($maxsize) . '</a>';
636
        }
637
638
        return '<a href="' . $this->getItemUrl() . '">' . $this->getTitle($maxsize) . '</a>';
639
    }
640
641
    /**
642
     * @return string
643
     */
644
    public function getWhoAndWhen()
645
    {
646
        $posterName = $this->getLinkedPosterName();
647
        $postdate   = $this->getDatesub();
648
649
        return \sprintf(\_CO_PUBLISHER_POSTEDBY, $posterName, $postdate);
650
    }
651
652
    /**
653
     * @return string
654
     */
655
    public function getWho()
656
    {
657
        $posterName = $this->getLinkedPosterName();
658
659
        return $posterName;
660
    }
661
662
    /**
663
     * @return string
664
     */
665
    public function getWhen()
666
    {
667
        $postdate = $this->getDatesub();
668
669
        return $postdate;
670
    }
671
672
    /**
673
     * @param null|string $body
674
     *
675
     * @return string
676
     */
677
    public function plainMaintext($body = null)
678
    {
679
        $ret = '';
680
        if (!$body) {
681
            $body = $this->body();
682
        }
683
        $ret .= \str_replace('[pagebreak]', '<br><br>', $body);
684
685
        return $ret;
686
    }
687
688
    /**
689
     * @param int         $itemPageId
690
     * @param null|string $body
691
     *
692
     * @return string
693
     */
694
    public function buildMainText($itemPageId = -1, $body = null)
695
    {
696
        if (null === $body) {
697
            $body = $this->body();
698
        }
699
        $bodyParts = \explode('[pagebreak]', $body);
700
        $this->setVar('pagescount', \count($bodyParts));
701
        if (\count($bodyParts) <= 1) {
702
            return $this->plainMaintext($body);
703
        }
704
        $ret = '';
705
        if (-1 == $itemPageId) {
706
            $ret .= \trim($bodyParts[0]);
707
708
            return $ret;
709
        }
710
        if ($itemPageId >= \count($bodyParts)) {
711
            $itemPageId = \count($bodyParts) - 1;
712
        }
713
        $ret .= \trim($bodyParts[$itemPageId]);
714
715
        return $ret;
716
    }
717
718
    /**
719
     * @return mixed
720
     */
721
    public function getImages()
722
    {
723
        static $ret;
724
        $itemId = $this->getVar('itemid');
725
        if (!isset($ret[$itemId])) {
726
            $ret[$itemId]['main']   = '';
727
            $ret[$itemId]['others'] = [];
728
            $imagesIds              = [];
729
            $image                  = $this->getVar('image');
730
            $images                 = $this->getVar('images');
731
            if ('' != $images) {
732
                $imagesIds = \explode('|', $images);
733
            }
734
            if ($image > 0) {
735
                $imagesIds[] = $image;
736
            }
737
            $imageObjs = [];
738
            if (\count($imagesIds) > 0) {
739
                $imageHandler = \xoops_getHandler('image');
740
                $criteria     = new \CriteriaCompo(new \Criteria('image_id', '(' . \implode(',', $imagesIds) . ')', 'IN'));
741
                $imageObjs    = $imageHandler->getObjects($criteria, true);
742
                unset($criteria);
743
            }
744
            foreach ($imageObjs as $id => $imageObj) {
745
                if ($id == $image) {
746
                    $ret[$itemId]['main'] = $imageObj;
747
                } else {
748
                    $ret[$itemId]['others'][] = $imageObj;
749
                }
750
                unset($imageObj);
751
            }
752
            unset($imageObjs);
753
        }
754
755
        return $ret[$itemId];
756
    }
757
758
    /**
759
     * @param string $display
760
     * @param int    $maxCharTitle
761
     * @param int    $maxCharSummary
762
     * @param bool   $fullSummary
763
     *
764
     * @return array
765
     */
766
    public function toArraySimple($display = 'default', $maxCharTitle = 0, $maxCharSummary = 300, $fullSummary = false)
767
    {
768
        $itemPageId = -1;
769
        if (\is_numeric($display)) {
770
            $itemPageId = $display;
771
            $display    = 'all';
772
        }
773
        $item['itemid']       = $this->itemid();
774
        $item['uid']          = $this->uid();
775
        $item['itemurl']      = $this->getItemUrl();
776
        $item['titlelink']    = $this->getItemLink('titlelink', $maxCharTitle);
777
        $item['subtitle']     = $this->subtitle();
778
        $item['datesub']      = $this->getDatesub();
779
        $item['dateexpire']   = $this->getDateExpire();
780
        $item['counter']      = $this->counter();
781
        $item['hits']         = '&nbsp;' . $this->counter() . ' ' . _READS . '';
782
        $item['who']          = $this->getWho();
783
        $item['when']         = $this->getWhen();
784
        $item['category']     = $this->getCategoryName();
785
        $item['categorylink'] = $this->getCategoryLink();
786
        $item['cancomment']   = $this->cancomment();
787
        $item['votetype']     = $this->votetype();
788
        $comments             = $this->comments();
789
        if ($comments > 0) {
790
            //shows 1 comment instead of 1 comm. if comments ==1
791
            //langugage file modified accordingly
792
            if (1 == $comments) {
793
                $item['comments'] = '&nbsp;' . \_MD_PUBLISHER_ONECOMMENT . '&nbsp;';
794
            } else {
795
                $item['comments'] = '&nbsp;' . $comments . '&nbsp;' . \_MD_PUBLISHER_COMMENTS . '&nbsp;';
796
            }
797
        } else {
798
            $item['comments'] = '&nbsp;' . \_MD_PUBLISHER_NO_COMMENTS . '&nbsp;';
799
        }
800
        $item = $this->getMainImage($item);
801
        switch ($display) {
802
            case 'summary':
803
                $item = $this->toArrayFull($item);
804
                $item = $this->toArrayAll($item, $itemPageId);
805
            // no break
806
            case 'list':
807
                $item = $this->toArrayFull($item);
808
                $item = $this->toArrayAll($item, $itemPageId);
809
            //break;
810
            // no break
811
            case 'full':
812
                $item = $this->toArrayFull($item);
813
                $item = $this->toArrayAll($item, $itemPageId);
814
            // no break
815
            case 'wfsection':
816
                $item = $this->toArrayFull($item);
817
                $item = $this->toArrayAll($item, $itemPageId);
818
            // no break
819
            case 'default':
820
                $item    = $this->toArrayFull($item);
821
                $item    = $this->toArrayAll($item, $itemPageId);
822
                $summary = $this->getSummary($maxCharSummary);
823
                if (!$summary) {
824
                    $summary = $this->getBody($maxCharSummary);
825
                }
826
                $item['summary']   = $summary;
827
                $item['truncated'] = $maxCharSummary > 0 && \mb_strlen($summary) > $maxCharSummary;
828
                $item              = $this->toArrayFull($item);
829
                break;
830
            case 'all':
831
                $item = $this->toArrayFull($item);
832
                $item = $this->toArrayAll($item, $itemPageId);
833
                break;
834
        }
835
        // Highlighting searched words
836
        $highlight = true;
837
        if ($highlight && Request::getString('keywords', '', 'GET')) {
838
            $keywords = \htmlspecialchars(\trim(\urldecode(Request::getString('keywords', '', 'GET'))), \ENT_QUOTES | \ENT_HTML5);
839
            $fields   = ['title', 'maintext', 'summary'];
840
            foreach ($fields as $field) {
841
                if (isset($item[$field])) {
842
                    $item[$field] = $this->highlight($item[$field], $keywords);
843
                }
844
            }
845
        }
846
847
        return $item;
848
    }
849
850
    /**
851
     * @param array $item
852
     *
853
     * @return array
854
     */
855
    public function toArrayFull($item)
856
    {
857
        $configurator = new Common\Configurator();
858
        $icons        = $configurator->icons;
859
860
        $item['title']       = $this->getTitle();
861
        $item['clean_title'] = $this->getTitle();
862
        $item['itemurl']     = $this->getItemUrl();
863
864
        $item['adminlink']    = $this->getAdminLinks($icons);
865
        $item['pdfbutton']    = $this->getPdfButton($icons);
866
        $item['printlink']    = $this->getPrintLinks($icons);
867
        $item['categoryPath'] = $this->getCategoryPath($this->helper->getConfig('format_linked_path'));
868
        $item['who_when']     = $this->getWhoAndWhen();
869
        $item['who']          = $this->getWho();
870
        $item['when']         = $this->getWhen();
871
        $item['category']     = $this->getCategoryName();
872
        $item['body']         = $this->getBody();
873
        $item['more']         = $this->getItemUrl();
874
        $item                 = $this->getMainImage($item);
875
876
        return $item;
877
    }
878
879
    /**
880
     * @param array $item
881
     * @param int   $itemPageId
882
     *
883
     * @return array
884
     */
885
    public function toArrayAll($item, $itemPageId)
886
    {
887
        $item['maintext'] = $this->buildMainText($itemPageId, $this->getBody());
888
        $item             = $this->getOtherImages($item);
889
890
        return $item;
891
    }
892
893
    /**
894
     * @param array $item
895
     *
896
     * @return array
897
     */
898
    public function getMainImage($item = [])
899
    {
900
        $images             = $this->getImages();
901
        $item['image_path'] = '';
902
        $item['image_name'] = '';
903
        if (\is_object($images['main'])) {
904
            $dimensions           = \getimagesize($GLOBALS['xoops']->path('uploads/' . $images['main']->getVar('image_name')));
905
            $item['image_width']  = $dimensions[0];
906
            $item['image_height'] = $dimensions[1];
907
            $item['image_path']   = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name');
908
            // check to see if GD function exist
909
            if (\function_exists('imagecreatetruecolor')) {
910
                $item['image_thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name') . '&amp;h=180';
911
            } else {
912
                $item['image_thumb'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name');
913
            }
914
            $item['image_name'] = $images['main']->getVar('image_nicename');
915
        }
916
917
        return $item;
918
    }
919
920
    /**
921
     * @param array $item
922
     *
923
     * @return array
924
     */
925
    public function getOtherImages($item = [])
926
    {
927
        $images         = $this->getImages();
928
        $item['images'] = [];
929
        $i              = 0;
930
        foreach ($images['others'] as $image) {
931
            $dimensions                   = \getimagesize($GLOBALS['xoops']->path('uploads/' . $image->getVar('image_name')));
932
            $item['images'][$i]['width']  = $dimensions[0];
933
            $item['images'][$i]['height'] = $dimensions[1];
934
            $item['images'][$i]['path']   = XOOPS_URL . '/uploads/' . $image->getVar('image_name');
935
            // check to see if GD function exist
936
            if (\function_exists('imagecreatetruecolor')) {
937
                $item['images'][$i]['thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $image->getVar('image_name') . '&amp;w=240';
938
            } else {
939
                $item['images'][$i]['thumb'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name');
940
            }
941
            $item['images'][$i]['name'] = $image->getVar('image_nicename');
942
            ++$i;
943
        }
944
945
        return $item;
946
    }
947
948
    /**
949
     * @param string       $content
950
     * @param string|array $keywords
951
     *
952
     * @return string Text
953
     */
954
    public function highlight($content, $keywords)
955
    {
956
        $color = $this->helper->getConfig('format_highlight_color');
957
        if (0 !== \mb_strpos($color, '#')) {
958
            $color = '#' . $color;
959
        }
960
        require_once __DIR__ . '/Highlighter.php';
961
        $highlighter = new Highlighter();
962
        $highlighter->setReplacementString('<span style="font-weight: bolder; background-color: ' . $color . ';">\1</span>');
963
964
        return $highlighter->highlight($content, $keywords);
965
    }
966
967
    /**
968
     *  Create metada and assign it to template
969
     */
970
    public function createMetaTags(): void
971
    {
972
        $publisherMetagen = new Metagen($this->getTitle(), $this->meta_keywords(), $this->meta_description(), $this->category->categoryPath);
973
        $publisherMetagen->createMetaTags();
974
    }
975
976
    /**
977
     * @param string $str
978
     *
979
     * @return string
980
     */
981
    protected function convertForJapanese($str)
982
    {
983
        // no action, if not flag
984
        if (!\defined('_PUBLISHER_FLAG_JP_CONVERT')) {
985
            return $str;
986
        }
987
        // no action, if not Japanese
988
        if ('japanese' !== $GLOBALS['xoopsConfig']['language']) {
989
            return $str;
990
        }
991
        // presume OS Browser
992
        $agent   = Request::getString('HTTP_USER_AGENT', '', 'SERVER');
993
        $os      = '';
994
        $browser = '';
995
        //        if (preg_match("/Win/i", $agent)) {
996
        if (false !== \mb_stripos($agent, 'Win')) {
997
            $os = 'win';
998
        }
999
        //        if (preg_match("/MSIE/i", $agent)) {
1000
        if (false !== \mb_stripos($agent, 'MSIE')) {
1001
            $browser = 'msie';
1002
        }
1003
        // if msie
1004
        if (('win' === $os) && ('msie' === $browser)) {
1005
            // if multibyte
1006
            if (\function_exists('mb_convert_encoding')) {
1007
                $str = \mb_convert_encoding($str, 'SJIS', 'EUC-JP');
1008
                $str = \rawurlencode($str);
1009
            }
1010
        }
1011
1012
        return $str;
1013
    }
1014
1015
    /**
1016
     * @param string $title
1017
     * @param bool   $checkperm
1018
     *
1019
     * @return Form\ItemForm
1020
     */
1021
    public function getForm($title = 'default', $checkperm = true)
1022
    {
1023
        //        require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/item.php');
1024
        $form = new Form\ItemForm($title, 'form', \xoops_getenv('SCRIPT_NAME'), 'post', true);
1025
        $form->setCheckPermissions($checkperm);
1026
        $form->createElements($this);
1027
1028
        return $form;
1029
    }
1030
1031
    /**
1032
     * Checks if a user has access to a selected item. if no item permissions are
1033
     * set, access permission is denied. The user needs to have necessary category
1034
     * permission as well.
1035
     * Also, the item needs to be Published
1036
     *
1037
     * @return bool : TRUE if the no errors occured
1038
     */
1039
    public function accessGranted()
1040
    {
1041
        if (Utility::userIsAdmin()) {
1042
            return true;
1043
        }
1044
        if (Constants::PUBLISHER_STATUS_PUBLISHED != $this->getVar('status')) {
1045
            return false;
1046
        }
1047
        // Do we have access to the parent category
1048
        if ($this->helper->getHandler('Permission')->isGranted('category_read', $this->categoryid())) {
1049
            return true;
1050
        }
1051
1052
        return false;
1053
    }
1054
1055
    /**
1056
     * The name says it all
1057
     */
1058
    public function setVarsFromRequest(): void
1059
    {
1060
        //Required fields
1061
        //        if (!empty($categoryid = Request::getInt('categoryid', 0, 'POST'))) {
1062
        //            $this->setVar('categoryid', $categoryid);}
1063
        if (\is_object($GLOBALS['xoopsUser'])) {
1064
            $userTimeoffset = $GLOBALS['xoopsUser']->getVar('timezone_offset');
1065
        } else {
1066
            $userTimeoffset = null;
1067
        }
1068
        $this->setVar('categoryid', Request::getInt('categoryid', 0, 'POST'));
1069
        $this->setVar('title', Request::getString('title', '', 'POST'));
1070
        $this->setVar('body', Request::getText('body', '', 'POST'));
1071
1072
        if ('' !== ($imageFeatured = Request::getString('image_featured', '', 'POST'))) {
1073
            $imageItem = Request::getArray('image_item', [], 'POST');
1074
            //            $imageFeatured = Request::getString('image_featured', '', 'POST');
1075
            //Todo: get a better image class for xoops!
1076
            //Image hack
1077
            $imageItemIds = [];
1078
1079
            $sql    = 'SELECT image_id, image_name FROM ' . $GLOBALS['xoopsDB']->prefix('image');
1080
            $result = $GLOBALS['xoopsDB']->query($sql, 0, 0);
1081
            while (false !== ($myrow = $GLOBALS['xoopsDB']->fetchArray($result))) {
1082
                $imageName = $myrow['image_name'];
1083
                $id        = $myrow['image_id'];
1084
                if ($imageName == $imageFeatured) {
1085
                    $this->setVar('image', $id);
1086
                }
1087
                if (\in_array($imageName, $imageItem, true)) {
1088
                    $imageItemIds[] = $id;
1089
                }
1090
            }
1091
            $this->setVar('images', \implode('|', $imageItemIds));
1092
        } else {
1093
            $this->setVar('image', 0);
1094
            $this->setVar('images', '');
1095
        }
1096
1097
        if (false !== ($authorAlias = Request::getString('author_alias', '', 'POST'))) {
1098
            $this->setVar('author_alias', $authorAlias);
1099
            if ('' !== $this->getVar('author_alias')) {
1100
                $this->setVar('uid', 0);
1101
            }
1102
        }
1103
1104
        //mb TODO check on version
1105
        //check if date is set and convert it to GMT date
1106
        //        if (($datesub = Request::getString('datesub', '', 'POST'))) {
1107
        if ('' !== Request::getString('datesub', '', 'POST')) {
1108
            //            if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
1109
            //                $this->setVar('datesub', strtotime(Request::getArray('datesub', array(), 'POST')['date']) + Request::getArray('datesub', array(), 'POST')['time']);
1110
            //            } else {
1111
            $resDate     = Request::getArray('datesub', [], 'POST');
1112
            $resTime     = Request::getArray('datesub', [], 'POST');
1113
            $dateTimeObj = \DateTime::createFromFormat(_SHORTDATESTRING, $resDate['date']);
1114
            $dateTimeObj->setTime(0, 0, (int)$resTime['time']);
1115
            $serverTimestamp = \userTimeToServerTime($dateTimeObj->getTimestamp(), $userTimeoffset);
1116
            $this->setVar('datesub', $serverTimestamp);
1117
            //            }
1118
        } elseif ($this->isNew()) {
1119
            $this->setVar('datesub', \time());
1120
        }
1121
1122
        // date expire
1123
        if (0 !== Request::getInt('use_expire_yn', 0, 'POST')) {
1124
            if ('' !== Request::getString('dateexpire', '', 'POST')) {
1125
                $resExDate   = Request::getArray('dateexpire', [], 'POST');
1126
                $resExTime   = Request::getArray('dateexpire', [], 'POST');
1127
                $dateTimeObj = \DateTime::createFromFormat(_SHORTDATESTRING, $resExDate['date']);
1128
                $dateTimeObj->setTime(0, 0, (int)$resExTime['time']);
1129
                $serverTimestamp = \userTimeToServerTime($dateTimeObj->getTimestamp(), $userTimeoffset);
1130
                $this->setVar('dateexpire', $serverTimestamp);
1131
            }
1132
        } else {
1133
            $this->setVar('dateexpire', 0);
1134
        }
1135
1136
        if ($this->isNew()) {
1137
            $this->setVar('uid', Request::getInt('uid', (\is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0), 'POST'));
1138
            $this->setVar('cancoment', Request::getInt('allowcomments', $this->helper->getConfig('submit_allowcomments'), 'POST'));
1139
            $this->setVar('status', Request::getInt('status', $this->helper->getConfig('submit_status'), 'POST'));
1140
            $this->setVar('dohtml', Request::getInt('dohtml', $this->helper->getConfig('submit_dohtml'), 'POST'));
1141
            $this->setVar('dosmiley', Request::getInt('dosmiley', $this->helper->getConfig('submit_dosmiley'), 'POST'));
1142
            $this->setVar('doxcode', Request::getInt('doxcode', $this->helper->getConfig('submit_doxcode'), 'POST'));
1143
            $this->setVar('doimage', Request::getInt('doimage', $this->helper->getConfig('submit_doimage'), 'POST'));
1144
            $this->setVar('dobr', Request::getInt('dolinebreak', $this->helper->getConfig('submit_dobr'), 'POST'));
1145
            $this->setVar('votetype', Request::getInt('votetype', $this->helper->getConfig('ratingbars'), 'POST'));
1146
            $this->setVar('short_url', Request::getString('item_short_url', '', 'POST'));
1147
            $this->setVar('meta_keywords', Request::getString('item_meta_keywords', '', 'POST'));
1148
            $this->setVar('meta_description', Request::getString('item_meta_description', '', 'POST'));
1149
            $this->setVar('weight', Request::getInt('weight', 0, 'POST'));
1150
            //Not required fields
1151
            $this->setVar('summary', Request::getText('summary', '', 'POST'));
1152
            $this->setVar('subtitle', Request::getString('subtitle', '', 'POST'));
1153
            $this->setVar('item_tag', Request::getString('item_tag', '', 'POST'));
1154
1155
            $this->setVar('notifypub', Request::getString('notify', 1, 'POST'));
1156
        } else {
1157
            $this->setVar('uid', Request::getInt('uid', null, 'POST'));
1158
            $this->setVar('cancomment', Request::getInt('allowcomments', null, 'POST'));
1159
            $this->setVar('status', Request::getInt('status', $this->helper->getConfig('submit_edit_status'), 'POST'));
1160
            $this->setVar('dohtml', Request::getInt('dohtml', null, 'POST'));
1161
            $this->setVar('dosmiley', Request::getInt('dosmiley', null, 'POST'));
1162
            $this->setVar('doxcode', Request::getInt('doxcode', null, 'POST'));
1163
            $this->setVar('doimage', Request::getInt('doimage', null, 'POST'));
1164
            $this->setVar('dobr', Request::getInt('dolinebreak', null, 'POST'));
1165
            $this->setVar('votetype', Request::getInt('votetype', null, 'POST'));
1166
            $this->setVar('short_url', Request::getString('item_short_url', $this->getVar('short_url'), 'POST'));
0 ignored issues
show
It seems like $this->getVar('short_url') can also be of type array and array; however, parameter $default of Xmf\Request::getString() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1166
            $this->setVar('short_url', Request::getString('item_short_url', /** @scrutinizer ignore-type */ $this->getVar('short_url'), 'POST'));
Loading history...
1167
            $this->setVar('meta_keywords', Request::getString('item_meta_keywords', $this->getVar('meta_keywords'), 'POST'));
1168
            $this->setVar('meta_description', Request::getString('item_meta_description', $this->getVar('meta_description'), 'POST'));
1169
            $this->setVar('weight', Request::getInt('weight', null, 'POST'));
1170
            //Not required fields
1171
            if (null !== Request::getVar('summary', null, 'POST')) {
1172
                $this->setVar('summary', Request::getText('summary', '', 'POST'));
1173
            }
1174
            $this->setVar('subtitle', Request::getString('subtitle', $this->getVar('subtitle'), 'POST'));
1175
            $this->setVar('item_tag', Request::getString('item_tag', $this->getVar('item_tag'), 'POST'));
1176
            $this->setVar('notifypub', Request::getString('notify', $this->getVar('notifypub'), 'POST'));
1177
        }
1178
    }
1179
1180
    public function assignOtherProperties(): void
1181
    {
1182
        $module    = $this->helper->getModule();
1183
        $module_id = $module->getVar('mid');
1184
        /** @var \XoopsGroupPermHandler $grouppermHandler */
1185
        $grouppermHandler = \xoops_getHandler('groupperm');
1186
1187
        $this->category    = $this->helper->getHandler('Category')->get($this->getVar('categoryid'));
1188
        $this->groups_read = $grouppermHandler->getGroupIds('item_read', $this->itemid(), $module_id);
1189
    }
1190
}
1191