Passed
Branch master (7e303a)
by Michael
02:15
created

class/Item.php (6 issues)

Labels
1
<?php
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 http://sourceforge.net/projects/xuups/
17
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @package         Publisher
19
 * @since           1.0
20
 * @author          trabis <[email protected]>
21
 * @author          The SmartFactory <www.smartfactory.ca>
22
 */
23
24
use Xmf\Request;
25
use XoopsModules\Publisher;
26
27
//namespace Publisher;
28
29
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
30
require_once dirname(__DIR__) . '/include/common.php';
31
32
/**
33
 * Class Item
34
 */
35
class Item extends \XoopsObject
36
{
37
    /**
38
     * @var Publisher\Helper
39
     */
40
    public $helper;
41
    public $groupsRead = [];
42
43
    /**
44
     * @var Publisher\Category
45
     */
46
    public $category;
47
48
    /**
49
     * @param int|null $id
50
     */
51
    public function __construct($id = null)
52
    {
53
        /** @var Publisher\Helper $this->helper */
54
        $this->helper = Publisher\Helper::getInstance();
55
        $this->db     = \XoopsDatabaseFactory::getDatabaseConnection();
56
        $this->initVar('itemid', XOBJ_DTYPE_INT, 0);
57
        $this->initVar('categoryid', XOBJ_DTYPE_INT, 0, false);
58
        $this->initVar('title', XOBJ_DTYPE_TXTBOX, '', true, 255);
59
        $this->initVar('subtitle', XOBJ_DTYPE_TXTBOX, '', false, 255);
60
        $this->initVar('summary', XOBJ_DTYPE_TXTAREA, '', false);
61
        $this->initVar('body', XOBJ_DTYPE_TXTAREA, '', false);
62
        $this->initVar('uid', XOBJ_DTYPE_INT, 0, false);
63
        $this->initVar('author_alias', XOBJ_DTYPE_TXTBOX, '', false, 255);
64
        $this->initVar('datesub', 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
        // Non consistent values
85
        $this->initVar('pagescount', XOBJ_DTYPE_INT, 0, false);
86
        if (null !== $id) {
87
            $item = $this->helper->getHandler('Item')->get($id);
88
            foreach ($item->vars as $k => $v) {
89
                $this->assignVar($k, $v['value']);
90
            }
91
        }
92
    }
93
94
    /**
95
     * @param string $method
96
     * @param array  $args
97
     *
98
     * @return mixed
99
     */
100
    public function __call($method, $args)
101
    {
102
        $arg = isset($args[0]) ? $args[0] : null;
103
104
        return $this->getVar($method, $arg);
105
    }
106
107
    /**
108
     * @return null|Publisher\Category
109
     */
110
    public function getCategory()
111
    {
112
        if (null === $this->category) {
113
            $this->category = $this->helper->getHandler('Category')->get($this->getVar('categoryid'));
114
        }
115
116
        return $this->category;
117
    }
118
119
    /**
120
     * @param int    $maxLength
121
     * @param string $format
122
     *
123
     * @return mixed|string
124
     */
125
    public function getTitle($maxLength = 0, $format = 'S')
126
    {
127
        $ret = $this->getVar('title', $format);
128
        if (0 != $maxLength) {
129
            if (!XOOPS_USE_MULTIBYTES) {
130
                if (mb_strlen($ret) >= $maxLength) {
0 ignored issues
show
It seems like $ret can also be of type array and array; however, parameter $str of mb_strlen() 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

130
                if (mb_strlen(/** @scrutinizer ignore-type */ $ret) >= $maxLength) {
Loading history...
131
                    $ret = Publisher\Utility::substr($ret, 0, $maxLength);
0 ignored issues
show
The method substr() does not exist on XoopsModules\Publisher\Utility. Did you maybe mean mb_substr()? ( Ignorable by Annotation )

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

131
                    /** @scrutinizer ignore-call */ 
132
                    $ret = Publisher\Utility::substr($ret, 0, $maxLength);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
132
                }
133
            }
134
        }
135
136
        return $ret;
137
    }
138
139
    /**
140
     * @param int    $maxLength
141
     * @param string $format
142
     *
143
     * @return mixed|string
144
     */
145
    public function getSubtitle($maxLength = 0, $format = 'S')
146
    {
147
        $ret = $this->getVar('subtitle', $format);
148
        if (0 != $maxLength) {
149
            if (!XOOPS_USE_MULTIBYTES) {
150
                if (mb_strlen($ret) >= $maxLength) {
0 ignored issues
show
It seems like $ret can also be of type array and array; however, parameter $str of mb_strlen() 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

150
                if (mb_strlen(/** @scrutinizer ignore-type */ $ret) >= $maxLength) {
Loading history...
151
                    $ret = Publisher\Utility::substr($ret, 0, $maxLength);
152
                }
153
            }
154
        }
155
156
        return $ret;
157
    }
158
159
    /**
160
     * @param int    $maxLength
161
     * @param string $format
162
     * @param string $stripTags
163
     *
164
     * @return mixed|string
165
     */
166
    public function getSummary($maxLength = 0, $format = 'S', $stripTags = '')
167
    {
168
        $ret = $this->getVar('summary', $format);
169
        if (!empty($stripTags)) {
170
            $ret = strip_tags($ret, $stripTags);
171
        }
172
        if (0 != $maxLength) {
173
            if (!XOOPS_USE_MULTIBYTES) {
174
                if (mb_strlen($ret) >= $maxLength) {
175
                    //$ret = Publisher\Utility::substr($ret , 0, $maxLength);
176
                    //                    $ret = Publisher\Utility::truncateTagSafe($ret, $maxLength, $etc = '...', $breakWords = false);
177
                    $ret = Publisher\Utility::truncateHtml($ret, $maxLength, $etc = '...', $breakWords = false);
178
                }
179
            }
180
        }
181
182
        return $ret;
183
    }
184
185
    /**
186
     * @param int  $maxLength
187
     * @param bool $fullSummary
188
     *
189
     * @return mixed|string
190
     */
191
    public function getBlockSummary($maxLength = 0, $fullSummary = false)
192
    {
193
        if ($fullSummary) {
194
            $ret = $this->getSummary(0, 's', '<br><br>');
195
        } else {
196
            $ret = $this->getSummary($maxLength, 's', '<br><br>');
197
        }
198
        //no summary? get body!
199
        if ('' === $ret) {
200
            $ret = $this->getBody($maxLength, 's', '<br><br>');
201
        }
202
203
        return $ret;
204
    }
205
206
    /**
207
     * @param string $fileName
208
     *
209
     * @return string
210
     */
211
    public function wrapPage($fileName)
212
    {
213
        $content = '';
214
        $page    = Publisher\Utility::getUploadDir(true, 'content') . $fileName;
215
        if (file_exists($page)) {
216
            // this page uses smarty template
217
            ob_start();
218
            require $page;
219
            $content = ob_get_contents();
220
            ob_end_clean();
221
            // Cleaning the content
222
            $bodyStartPos = mb_strpos($content, '<body>');
223
            if ($bodyStartPos) {
224
                $bodyEndPos = mb_strpos($content, '</body>', $bodyStartPos);
225
                $content    = mb_substr($content, $bodyStartPos + mb_strlen('<body>'), $bodyEndPos - mb_strlen('<body>') - $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, '[pagewrap=');
0 ignored issues
show
It seems like $ret can also be of type array and array; however, parameter $haystack of mb_strpos() 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

249
        $wrapPos = mb_strpos(/** @scrutinizer ignore-type */ $ret, '[pagewrap=');
Loading history...
250
        if (!(false === $wrapPos)) {
251
            $wrapPages      = [];
252
            $wrapCodeLength = mb_strlen('[pagewrap=');
253
            while (!(false === $wrapPos)) {
254
                $endWrapPos = mb_strpos($ret, ']', $wrapPos);
255
                if ($endWrapPos) {
256
                    $wrap_page_name = mb_substr($ret, $wrapPos + $wrapCodeLength, $endWrapPos - $wrapCodeLength - $wrapPos);
0 ignored issues
show
It seems like $ret can also be of type array and array; however, parameter $str of mb_substr() 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

256
                    $wrap_page_name = mb_substr(/** @scrutinizer ignore-type */ $ret, $wrapPos + $wrapCodeLength, $endWrapPos - $wrapCodeLength - $wrapPos);
Loading history...
257
                    $wrapPages[]    = $wrap_page_name;
258
                }
259
                $wrapPos = mb_strpos($ret, '[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 = Publisher\Utility::substr($ret , 0, $maxLength);
279
                    $ret = Publisher\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 int $realName
304
     *
305
     * @return string
306
     */
307
    public function posterName($realName = -1)
308
    {
309
        xoops_load('XoopsUserUtility');
310
        if (-1 == $realName) {
311
            $realName = $this->helper->getConfig('format_realname');
312
        }
313
        $ret = $this->author_alias();
314
        if ('' == $ret) {
315
            $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $realName);
316
        }
317
318
        return $ret;
319
    }
320
321
    /**
322
     * @return string
323
     */
324
    public function posterAvatar()
325
    {
326
        $ret           = 'blank.gif';
327
        $memberHandler = xoops_getHandler('member');
328
        $thisUser      = $memberHandler->getUser($this->uid());
329
        if (is_object($thisUser)) {
330
            $ret = $thisUser->getVar('user_avatar');
331
        }
332
333
        return $ret;
334
    }
335
336
    /**
337
     * @return string
338
     */
339
    public function getLinkedPosterName()
340
    {
341
        xoops_load('XoopsUserUtility');
342
        $ret = $this->author_alias();
343
        if ('' === $ret) {
344
            $ret = \XoopsUserUtility::getUnameFromId($this->uid(), $this->helper->getConfig('format_realname'), true);
345
        }
346
347
        return $ret;
348
    }
349
350
    /**
351
     * @return mixed
352
     */
353
    public function updateCounter()
354
    {
355
        return $this->helper->getHandler('Item')->updateCounter($this->itemid());
356
    }
357
358
    /**
359
     * @param bool $force
360
     *
361
     * @return bool
362
     */
363
    public function store($force = true)
364
    {
365
        $isNew = $this->isNew();
366
        if (!$this->helper->getHandler('Item')->insert($this, $force)) {
367
            return false;
368
        }
369
        if ($isNew && Constants::PUBLISHER_STATUS_PUBLISHED == $this->status()) {
0 ignored issues
show
The method status() does not exist on XoopsModules\Publisher\Item. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

369
        if ($isNew && Constants::PUBLISHER_STATUS_PUBLISHED == $this->/** @scrutinizer ignore-call */ status()) {
Loading history...
370
            // Increment user posts
371
            $userHandler   = xoops_getHandler('user');
372
            $memberHandler = xoops_getHandler('member');
373
            $poster        = $userHandler->get($this->uid());
374
            if (is_object($poster) && !$poster->isNew()) {
375
                $poster->setVar('posts', $poster->getVar('posts') + 1);
376
                if (!$memberHandler->insertUser($poster, true)) {
377
                    $this->setErrors('Article created but could not increment user posts.');
378
379
                    return false;
380
                }
381
            }
382
        }
383
384
        return true;
385
    }
386
387
    /**
388
     * @return string
389
     */
390
    public function getCategoryName()
391
    {
392
        return $this->getCategory()->name();
393
    }
394
395
    /**
396
     * @return string
397
     */
398
    public function getCategoryUrl()
399
    {
400
        return $this->getCategory()->getCategoryUrl();
401
    }
402
403
    /**
404
     * @return string
405
     */
406
    public function getCategoryLink()
407
    {
408
        return $this->getCategory()->getCategoryLink();
409
    }
410
411
    /**
412
     * @param bool $withAllLink
413
     *
414
     * @return string
415
     */
416
    public function getCategoryPath($withAllLink = true)
417
    {
418
        return $this->getCategory()->getCategoryPath($withAllLink);
419
    }
420
421
    /**
422
     * @return string
423
     */
424
    public function getCategoryImagePath()
425
    {
426
        return Publisher\Utility::getImageDir('category', false) . $this->getCategory()->getImage();
427
    }
428
429
    /**
430
     * @return mixed
431
     */
432
    public function getFiles()
433
    {
434
        return $this->helper->getHandler('File')->getAllFiles($this->itemid(), Constants::PUBLISHER_STATUS_FILE_ACTIVE);
435
    }
436
437
    /**
438
     * @return string
439
     */
440
    public function getAdminLinks()
441
    {
442
        $adminLinks = '';
443
        if (is_object($GLOBALS['xoopsUser'])
444
            && (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this)
445
                || $this->helper->getHandler('Permission')->isGranted('item_submit', $this->categoryid()))) {
446
            if (Publisher\Utility::userIsAdmin() || Publisher\Utility::userIsAuthor($this) || Publisher\Utility::userIsModerator($this)) {
447
                if ($this->helper->getConfig('perm_edit') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) {
448
                    // Edit button
449
                    $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?itemid=' . $this->itemid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/edit.gif'" . " title='" . _CO_PUBLISHER_EDIT . "' alt='" . _CO_PUBLISHER_EDIT . "'></a>";
450
                    $adminLinks .= ' ';
451
                }
452
                if ($this->helper->getConfig('perm_delete') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) {
453
                    // Delete button
454
                    $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?op=del&amp;itemid=' . $this->itemid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/delete.png'" . " title='" . _CO_PUBLISHER_DELETE . "' alt='" . _CO_PUBLISHER_DELETE . "'></a>";
455
                    $adminLinks .= ' ';
456
                }
457
            }
458
            if ($this->helper->getConfig('perm_clone') || Publisher\Utility::userIsModerator($this) || Publisher\Utility::userIsAdmin()) {
459
                // Duplicate button
460
                $adminLinks .= "<a href='" . PUBLISHER_URL . '/submit.php?op=clone&amp;itemid=' . $this->itemid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/clone.gif'" . " title='" . _CO_PUBLISHER_CLONE . "' alt='" . _CO_PUBLISHER_CLONE . "'></a>";
461
                $adminLinks .= ' ';
462
            }
463
        }
464
465
        // PDF button
466
        if ($this->helper->getConfig('display_pdf')) {
467
            if (!is_file(XOOPS_ROOT_PATH . '/class/libraries/vendor/tecnickcom/tcpdf/tcpdf.php')) {
468
                //                if (is_object($GLOBALS['xoopsUser']) && Publisher\Utility::userIsAdmin()) {
469
                //                    $GLOBALS['xoTheme']->addStylesheet('/modules/system/css/jquery.jgrowl.min.css');
470
                //                    $GLOBALS['xoTheme']->addScript('browse.php?Frameworks/jquery/plugins/jquery.jgrowl.js');
471
                //                    $adminLinks .= '<script type="text/javascript">
472
                //                    (function($){
473
                //                        $(document).ready(function(){
474
                //                            $.jGrowl("' . _MD_PUBLISHER_ERROR_NO_PDF . '");});
475
                //                        })(jQuery);
476
                //                        </script>';
477
                //                }
478
            } else {
479
                $adminLinks .= "<a href='" . PUBLISHER_URL . '/makepdf.php?itemid=' . $this->itemid() . "' rel='nofollow' target='_blank'><img src='" . PUBLISHER_URL . "/assets/images/links/pdf.gif'" . " title='" . _CO_PUBLISHER_PDF . "' alt='" . _CO_PUBLISHER_PDF . "'></a>";
480
                $adminLinks .= ' ';
481
            }
482
        }
483
484
        // Print button
485
        $adminLinks .= "<a href='" . Publisher\Seo::generateUrl('print', $this->itemid(), $this->short_url()) . "' rel='nofollow' target='_blank'><img src='" . PUBLISHER_URL . "/assets/images/links/print.gif' title='" . _CO_PUBLISHER_PRINT . "' alt='" . _CO_PUBLISHER_PRINT . "'></a>";
486
        $adminLinks .= ' ';
487
        // Email button
488
        if (xoops_isActiveModule('tellafriend')) {
489
            $subject    = sprintf(_CO_PUBLISHER_INTITEMFOUND, $GLOBALS['xoopsConfig']['sitename']);
490
            $subject    = $this->convertForJapanese($subject);
491
            $maillink   = Publisher\Utility::tellAFriend($subject);
492
            $adminLinks .= '<a href="' . $maillink . '"><img src="' . PUBLISHER_URL . '/assets/images/links/friend.gif" title="' . _CO_PUBLISHER_MAIL . '" alt="' . _CO_PUBLISHER_MAIL . '"></a>';
493
            $adminLinks .= ' ';
494
        }
495
496
        return $adminLinks;
497
    }
498
499
    /**
500
     * @param array $notifications
501
     */
502
    public function sendNotifications($notifications = [])
503
    {
504
        /** @var \XoopsNotificationHandler $notificationHandler */
505
        $notificationHandler = xoops_getHandler('notification');
506
        $tags                = [];
507
508
        $tags['MODULE_NAME']   = $this->helper->getModule()->getVar('name');
509
        $tags['ITEM_NAME']     = $this->getTitle();
510
        $tags['ITEM_NAME']     = $this->subtitle();
511
        $tags['CATEGORY_NAME'] = $this->getCategoryName();
512
        $tags['CATEGORY_URL']  = PUBLISHER_URL . '/category.php?categoryid=' . $this->categoryid();
513
        $tags['ITEM_BODY']     = $this->body();
514
        $tags['DATESUB']       = $this->getDatesub();
515
        foreach ($notifications as $notification) {
516
            switch ($notification) {
517
                case Constants::PUBLISHER_NOTIFY_ITEM_PUBLISHED:
518
                    $tags['ITEM_URL'] = PUBLISHER_URL . '/item.php?itemid=' . $this->itemid();
519
                    $notificationHandler->triggerEvent('global_item', 0, 'published', $tags, [], $this->helper->getModule()->getVar('mid'));
520
                    $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'published', $tags, [], $this->helper->getModule()->getVar('mid'));
521
                    $notificationHandler->triggerEvent('item', $this->itemid(), 'approved', $tags, [], $this->helper->getModule()->getVar('mid'));
522
                    break;
523
                case Constants::PUBLISHER_NOTIFY_ITEM_SUBMITTED:
524
                    $tags['WAITINGFILES_URL'] = PUBLISHER_URL . '/admin/item.php?itemid=' . $this->itemid();
525
                    $notificationHandler->triggerEvent('global_item', 0, 'submitted', $tags, [], $this->helper->getModule()->getVar('mid'));
526
                    $notificationHandler->triggerEvent('category_item', $this->categoryid(), 'submitted', $tags, [], $this->helper->getModule()->getVar('mid'));
527
                    break;
528
                case Constants::PUBLISHER_NOTIFY_ITEM_REJECTED:
529
                    $notificationHandler->triggerEvent('item', $this->itemid(), 'rejected', $tags, [], $this->helper->getModule()->getVar('mid'));
530
                    break;
531
                case -1:
532
                default:
533
                    break;
534
            }
535
        }
536
    }
537
538
    /**
539
     * Sets default permissions for this item
540
     */
541
    public function setDefaultPermissions()
542
    {
543
        $memberHandler = xoops_getHandler('member');
544
        $groups        = $memberHandler->getGroupList();
545
        $j             = 0;
546
        $groupIds      = [];
547
        foreach (array_keys($groups) as $i) {
548
            $groupIds[$j] = $i;
549
            ++$j;
550
        }
551
        $this->groupsRead = $groupIds;
552
    }
553
554
    /**
555
     * @todo look at this
556
     *
557
     * @param $groupIds
558
     */
559
    public function setPermissions($groupIds)
560
    {
561
        if (!isset($groupIds)) {
562
            $memberHandler = xoops_getHandler('member');
563
            $groups        = $memberHandler->getGroupList();
564
            $j             = 0;
565
            $groupIds      = [];
566
            foreach (array_keys($groups) as $i) {
567
                $groupIds[$j] = $i;
568
                ++$j;
569
            }
570
        }
571
    }
572
573
    /**
574
     * @return bool
575
     */
576
    public function notLoaded()
577
    {
578
        return -1 == $this->getVar('itemid');
579
    }
580
581
    /**
582
     * @return string
583
     */
584
    public function getItemUrl()
585
    {
586
        return Publisher\Seo::generateUrl('item', $this->itemid(), $this->short_url());
587
    }
588
589
    /**
590
     * @param bool $class
591
     * @param int  $maxsize
592
     *
593
     * @return string
594
     */
595
    public function getItemLink($class = false, $maxsize = 0)
596
    {
597
        if ($class) {
598
            return '<a class=' . $class . ' href="' . $this->getItemUrl() . '">' . $this->getTitle($maxsize) . '</a>';
599
        }
600
        return '<a href="' . $this->getItemUrl() . '">' . $this->getTitle($maxsize) . '</a>';
601
    }
602
603
    /**
604
     * @return string
605
     */
606
    public function getWhoAndWhen()
607
    {
608
        $posterName = $this->getLinkedPosterName();
609
        $postdate   = $this->getDatesub();
610
611
        return sprintf(_CO_PUBLISHER_POSTEDBY, $posterName, $postdate);
612
    }
613
614
    /**
615
     * @return string
616
     */
617
    public function getWho()
618
    {
619
        $posterName = $this->getLinkedPosterName();
620
621
        return $posterName;
622
    }
623
624
    /**
625
     * @return string
626
     */
627
    public function getWhen()
628
    {
629
        $postdate = $this->getDatesub();
630
631
        return $postdate;
632
    }
633
634
    /**
635
     * @param null|string $body
636
     *
637
     * @return string
638
     */
639
    public function plainMaintext($body = null)
640
    {
641
        $ret = '';
642
        if (!$body) {
643
            $body = $this->body();
644
        }
645
        $ret .= str_replace('[pagebreak]', '<br><br>', $body);
646
647
        return $ret;
648
    }
649
650
    /**
651
     * @param int         $itemPageId
652
     * @param null|string $body
653
     *
654
     * @return string
655
     */
656
    public function buildMainText($itemPageId = -1, $body = null)
657
    {
658
        if (null === $body) {
659
            $body = $this->body();
660
        }
661
        $bodyParts = explode('[pagebreak]', $body);
662
        $this->setVar('pagescount', count($bodyParts));
663
        if (count($bodyParts) <= 1) {
664
            return $this->plainMaintext($body);
665
        }
666
        $ret = '';
667
        if (-1 == $itemPageId) {
668
            $ret .= trim($bodyParts[0]);
669
670
            return $ret;
671
        }
672
        if ($itemPageId >= count($bodyParts)) {
673
            $itemPageId = count($bodyParts) - 1;
674
        }
675
        $ret .= trim($bodyParts[$itemPageId]);
676
677
        return $ret;
678
    }
679
680
    /**
681
     * @return mixed
682
     */
683
    public function getImages()
684
    {
685
        static $ret;
686
        $itemid = $this->getVar('itemid');
687
        if (!isset($ret[$itemid])) {
688
            $ret[$itemid]['main']   = '';
689
            $ret[$itemid]['others'] = [];
690
            $imagesIds              = [];
691
            $image                  = $this->getVar('image');
692
            $images                 = $this->getVar('images');
693
            if ('' != $images) {
694
                $imagesIds = explode('|', $images);
695
            }
696
            if ($image > 0) {
697
                $imagesIds = array_merge($imagesIds, [$image]);
698
            }
699
            $imageObjs = [];
700
            if (count($imagesIds) > 0) {
701
                $imageHandler = xoops_getHandler('image');
702
                $criteria     = new \CriteriaCompo(new \Criteria('image_id', '(' . implode(',', $imagesIds) . ')', 'IN'));
703
                $imageObjs    = $imageHandler->getObjects($criteria, true);
704
                unset($criteria);
705
            }
706
            foreach ($imageObjs as $id => $imageObj) {
707
                if ($id == $image) {
708
                    $ret[$itemid]['main'] = $imageObj;
709
                } else {
710
                    $ret[$itemid]['others'][] = $imageObj;
711
                }
712
                unset($imageObj);
713
            }
714
            unset($imageObjs);
715
        }
716
717
        return $ret[$itemid];
718
    }
719
720
    /**
721
     * @param string $display
722
     * @param int    $maxCharTitle
723
     * @param int    $maxCharSummary
724
     * @param bool   $fullSummary
725
     *
726
     * @return array
727
     */
728
    public function toArraySimple($display = 'default', $maxCharTitle = 0, $maxCharSummary = 0, $fullSummary = false)
729
    {
730
        $itemPageId = -1;
731
        if (is_numeric($display)) {
732
            $itemPageId = $display;
733
            $display    = 'all';
734
        }
735
        $item['itemid']    = $this->itemid();
736
        $item['uid']       = $this->uid();
737
        $item['itemurl']   = $this->getItemUrl();
738
        $item['titlelink'] = $this->getItemLink('titlelink', $maxCharTitle);
739
        $item['subtitle']  = $this->subtitle();
740
        $item['datesub']   = $this->getDatesub();
741
        $item['counter']   = $this->counter();
742
        $item['who']       = $this->getWho();
743
        $item['when']      = $this->getWhen();
744
        $item['category']  = $this->getCategoryName();
745
        $item              = $this->getMainImage($item);
746
        switch ($display) {
747
            case 'summary':
748
            case 'list':
749
                break;
750
            case 'full':
751
            case 'wfsection':
752
            case 'default':
753
                $summary = $this->getSummary($maxCharSummary);
754
                if (!$summary) {
755
                    $summary = $this->getBody($maxCharSummary);
756
                }
757
                $item['summary'] = $summary;
758
                $item            = $this->toArrayFull($item);
759
                break;
760
            case 'all':
761
                $item = $this->toArrayFull($item);
762
                $item = $this->toArrayAll($item, $itemPageId);
763
                break;
764
        }
765
        // Highlighting searched words
766
        $highlight = true;
767
        if ($highlight && Request::getString('keywords', '', 'GET')) {
768
            $myts     = \MyTextSanitizer::getInstance();
769
            $keywords = $myts->htmlSpecialChars(trim(urldecode(Request::getString('keywords', '', 'GET'))));
770
            $fields   = ['title', 'maintext', 'summary'];
771
            foreach ($fields as $field) {
772
                if (isset($item[$field])) {
773
                    $item[$field] = $this->highlight($item[$field], $keywords);
774
                }
775
            }
776
        }
777
778
        return $item;
779
    }
780
781
    /**
782
     * @param array $item
783
     *
784
     * @return array
785
     */
786
    public function toArrayFull($item)
787
    {
788
        $item['title']        = $this->getTitle();
789
        $item['clean_title']  = $this->getTitle();
790
        $item['itemurl']      = $this->getItemUrl();
791
        $item['cancomment']   = $this->cancomment();
792
        $item['comments']     = $this->comments();
793
        $item['adminlink']    = $this->getAdminLinks();
794
        $item['categoryPath'] = $this->getCategoryPath($this->helper->getConfig('format_linked_path'));
795
        $item['who_when']     = $this->getWhoAndWhen();
796
        $item['who']          = $this->getWho();
797
        $item['when']         = $this->getWhen();
798
        $item['category']     = $this->getCategoryName();
799
        $item                 = $this->getMainImage($item);
800
801
        return $item;
802
    }
803
804
    /**
805
     * @param array $item
806
     * @param int   $itemPageId
807
     *
808
     * @return array
809
     */
810
    public function toArrayAll($item, $itemPageId)
811
    {
812
        $item['maintext'] = $this->buildMainText($itemPageId, $this->getBody());
813
        $item             = $this->getOtherImages($item);
814
815
        return $item;
816
    }
817
818
    /**
819
     * @param array $item
820
     *
821
     * @return array
822
     */
823
    public function getMainImage($item = [])
824
    {
825
        $images             = $this->getImages();
826
        $item['image_path'] = '';
827
        $item['image_name'] = '';
828
        if (is_object($images['main'])) {
829
            $dimensions           = getimagesize($GLOBALS['xoops']->path('uploads/' . $images['main']->getVar('image_name')));
830
            $item['image_width']  = $dimensions[0];
831
            $item['image_height'] = $dimensions[1];
832
            $item['image_path']   = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name');
833
            // check to see if GD function exist
834
            if (!function_exists('imagecreatetruecolor')) {
835
                $item['image_thumb'] = XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name');
836
            } else {
837
                $item['image_thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $images['main']->getVar('image_name') . '&amp;h=180';
838
            }
839
            $item['image_name'] = $images['main']->getVar('image_nicename');
840
        }
841
842
        return $item;
843
    }
844
845
    /**
846
     * @param array $item
847
     *
848
     * @return array
849
     */
850
    public function getOtherImages($item = [])
851
    {
852
        $images         = $this->getImages();
853
        $item['images'] = [];
854
        $i              = 0;
855
        foreach ($images['others'] as $image) {
856
            $dimensions                   = getimagesize($GLOBALS['xoops']->path('uploads/' . $image->getVar('image_name')));
857
            $item['images'][$i]['width']  = $dimensions[0];
858
            $item['images'][$i]['height'] = $dimensions[1];
859
            $item['images'][$i]['path']   = XOOPS_URL . '/uploads/' . $image->getVar('image_name');
860
            // check to see if GD function exist
861
            if (!function_exists('imagecreatetruecolor')) {
862
                $item['images'][$i]['thumb'] = XOOPS_URL . '/uploads/' . $image->getVar('image_name');
863
            } else {
864
                $item['images'][$i]['thumb'] = PUBLISHER_URL . '/thumb.php?src=' . XOOPS_URL . '/uploads/' . $image->getVar('image_name') . '&amp;w=240';
865
            }
866
            $item['images'][$i]['name'] = $image->getVar('image_nicename');
867
            ++$i;
868
        }
869
870
        return $item;
871
    }
872
873
    /**
874
     * @param string       $content
875
     * @param string|array $keywords
876
     *
877
     * @return string Text
878
     */
879
    public function highlight($content, $keywords)
880
    {
881
        $color = $this->helper->getConfig('format_highlight_color');
882
        if (0 !== mb_strpos($color, '#')) {
883
            $color = '#' . $color;
884
        }
885
        require_once __DIR__ . '/Highlighter.php';
886
        $highlighter = new Highlighter();
887
        $highlighter->setReplacementString('<span style="font-weight: bolder; background-color: ' . $color . ';">\1</span>');
888
889
        return $highlighter->highlight($content, $keywords);
890
    }
891
892
    /**
893
     *  Create metada and assign it to template
894
     */
895
    public function createMetaTags()
896
    {
897
        $publisherMetagen = new Publisher\Metagen($this->getTitle(), $this->meta_keywords(), $this->meta_description(), $this->category->categoryPath);
898
        $publisherMetagen->createMetaTags();
899
    }
900
901
    /**
902
     * @param string $str
903
     *
904
     * @return string
905
     */
906
    protected function convertForJapanese($str)
907
    {
908
        // no action, if not flag
909
        if (!defined('_PUBLISHER_FLAG_JP_CONVERT')) {
910
            return $str;
911
        }
912
        // no action, if not Japanese
913
        if ('japanese' !== $GLOBALS['xoopsConfig']['language']) {
914
            return $str;
915
        }
916
        // presume OS Browser
917
        $agent   = Request::getString('HTTP_USER_AGENT', '', 'SERVER');
918
        $os      = '';
919
        $browser = '';
920
        //        if (preg_match("/Win/i", $agent)) {
921
        if (false !== mb_stripos($agent, 'Win')) {
922
            $os = 'win';
923
        }
924
        //        if (preg_match("/MSIE/i", $agent)) {
925
        if (false !== mb_stripos($agent, 'MSIE')) {
926
            $browser = 'msie';
927
        }
928
        // if msie
929
        if (('win' === $os) && ('msie' === $browser)) {
930
            // if multibyte
931
            if (function_exists('mb_convert_encoding')) {
932
                $str = mb_convert_encoding($str, 'SJIS', 'EUC-JP');
933
                $str = rawurlencode($str);
934
            }
935
        }
936
937
        return $str;
938
    }
939
940
    /**
941
     * @param string $title
942
     * @param bool   $checkperm
943
     *
944
     * @return \XoopsModules\Publisher\Form\ItemForm
945
     */
946
    public function getForm($title = 'default', $checkperm = true)
947
    {
948
        //        require_once $GLOBALS['xoops']->path('modules/' . PUBLISHER_DIRNAME . '/class/form/item.php');
949
        $form = new Publisher\Form\ItemForm($title, 'form', xoops_getenv('PHP_SELF'), 'post', true);
950
        $form->setCheckPermissions($checkperm);
951
        $form->createElements($this);
952
953
        return $form;
954
    }
955
956
    /**
957
     * Checks if a user has access to a selected item. if no item permissions are
958
     * set, access permission is denied. The user needs to have necessary category
959
     * permission as well.
960
     * Also, the item needs to be Published
961
     *
962
     * @return bool : TRUE if the no errors occured
963
     */
964
    public function accessGranted()
965
    {
966
        if (Publisher\Utility::userIsAdmin()) {
967
            return true;
968
        }
969
        if (Constants::PUBLISHER_STATUS_PUBLISHED != $this->status()) {
970
            return false;
971
        }
972
        // Do we have access to the parent category
973
        if ($this->helper->getHandler('Permission')->isGranted('category_read', $this->categoryid())) {
974
            return true;
975
        }
976
977
        return false;
978
    }
979
980
    /**
981
     * The name says it all
982
     */
983
    public function setVarsFromRequest()
984
    {
985
        //Required fields
986
        //        if (!empty($categoryid = Request::getInt('categoryid', 0, 'POST'))) {
987
        //            $this->setVar('categoryid', $categoryid);}
988
989
        $this->setVar('categoryid', Request::getInt('categoryid', 0, 'POST'));
990
        $this->setVar('title', Request::getString('title', '', 'POST'));
991
        $this->setVar('body', Request::getText('body', '', 'POST'));
992
993
        //Not required fields
994
        $this->setVar('summary', Request::getText('summary', '', 'POST'));
995
        $this->setVar('subtitle', Request::getString('subtitle', '', 'POST'));
996
        $this->setVar('item_tag', Request::getString('item_tag', '', 'POST'));
997
998
        if (false !== ($imageFeatured = Request::getString('image_featured', '', 'POST'))) {
999
            $imageItem = Request::getArray('image_item', [], 'POST');
1000
            //            $imageFeatured = Request::getString('image_featured', '', 'POST');
1001
            //Todo: get a better image class for xoops!
1002
            //Image hack
1003
            $imageItemIds = [];
1004
1005
            $sql    = 'SELECT image_id, image_name FROM ' . $GLOBALS['xoopsDB']->prefix('image');
1006
            $result = $GLOBALS['xoopsDB']->query($sql, 0, 0);
1007
            while (false !== ($myrow = $GLOBALS['xoopsDB']->fetchArray($result))) {
1008
                $imageName = $myrow['image_name'];
1009
                $id        = $myrow['image_id'];
1010
                if ($imageName == $imageFeatured) {
1011
                    $this->setVar('image', $id);
1012
                }
1013
                if (in_array($imageName, $imageItem)) {
1014
                    $imageItemIds[] = $id;
1015
                }
1016
            }
1017
            $this->setVar('images', implode('|', $imageItemIds));
1018
        } else {
1019
            $this->setVar('image', 0);
1020
            $this->setVar('images', '');
1021
        }
1022
1023
        if (false !== ($authorAlias = Request::getString('author_alias', '', 'POST'))) {
1024
            $this->setVar('author_alias', $authorAlias);
1025
            if ('' !== $this->getVar('author_alias')) {
1026
                $this->setVar('uid', 0);
1027
            }
1028
        }
1029
1030
        //mb TODO check on version
1031
        //check if date is set and convert it to GMT date
1032
        //        if (($datesub = Request::getString('datesub', '', 'POST'))) {
1033
        if ('' !== Request::getString('datesub', '', 'POST')) {
1034
            //            if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
1035
            //                $this->setVar('datesub', strtotime(Request::getArray('datesub', array(), 'POST')['date']) + Request::getArray('datesub', array(), 'POST')['time']);
1036
            //            } else {
1037
            $resDate = Request::getArray('datesub', [], 'POST');
1038
            $resTime = Request::getArray('datesub', [], 'POST');
1039
            //            $this->setVar('datesub', strtotime($resDate['date']) + $resTime['time']);
1040
            $localTimestamp = strtotime($resDate['date']) + $resTime['time'];
1041
1042
            // get user Timezone offset and use it to find out the Timezone, needed for PHP DataTime
1043
            $userTimeoffset = $GLOBALS['xoopsUser']->getVar('timezone_offset');
1044
            $tz             = timezone_name_from_abbr(null, $userTimeoffset * 3600);
1045
            if (false === $tz) {
1046
                $tz = timezone_name_from_abbr(null, $userTimeoffset * 3600, false);
1047
            }
1048
1049
            $userTimezone = new \DateTimeZone($tz);
1050
            $gmtTimezone  = new \DateTimeZone('GMT');
1051
            $myDateTime   = new \DateTime('now', $gmtTimezone);
1052
            $offset       = $userTimezone->getOffset($myDateTime);
1053
1054
            $gmtTimestamp = $localTimestamp - $offset;
1055
            $this->setVar('datesub', $gmtTimestamp);
1056
1057
            //            }
1058
        } elseif ($this->isNew()) {
1059
            $this->setVar('datesub', time());
1060
        }
1061
1062
        $this->setVar('short_url', Request::getString('item_short_url', '', 'POST'));
1063
        $this->setVar('meta_keywords', Request::getString('item_meta_keywords', '', 'POST'));
1064
        $this->setVar('meta_description', Request::getString('item_meta_description', '', 'POST'));
1065
        $this->setVar('weight', Request::getInt('weight', 0, 'POST'));
1066
1067
        if ($this->isNew()) {
1068
            $this->setVar('uid', is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0);
1069
            $this->setVar('cancoment', $this->helper->getConfig('submit_allowcomments'));
1070
            $this->setVar('status', $this->helper->getConfig('submit_status'));
1071
            $this->setVar('dohtml', $this->helper->getConfig('submit_dohtml'));
1072
            $this->setVar('dosmiley', $this->helper->getConfig('submit_dosmiley'));
1073
            $this->setVar('doxcode', $this->helper->getConfig('submit_doxcode'));
1074
            $this->setVar('doimage', $this->helper->getConfig('submit_doimage'));
1075
            $this->setVar('dobr', $this->helper->getConfig('submit_dobr'));
1076
        } else {
1077
            $this->setVar('uid', Request::getInt('uid', 0, 'POST'));
1078
            $this->setVar('cancomment', Request::getInt('allowcomments', 1, 'POST'));
1079
            $this->setVar('status', Request::getInt('status', 1, 'POST'));
1080
            $this->setVar('dohtml', Request::getInt('dohtml', 1, 'POST'));
1081
            $this->setVar('dosmiley', Request::getInt('dosmiley', 1, 'POST'));
1082
            $this->setVar('doxcode', Request::getInt('doxcode', 1, 'POST'));
1083
            $this->setVar('doimage', Request::getInt('doimage', 1, 'POST'));
1084
            $this->setVar('dobr', Request::getInt('dolinebreak', 1, 'POST'));
1085
        }
1086
1087
        $this->setVar('notifypub', Request::getString('notify', '', 'POST'));
1088
    }
1089
}
1090