HeadlineRenderer::getBlock()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Xoopsheadline;
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
//use think\console\command\Help;
16
17
/**
18
 * @copyright    XOOPS Project (https://xoops.org)
19
 * @license      GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
20
 * @author       XOOPS Development Team, Kazumi Ono (AKA onokazu)
21
 */
22
require_once XOOPS_ROOT_PATH . '/class/template.php';
23
24
$helper = Helper::getInstance();
25
$helper->loadLanguage('main');
26
27
/**
28
 * Class HeadlineRenderer
29
 */
30
class HeadlineRenderer
31
{
32
    // holds reference to Headline class object
33
    protected $headline;
34
    protected $tpl;
35
    protected $feed;
36
    protected $block;
37
    protected $errors = [];
38
    // RSS2 SAX parser
39
    protected $parser;
40
41
    /**
42
     * HeadlineRenderer constructor.
43
     */
44
    public function __construct(Headline $headline)
45
    {
46
        $this->headline = $headline;
47
        $this->tpl      = new \XoopsTpl();
48
    }
49
50
    /**
51
     * @return int|bool
52
     */
53
    public function updateCache()
54
    {
55
        $helper = Helper::getInstance();
56
        /**
57
         * Update cache - first try using fopen and then cURL
58
         */
59
        $retval = false;
60
        if ($fp = @\fopen($this->headline->getVar('headline_rssurl'), 'rb')) {  // successfully openned file using fopen
61
            $data = '';
62
            while (!\feof($fp)) {
63
                $data .= \fgets($fp, 4096);
64
            }
65
            \fclose($fp);
66
            $this->headline->setVar('headline_xml', $this->convertToUtf8($data));
67
            $this->headline->setVar('headline_updated', \time());
68
            $headlineHandler = $helper->getHandler('Headline');
69
            if (null !== $headlineHandler) {
70
                $retval = $headlineHandler->insert($this->headline);
71
            }
72
        } else {
73
            // failed open using fopen, now try cURL
74
            $ch = \curl_init($this->headline->getVar('headline_rssurl'));
75
            if (\curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true)) {
76
                if ($data = \curl_exec($ch)) {
77
                    \curl_close($ch);
78
                    $this->headline->setVar('headline_xml', $this->convertToUtf8($data));
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type true; however, parameter $xmlfile of XoopsModules\Xoopsheadli...nderer::convertToUtf8() 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

78
                    $this->headline->setVar('headline_xml', $this->convertToUtf8(/** @scrutinizer ignore-type */ $data));
Loading history...
79
                    $this->headline->setVar('headline_updated', \time());
80
                    $headlineHandler = $helper->getHandler('Headline');
81
                    if (null !== $headlineHandler) {
82
                        $retval = $headlineHandler->insert($this->headline);
83
                    }
84
                } else {
85
                    \curl_close($ch);
86
                    $errmsg = \sprintf(\_MD_XOOPSHEADLINE_NOTOPEN, $this->headline->getVar('headline_rssurl'));
0 ignored issues
show
Bug introduced by
It seems like $this->headline->getVar('headline_rssurl') can also be of type array and array; however, parameter $values of sprintf() does only seem to accept double|integer|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

86
                    $errmsg = \sprintf(\_MD_XOOPSHEADLINE_NOTOPEN, /** @scrutinizer ignore-type */ $this->headline->getVar('headline_rssurl'));
Loading history...
87
                    $this->setErrors($errmsg);
88
                }
89
            } else {
90
                $this->setErrors(\_MD_XOOPSHEADLINE_BADOPT);
91
            }
92
        }
93
94
        return $retval;
95
    }
96
97
    public function renderFeed(bool $force_update = false): bool
98
    {
99
        $retval = false;
100
        if ($force_update || $this->headline->cacheExpired()) {
101
            if (!$this->updateCache()) {
102
                return $retval;
103
            }
104
        }
105
        if ($this->_parse()) {
106
            $this->tpl->clear_all_assign();
107
            $this->tpl->assign('xoops_url', XOOPS_URL);
108
            $channel_data = $this->parser->getChannelData();
109
            \array_walk($channel_data, [$this, 'convertFromUtf8']);
110
            $this->tpl->assign_by_ref('channel', $channel_data);
111
            if (1 == $this->headline->getVar('headline_mainimg')) {
112
                $image_data = $this->parser->getImageData();
113
                \array_walk($image_data, [$this, 'convertFromUtf8']);
114
                $max_width  = 256;
115
                $max_height = 92;
116
                if (!isset($image_data['height']) || !isset($image_data['width'])) {
117
                    $image_size = @\getimagesize($image_data['url']);
118
                    if ($image_size) {
119
                        $image_data['width']  = $image_size[0];
120
                        $image_data['height'] = $image_size[1];
121
                    }
122
                }
123
                if (\array_key_exists('height', $image_data) && \array_key_exists('width', $image_data)
124
                    && ($image_data['width'] > 0)) {
125
                    $width_ratio  = $image_data['width'] / $max_width;
126
                    $height_ratio = $image_data['height'] / $max_height;
127
                    $scale        = \max($width_ratio, $height_ratio);
128
                    if ($scale > 1) {
129
                        $image_data['width']  = (int)($image_data['width'] / $scale);
130
                        $image_data['height'] = (int)($image_data['height'] / $scale);
131
                    }
132
                }
133
                $this->tpl->assign_by_ref('image', $image_data);
134
            }
135
            if (1 == $this->headline->getVar('headline_mainfull')) {
136
                $this->tpl->assign('show_full', true);
137
            } else {
138
                $this->tpl->assign('show_full', false);
139
            }
140
            $items = $this->parser->getItems();
141
            $count = \count($items);
142
            $max   = ($count > $this->headline->getVar('headline_mainmax')) ? $this->headline->getVar('headline_mainmax') : $count;
143
            for ($i = 0; $i < $max; ++$i) {
144
                \array_walk($items[$i], [$this, 'convertFromUtf8']);
145
                $this->tpl->append_by_ref('items', $items[$i]);
146
            }
147
            $this->tpl->assign(
148
                [
149
                    'lang_lastbuild'   => \_MD_XOOPSHEADLINE_LASTBUILD,
150
                    'lang_language'    => \_MD_XOOPSHEADLINE_LANGUAGE,
151
                    'lang_description' => \_MD_XOOPSHEADLINE_DESCRIPTION,
152
                    'lang_webmaster'   => \_MD_XOOPSHEADLINE_WEBMASTER,
153
                    'lang_category'    => \_MD_XOOPSHEADLINE_CATEGORY,
154
                    'lang_generator'   => \_MD_XOOPSHEADLINE_GENERATOR,
155
                    'lang_title'       => \_MD_XOOPSHEADLINE_TITLE,
156
                    'lang_pubdate'     => \_MD_XOOPSHEADLINE_PUBDATE,
157
                    //                                   'lang_description2' => _MD_XOOPSHEADLINE_DESCRIPTION2,
158
                    'lang_more'        => _MORE,
159
                ]
160
            );
161
            $this->feed = $this->tpl->fetch('db:xoopsheadline_feed.tpl');
162
            $retval     = true;
163
        }
164
165
        return $retval;
166
    }
167
168
    public function renderBlock(bool $force_update = false): bool
169
    {
170
        $retval = false;
171
        if ($force_update || $this->headline->cacheExpired()) {
172
            if (!$this->updateCache()) {
173
                return $retval;
174
            }
175
        }
176
        if ($this->_parse()) {
177
            $this->tpl->clear_all_assign();
178
            $this->tpl->assign('xoops_url', XOOPS_URL);
179
            $channel_data = $this->parser->getChannelData();
180
            \array_walk($channel_data, [$this, 'convertFromUtf8']);
181
            $this->tpl->assign_by_ref('channel', $channel_data);
182
            if (1 == $this->headline->getVar('headline_blockimg')) {
183
                $image_data = $this->parser->getImageData();
184
                \array_walk($image_data, [$this, 'convertFromUtf8']);
185
                $this->tpl->assign_by_ref('image', $image_data);
186
            }
187
            $items = $this->parser->getItems();
188
            $count = \count($items);
189
            $max   = ($count > $this->headline->getVar('headline_blockmax')) ? $this->headline->getVar('headline_blockmax') : $count;
190
            for ($i = 0; $i < $max; ++$i) {
191
                \array_walk($items[$i], [$this, 'convertFromUtf8']);
192
                $this->tpl->append_by_ref('items', $items[$i]);
193
            }
194
            $this->tpl->assign(
195
                [
196
                    'site_name' => $this->headline->getVar('headline_name'),
197
                    'site_url'  => $this->headline->getVar('headline_url'),
198
                    'site_id'   => $this->headline->getVar('headline_id'),
199
                ]
200
            );
201
202
            $this->block = $this->tpl->fetch('db:blocks/headline_block.tpl');
203
            $retval      = true;
204
        }
205
206
        return $retval;
207
    }
208
209
    protected function &_parse(): bool
210
    {
211
        $retval = true;
212
        if (!isset($this->parser)) {
213
            require_once XOOPS_ROOT_PATH . '/class/xml/rss/xmlrss2parser.php';
214
            $temp         = $this->headline->getVar('headline_xml');
215
            $this->parser = new \XoopsXmlRss2Parser($temp);
216
            switch ($this->headline->getVar('headline_encoding')) {
217
                case 'utf-8':
218
                    $this->parser->useUtfEncoding();
219
                    break;
220
                case 'us-ascii':
221
                    $this->parser->useAsciiEncoding();
222
                    break;
223
                default:
224
                    $this->parser->useIsoEncoding();
225
                    break;
226
            }
227
            $result = $this->parser->parse();
228
            if (!$result) {
229
                $this->setErrors($this->parser->getErrors(false));
0 ignored issues
show
Bug introduced by
$this->parser->getErrors(false) of type string[] is incompatible with the type string expected by parameter $err of XoopsModules\Xoopsheadli...neRenderer::setErrors(). ( Ignorable by Annotation )

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

229
                $this->setErrors(/** @scrutinizer ignore-type */ $this->parser->getErrors(false));
Loading history...
230
                unset($this->parser);
231
                $retval = false;
232
            }
233
        }
234
235
        return $retval;
236
    }
237
238
    /**
239
     * @return mixed
240
     */
241
    public function &getFeed()
242
    {
243
        return $this->feed;
244
    }
245
246
    /**
247
     * @return mixed
248
     */
249
    public function &getBlock()
250
    {
251
        return $this->block;
252
    }
253
254
    protected function setErrors(string $err): void
255
    {
256
        $this->errors[] = $err;
257
    }
258
259
    /**
260
     * @return array|string
261
     */
262
    public function &getErrors(bool $ashtml = true)
263
    {
264
        if ($ashtml) {
265
            $retval = '';
266
            if (\count($this->errors) > 0) {
267
                foreach ($this->errors as $error) {
268
                    $retval .= $error . '<br>';
269
                }
270
            }
271
        } else {
272
            $retval = $this->errors;
273
        }
274
275
        return $retval;
276
    }
277
278
    // abstract
279
    // overide this method in /language/your_language/headlinerenderer.php
280
    // this method is called by the array_walk function
281
    // return void
282
283
    /**
284
     * @param $value
285
     * @param $key
286
     */
287
    public function convertFromUtf8(&$value, $key): void
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed. ( Ignorable by Annotation )

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

287
    public function convertFromUtf8(/** @scrutinizer ignore-unused */ &$value, $key): void

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

Loading history...
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

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

287
    public function convertFromUtf8(&$value, /** @scrutinizer ignore-unused */ $key): void

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

Loading history...
288
    {
289
    }
290
291
    // abstract
292
    // overide this method in /language/your_language/headlinerenderer.php
293
    // return string
294
295
    public function &convertToUtf8(string &$xmlfile): string
296
    {
297
        if ('iso-8859-1' === \mb_strtolower($this->headline->getVar('headline_encoding'))) {
298
            $xmlfile = utf8_encode($xmlfile);
299
        }
300
301
        return $xmlfile;
302
    }
303
}
304