Poll   F
last analyzed

Complexity

Total Complexity 61

Size/Duplication

Total Lines 511
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 275
c 1
b 0
f 0
dl 0
loc 511
rs 3.52
wmc 61

13 Methods

Rating   Name   Duplication   Size   Complexity  
A isAllowedToVote() 0 11 5
A __toString() 0 5 1
A delete() 0 7 1
A store() 0 7 1
A getStaticPollHandler() 0 11 2
A __construct() 0 40 4
A updateCount() 0 7 1
B isResultVisible() 0 36 11
B notifyVoter() 0 68 11
A hasExpired() 0 8 2
C vote() 0 44 14
B renderForm() 0 140 7
A getComments() 0 14 1

How to fix   Complexity   

Complex Class

Complex classes like Poll often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Poll, and based on these observations, apply Extract Interface, too.

1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Xoopspoll;
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
 This program is distributed in the hope that it will be useful,
10
 but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
*/
13
14
/**
15
 * XOOPS Poll Class Definitions
16
 *
17
 * @copyright ::  {@link https://xoops.org/ XOOPS Project}
18
 * @license   ::    {@link https://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2.0 or later}
19
 * @subpackage:: class
20
 * @since     ::         1.40
21
 * @author    ::     zyspec <[email protected]>
22
 */
23
\xoops_loadLanguage('admin', \basename(\dirname(__DIR__)));
24
25
/**
26
 * Class Poll
27
 */
28
class Poll extends \XoopsObject
29
{
30
    private int    $poll_id;
0 ignored issues
show
introduced by
The private property $poll_id is not used, and could be removed.
Loading history...
31
    private string $question;
0 ignored issues
show
introduced by
The private property $question is not used, and could be removed.
Loading history...
32
    private string $description;
0 ignored issues
show
introduced by
The private property $description is not used, and could be removed.
Loading history...
33
    private int    $user_id;
0 ignored issues
show
introduced by
The private property $user_id is not used, and could be removed.
Loading history...
34
    private int    $start_time;
0 ignored issues
show
introduced by
The private property $start_time is not used, and could be removed.
Loading history...
35
    private int    $end_time;
0 ignored issues
show
introduced by
The private property $end_time is not used, and could be removed.
Loading history...
36
    private int    $votes;
0 ignored issues
show
introduced by
The private property $votes is not used, and could be removed.
Loading history...
37
    private int    $voters;
0 ignored issues
show
introduced by
The private property $voters is not used, and could be removed.
Loading history...
38
    private int    $display;
0 ignored issues
show
introduced by
The private property $display is not used, and could be removed.
Loading history...
39
    private int    $visibility;
0 ignored issues
show
introduced by
The private property $visibility is not used, and could be removed.
Loading history...
40
    private int    $anonymous;
0 ignored issues
show
introduced by
The private property $anonymous is not used, and could be removed.
Loading history...
41
    private int    $weight;
0 ignored issues
show
introduced by
The private property $weight is not used, and could be removed.
Loading history...
42
    private int    $multiple;
0 ignored issues
show
introduced by
The private property $multiple is not used, and could be removed.
Loading history...
43
    private int    $multilimit;
0 ignored issues
show
introduced by
The private property $multilimit is not used, and could be removed.
Loading history...
44
    private int    $mail_status;
0 ignored issues
show
introduced by
The private property $mail_status is not used, and could be removed.
Loading history...
45
    private int    $mail_voter;
0 ignored issues
show
introduced by
The private property $mail_voter is not used, and could be removed.
Loading history...
46
47
    /**
48
     * Poll::__construct()
49
     *
50
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
51
     */
52
    public function __construct($id = null)
53
    {
54
        parent::__construct();
55
        //        $timestamp = xoops_getUserTimestamp(time());
56
        $currentTimestamp = \time();
57
        $this->initVar('poll_id', \XOBJ_DTYPE_INT, null, false);
58
        $this->initVar('question', \XOBJ_DTYPE_TXTBOX, null, true, 255);
59
        $this->initVar('description', \XOBJ_DTYPE_TXTAREA, null, false);
60
        $this->initVar('user_id', \XOBJ_DTYPE_INT, null, false);
61
        $this->initVar('start_time', \XOBJ_DTYPE_INT, $currentTimestamp, false);
62
        $this->initVar('end_time', \XOBJ_DTYPE_INT, $currentTimestamp + Constants::DEFAULT_POLL_DURATION, true);
63
        $this->initVar('votes', \XOBJ_DTYPE_INT, 0, false);
64
        $this->initVar('voters', \XOBJ_DTYPE_INT, 0, false);
65
        $this->initVar('display', \XOBJ_DTYPE_INT, Constants::DISPLAY_POLL_IN_BLOCK, false);
66
        $this->initVar('visibility', \XOBJ_DTYPE_INT, Constants::HIDE_NEVER, false);
67
        $this->initVar('anonymous', \XOBJ_DTYPE_INT, Constants::ANONYMOUS_VOTING_DISALLOWED, false);
68
        $this->initVar('weight', \XOBJ_DTYPE_INT, Constants::DEFAULT_WEIGHT, false);
69
        $this->initVar('multiple', \XOBJ_DTYPE_INT, Constants::NOT_MULTIPLE_SELECT_POLL, false);
70
        $this->initVar('multilimit', \XOBJ_DTYPE_INT, Constants::MULTIPLE_SELECT_LIMITLESS, false);
71
        $this->initVar('mail_status', \XOBJ_DTYPE_INT, Constants::POLL_NOT_MAILED, false);
72
        $this->initVar('mail_voter', \XOBJ_DTYPE_INT, Constants::NOT_MAIL_POLL_TO_VOTER, false);
73
74
        /**
75
         * {@internal This code added to support previous versions of newbb/xForum}
76
         */
77
        if (!empty($id)) {
78
            $trace    = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
79
            $errorMsg = __CLASS__ . " instantiation with 'id' set is deprecated since Xoopspoll 1.40, please use PollHandler instead." . " Called from {$trace[0]['file']}line {$trace[0]['line']}";
80
            if (isset($GLOBALS['xoopsLogger'])) {
81
                $GLOBALS['xoopsLogger']->addDeprecated($errorMsg);
82
            } else {
83
                \trigger_error($errorMsg, \E_USER_WARNING);
84
            }
85
86
            if (\is_array($id)) {
87
                $this->assignVars($id);
88
            } else {
89
                $pollHandler = Helper::getInstance()->getHandler('Poll');
90
                $this->assignVars($pollHandler->getAll(new \Criteria('id', $id, '=')), null, false);
0 ignored issues
show
Unused Code introduced by
The call to XoopsObject::assignVars() has too many arguments starting with null. ( Ignorable by Annotation )

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

90
                $this->/** @scrutinizer ignore-call */ 
91
                       assignVars($pollHandler->getAll(new \Criteria('id', $id, '=')), null, false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
91
                unset($pollHandler);
92
            }
93
        }
94
    }
95
96
    /**
97
     * Set display string for class
98
     * @return string
99
     */
100
    public function __toString()
101
    {
102
        $ret = $this->getVar('question');
103
104
        return (string)$ret;
105
    }
106
107
    /**
108
     * Find out if poll has expired
109
     * @uses   Poll::getVar()
110
     */
111
    public function hasExpired(): bool
112
    {
113
        $ret = true;
114
        if ($this->getVar('end_time') > \time()) {
115
            $ret = false;
116
        }
117
118
        return $ret;
119
    }
120
121
    /**
122
     * Determine if user is allowed to vote in this poll
123
     * @uses   Poll::getVar()
124
     * @uses   XoopsUser
125
     */
126
    public function isAllowedToVote(): bool
127
    {
128
        $ret = false;
129
        if ((Constants::ANONYMOUS_VOTING_ALLOWED === $this->getVar('anonymous'))
130
            || (($GLOBALS['xoopsUser'] instanceof \XoopsUser)
131
                && (($GLOBALS['xoopsUser']->uid() > 0)
132
                    && $GLOBALS['xoopsUser']->isActive()))) {
133
            $ret = true;
134
        }
135
136
        return $ret;
137
    }
138
139
    /**
140
     * @param int $optionId
141
     * @param string $ip ip address of voter
142
     * @param int $time
143
     * @return bool   true vote entered, false voting failed
144
     * @uses     xoops_getModuleHandler()
145
     * @uses     CriteriaCompo()
146
     * @uses     PollHandler::getAll()
147
     * @uses     LogHandler
148
     * @internal param int $uid
149
     */
150
    public function vote(int $optionId, string $ip, int $time): bool
151
    {
152
        if (!empty($optionId) && $this->isAllowedToVote()) {
153
            $voteTime      = empty($time) ? \time() : (int)$time;
154
            $uid           = ($GLOBALS['xoopsUser'] instanceof \XoopsUser) ? $GLOBALS['xoopsUser']->uid() : 0;
155
            $logHandler    = Helper::getInstance()->getHandler('Log');
156
            $optionHandler = Helper::getInstance()->getHandler('Option');
157
            $optsIdArray   = (array)$optionId; // type cast to make sure it's an array
158
            $optsIdArray   = \array_map('\intval', $optsIdArray); // make sure values are integers
159
            /* check to make sure voter hasn't selected too many options */
160
            if (!$this->getVar('multiple')
161
                || ($this->getVar('multiple')
162
                    && ((Constants::MULTIPLE_SELECT_LIMITLESS === $this->getVar('multilimit'))
163
                        || (\count($optsIdArray) <= $this->getVar('multilimit'))))) {
164
                $criteria = new \CriteriaCompo();
165
                $criteria->add(new \Criteria('option_id', '(' . \implode(',', $optsIdArray) . ')', 'IN'));
166
                $optionObjs = $optionHandler->getAll($criteria);
167
                foreach ($optionObjs as $optionObj) {
168
                    //                    if ($this->getVar('poll_id') == $optionObj->getVar('poll_id')) {
169
                    $log = $logHandler->create();
170
                    //force ip if invalid
171
                    $ip      = \filter_var($ip, \FILTER_VALIDATE_IP) ? $ip : '255.255.255.254';
172
                    $logVars = [
173
                        'poll_id'   => $this->getVar('poll_id'),
174
                        'option_id' => (int)$optionObj->getVar('option_id'),
175
                        'ip'        => $ip,
176
                        'user_id'   => $uid,
177
                        'time'      => $voteTime,
178
                    ];
179
                    $log->setVars($logVars);
180
                    if (false !== $logHandler->insert($log)) {
181
                        $optionHandler->updateCount($optionObj);
182
                    }
183
                }
184
                // now send voter an email if the poll is set to allow it (if the user is not anon)
185
                if (!empty($uid) && Constants::MAIL_POLL_TO_VOTER === $this->getVar('mail_voter')) {
186
                    $this->notifyVoter($GLOBALS['xoopsUser']);
187
                }
188
189
                return true;
190
            }
191
        }
192
193
        return false;
194
    }
195
196
    /**
197
     * Gets number of comments for this poll
198
     * @param int poll_id
0 ignored issues
show
Bug introduced by
The type XoopsModules\Xoopspoll\poll_id was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
199
     * @return int count of comments for this poll_id
200
     */
201
    public function getComments(): int
202
    {
203
        $moduleHandler = \xoops_getHandler('module');
204
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
0 ignored issues
show
Bug introduced by
The method getByDirname() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsModuleHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

204
        /** @scrutinizer ignore-call */ 
205
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
Loading history...
205
206
        /** @var \XoopsCommentHandler $commentHandler */
207
        $commentHandler = \xoops_getHandler('comment');
208
        $criteria       = new \CriteriaCompo();
209
        $criteria->add(new \Criteria('com_itemid', $this->getVar('poll_id'), '='));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('poll_id') can also be of type array and array; however, parameter $value of Criteria::__construct() 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

209
        $criteria->add(new \Criteria('com_itemid', /** @scrutinizer ignore-type */ $this->getVar('poll_id'), '='));
Loading history...
210
        $criteria->add(new \Criteria('com_modid', $pollModule->getVar('mid'), '='));
211
        $commentCount = $commentHandler->getCount($criteria);
212
        $commentCount = (int)$commentCount;
213
214
        return $commentCount;
215
    }
216
217
    /**
218
     * display the poll form
219
     * @param string $rtnPage   where to send the form result
220
     * @param string $rtnMethod return method  get|post
221
     * @param array $addHidden
222
     */
223
    public function renderForm(string $rtnPage, string $rtnMethod = 'post', array $addHidden = [])
224
    {
225
        \xoops_load('xoopsformloader');
226
        $myts = \MyTextSanitizer::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $myts is dead and can be removed.
Loading history...
227
228
        $rtnMethod = \mb_strtolower($rtnMethod);
229
        // force form to use xoopsSecurity if it's a 'post' form
230
        $rtnSecurity = 'post' === \mb_strtolower($rtnMethod);
231
232
        //  set form titles, etc. depending on if it's a new object or not
233
        if ($this->isNew()) {
234
            $formTitle = \_AM_XOOPSPOLL_CREATENEWPOLL;
235
            $this->setVar('user_id', $GLOBALS['xoopsUser']->getVar('uid'));
236
        } else {
237
            $formTitle = \_AM_XOOPSPOLL_EDITPOLL;
238
        }
239
240
        /*  create the form */
241
        $pollForm    = new \XoopsThemeForm(\ucwords($formTitle), 'poll_form', $rtnPage, $rtnMethod, $rtnSecurity);
242
        $authorLabel = new \XoopsFormLabel(\_AM_XOOPSPOLL_AUTHOR, "<a href='" . $GLOBALS['xoops']->url('userinfo.php') . '?uid=' . $this->getVar('user_id') . "' target='_blank'>" . \ucfirst(\XoopsUser::getUnameFromId($this->getVar('user_id'))) . '</a>');
243
        $pollForm->addElement($authorLabel);
244
        $pollForm->addElement(new \XoopsFormText(\_AM_XOOPSPOLL_DISPLAYORDER, 'weight', 6, 5, $this->getVar('weight')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('weight') can also be of type array and array; however, parameter $value of XoopsFormText::__construct() 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

244
        $pollForm->addElement(new \XoopsFormText(\_AM_XOOPSPOLL_DISPLAYORDER, 'weight', 6, 5, /** @scrutinizer ignore-type */ $this->getVar('weight')));
Loading history...
245
        $questionText = new \XoopsFormText(\_AM_XOOPSPOLL_POLLQUESTION, 'question', 50, 255, $this->getVar('question', 'E'));
246
        $pollForm->addElement($questionText, true);
247
        /*
248
                $descTarea = new \XoopsFormTextarea(_AM_XOOPSPOLL_POLLDESC, "description", $this->getVar('description', 'E'));
249
                $pollForm->addElement($descTarea);
250
        */
251
        /** @var \XoopsModuleHandler $moduleHandler */
252
        $moduleHandler = \xoops_getHandler('module');
253
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
0 ignored issues
show
Unused Code introduced by
The assignment to $pollModule is dead and can be removed.
Loading history...
254
255
        /** @var \XoopsConfigHandler $configHandler */
256
        $configHandler = \xoops_getHandler('config');
257
        //        $xp_module      = $moduleHandler->getByDirname("xoopspoll");
258
        //        $module_id      = $xp_module->getVar("mid");
259
        //        $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
260
        $sys_module = $moduleHandler->getByDirname('system');
261
        $sys_id     = $sys_module->getVar('mid');
262
        $sys_config = $configHandler->getConfigsByCat(0, $sys_id);
263
264
        $editorConfigs = [
265
            //                           'editor' => $GLOBALS['xoopsModuleConfig']['useeditor'],
266
            //                           'editor' => $xp_config['useeditor'],
267
            'editor' => $sys_config['general_editor'],
268
            'rows'   => 15,
269
            'cols'   => 60,
270
            'width'  => '100%',
271
            'height' => '350px',
272
            'name'   => 'description',
273
            //                           'value'  => ($this->getVar('description'))
274
            'value'  => \htmlspecialchars($this->getVar('description'), \ENT_QUOTES | \ENT_HTML5),
275
        ];
276
        $desc_text     = new \XoopsFormEditor(\_AM_XOOPSPOLL_POLLDESC, 'description', $editorConfigs);
277
        $pollForm->addElement($desc_text);
278
279
        $author = new \XoopsUser($this->getVar('user_id'));
0 ignored issues
show
Unused Code introduced by
The assignment to $author is dead and can be removed.
Loading history...
Bug introduced by
It seems like $this->getVar('user_id') can also be of type boolean and string; however, parameter $id of XoopsUser::__construct() does only seem to accept array|null, 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

279
        $author = new \XoopsUser(/** @scrutinizer ignore-type */ $this->getVar('user_id'));
Loading history...
280
281
        /* setup time variables */
282
        $timeTray = new \XoopsFormElementTray(\_AM_XOOPSPOLL_POLL_TIMES, '&nbsp;&nbsp;', 'time_tray');
283
284
        $xuCurrentTimestamp = \xoops_getUserTimestamp(\time());
285
        $xuCurrentFormatted = \ucfirst(\date(_MEDIUMDATESTRING, (int)$xuCurrentTimestamp));
286
        $xuStartTimestamp   = \xoops_getUserTimestamp($this->getVar('start_time'));
287
        $xuEndTimestamp     = \xoops_getUserTimestamp($this->getVar('end_time'));
288
289
        /* display start/end time fields on form */
290
        $startTimeText = new FormDateTimePicker("<div class='bold'>" . \_AM_XOOPSPOLL_START_TIME . '<br>' . "<span class='x-small'>" . \_AM_XOOPSPOLL_FORMAT . '<br>' . \sprintf(\_AM_XOOPSPOLL_CURRENTTIME, $xuCurrentFormatted) . '</span></div>', 'xu_start_time', 20, $xuStartTimestamp);
291
        if ($this->hasExpired()) {
292
            /*
293
                        $extra = "";
294
                        foreach ($addHidden as $key=>$value) {
295
                            $extra="&amp;{$key}={$value}";
296
                        }
297
298
                        $xuEndFormattedTime = ucfirst(date(_MEDIUMDATESTRING, $xuEndTimestamp));
299
                        $endTimeText = new \XoopsFormLabel("<div class='bold middle'>" . _AM_XOOPSPOLL_EXPIRATION,
300
                                         sprintf(_AM_XOOPSPOLL_EXPIREDAT, $xuEndFormattedTime)
301
                                       . "<br><a href='{$rtnPage}?op=restart&amp;poll_id="
302
                                       . $this->getVar('poll_id') . "{$extra}'>" . _AM_XOOPSPOLL_RESTART . "</a></div>");
303
                    }
304
            */
305
            $extra              = \is_array($addHidden) ? $addHidden : [];
0 ignored issues
show
introduced by
The condition is_array($addHidden) is always true.
Loading history...
306
            $extra              = \array_merge($extra, ['op' => 'restart', 'poll_id' => $this->getVar('poll_id')]);
307
            $query              = \http_build_query($extra, '', '&');
308
            $query              = \htmlentities($query, \ENT_QUOTES);
309
            $xuEndFormattedTime = \ucfirst(\date(_MEDIUMDATESTRING, $xuEndTimestamp));
310
            $endTimeText        = new \XoopsFormLabel("<div class='bold middle'>" . \_AM_XOOPSPOLL_EXPIRATION, \sprintf(\_AM_XOOPSPOLL_EXPIREDAT, $xuEndFormattedTime) . "<br><a href='{$rtnPage}?{$query}'>" . \_AM_XOOPSPOLL_RESTART . '</a></div>');
311
        } else {
312
            $endTimeText = new FormDateTimePicker("<div class='bold middle'>" . \_AM_XOOPSPOLL_EXPIRATION . '</div>', 'xu_end_time', 20, $xuEndTimestamp);
313
        }
314
315
        $timeTray->addElement($startTimeText);
316
        $timeTray->addElement($endTimeText, true);
317
        $pollForm->addElement($timeTray);
318
        /* allow anonymous voting */
319
        //        $pollForm->addElement(new \XoopsFormRadioYN(_AM_XOOPSPOLL_ALLOWANONYMOUS, 'anonymous', $this->getVar('anonymous')));
320
        $temp = new \XoopsFormRadioYN(\_AM_XOOPSPOLL_ALLOWANONYMOUS, 'anonymous', $this->getVar('anonymous'));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('anonymous') can also be of type array and array; however, parameter $value of XoopsFormRadioYN::__construct() 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

320
        $temp = new \XoopsFormRadioYN(\_AM_XOOPSPOLL_ALLOWANONYMOUS, 'anonymous', /** @scrutinizer ignore-type */ $this->getVar('anonymous'));
Loading history...
321
        $pollForm->addElement($temp);
322
        /* add poll options to the form */
323
        $pollForm->addElement(new \XoopsFormLabel(\_AM_XOOPSPOLL_OPTION_SETTINGS, "<hr class='center'>"));
324
        $multiCount = ($this->getVar('multiple') > 0) ? $this->getVar('multiple') : '';
0 ignored issues
show
Unused Code introduced by
The assignment to $multiCount is dead and can be removed.
Loading history...
325
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_ALLOWMULTI, 'multiple', $this->getVar('multiple')));
326
327
        /* add multiple selection limit to multiple selection polls */
328
        $multiLimit = new \XoopsFormText(\_AM_XOOPSPOLL_MULTI_LIMIT . '<br><small>' . \_AM_XOOPSPOLL_MULTI_LIMIT_DESC . '</small>', 'multilimit', 6, 5, $this->getVar('multilimit'));
329
        $pollForm->addElement($multiLimit);
330
331
        $optionHandler = Helper::getInstance()->getHandler('Option');
332
        $optionTray    = $optionHandler->renderOptionFormTray($this->getVar('poll_id'));
333
        $pollForm->addElement($optionTray);
334
335
        /* add preferences to the form */
336
        $pollForm->addElement(new \XoopsFormLabel(\_AM_XOOPSPOLL_PREFERENCES, "<hr class='center'>"));
337
        $visSelect = new \XoopsFormSelect(\_AM_XOOPSPOLL_BLIND, 'visibility', $this->getVar('visibility'), 1, false);
338
        /**
339
         * {@internal Do NOT add/delete from $vis_options after the module has been installed}
340
         */
341
        \xoops_loadLanguage('main', 'xoopspoll');
342
        $visSelect->addOptionArray(Utility::getVisibilityArray());
343
        $pollForm->addElement($visSelect);
344
        $notifyValue = (Constants::POLL_MAILED !== $this->getVar('mail_status')) ? Constants::NOTIFICATION_ENABLED : Constants::NOTIFICATION_DISABLED;
345
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_NOTIFY, 'notify', $notifyValue));
346
347
        // Add "notify voter" in the form
348
        $mail_voter_yn = new \XoopsFormRadioYN(\_AM_XOOPSPOLL_NOTIFY_VOTER, 'mail_voter', $this->getVar('mail_voter'));
349
        $pollForm->addElement($mail_voter_yn);
350
351
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_DISPLAYBLOCK, 'display', $this->getVar('display')));
352
353
        foreach ($addHidden as $key => $value) {
354
            $pollForm->addElement(new \XoopsFormHidden($key, $value));
355
        }
356
        $pollForm->addElement(new \XoopsFormHidden('op', 'update'));
357
        $pollForm->addElement(new \XoopsFormHidden('poll_id', $this->getVar('poll_id')));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('poll_id') can also be of type array and array; however, parameter $value of XoopsFormHidden::__construct() 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

357
        $pollForm->addElement(new \XoopsFormHidden('poll_id', /** @scrutinizer ignore-type */ $this->getVar('poll_id')));
Loading history...
358
        $pollForm->addElement(new \XoopsFormHidden('user_id', $this->getVar('user_id')));
359
        $pollForm->addElement(new \XoopsFormButtonTray('submit', _SUBMIT, null, null, true));
360
361
        //        $pollForm->addElement(new \XoopsFormButtonTray( "form_submit", _SUBMIT, "submit", "", true));
362
        return $pollForm->display();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $pollForm->display() targeting XoopsForm::display() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
363
    }
364
365
    /**
366
     * Method determines if current user can view the results of this poll
367
     * @return bool|string visibility of this poll's results (true if visible, msg if not)
368
     */
369
    public function isResultVisible()
370
    {
371
        $visibleMsg = '';
372
        \xoops_loadLanguage('main', 'xoopspoll');
373
        switch ($this->getVar('visibility')) {
374
            case Constants::HIDE_ALWAYS:  // always hide the results
375
            default:
376
                $isVisible  = false;
377
                $visibleMsg = \_MD_XOOPSPOLL_HIDE_ALWAYS_MSG;
378
                break;
379
            case Constants::HIDE_END:  // hide the results until the poll ends
380
                if ($this->hasExpired()) {
381
                    $isVisible = true;
382
                } else {
383
                    $visibleMsg = \_MD_XOOPSPOLL_HIDE_END_MSG;
384
                    $isVisible  = false;
385
                }
386
                break;
387
            case Constants::HIDE_VOTED: // hide the results until user votes
388
                $logHandler = Helper::getInstance()->getHandler('Log');
389
                $uid        = (($GLOBALS['xoopsUser'] instanceof \XoopsUser)
390
                               && ($GLOBALS['xoopsUser']->getVar('uid') > 0)) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
391
                if ($this->isAllowedToVote()
392
                    && $logHandler->hasVoted($this->getVar('poll_id'), \xoops_getenv('REMOTE_ADDR'), $uid)) {
393
                    $isVisible = true;
394
                } else {
395
                    $visibleMsg = \_MD_XOOPSPOLL_HIDE_VOTED_MSG;
396
                    $isVisible  = false;
397
                }
398
                break;
399
            case Constants::HIDE_NEVER:  // never hide the results - always show
400
                $isVisible = true;
401
                break;
402
        }
403
404
        return $isVisible ? true : $visibleMsg;
405
    }
406
407
    /**
408
     * Send copy of vote to the user at time of vote (if selected)
409
     *
410
     * @param \XoopsUser|null $user the Xoops user object for this user
411
     * @return bool      send status
412
     */
413
    public function notifyVoter(\XoopsUser $user = null): bool
414
    {
415
        if (($user instanceof \XoopsUser) && (Constants::MAIL_POLL_TO_VOTER === $this->getVar('mail_voter'))) {
416
            \xoops_loadLanguage('main', 'xoopspoll');
417
            $xoopsMailer = \xoops_getMailer();
418
            $xoopsMailer->useMail();
419
            $helper = Helper::getInstance();
420
421
            $language         = $GLOBALS['xoopsConfig']['language'];
422
            $templateDir      = $helper->path('language/' . $language . '/mail_template/');
423
            $templateFilename = 'mail_voter.tpl';
424
            if (!\file_exists($templateDir . $templateFilename)) {
425
                $language = 'english';
0 ignored issues
show
Unused Code introduced by
The assignment to $language is dead and can be removed.
Loading history...
426
            }
427
428
            $xoopsMailer->setTemplateDir($templateDir);
429
            $xoopsMailer->setTemplate($templateFilename);
430
431
            $author = new \XoopsUser($this->getVar('user_id'));
0 ignored issues
show
Bug introduced by
It seems like $this->getVar('user_id') can also be of type boolean and string; however, parameter $id of XoopsUser::__construct() does only seem to accept array|null, 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

431
            $author = new \XoopsUser(/** @scrutinizer ignore-type */ $this->getVar('user_id'));
Loading history...
432
            $xoopsMailer->setFromUser($author);
433
            $xoopsMailer->setToUsers($user);
434
435
            $xoopsMailer->assign('POLL_QUESTION', $this->getVar('question'));
436
437
            $xuEndTimestamp     = \xoops_getUserTimestamp($this->getVar('end_time'));
438
            $xuEndFormattedTime = \ucfirst(\date(_MEDIUMDATESTRING, (int)$xuEndTimestamp));
439
            // on the outside chance this expired right after the user voted.
440
            if ($this->hasExpired()) {
441
                $xoopsMailer->assign('POLL_END', \sprintf(\_MD_XOOPSPOLL_ENDED_AT, $xuEndFormattedTime));
442
            } else {
443
                $xoopsMailer->assign('POLL_END', \sprintf(\_MD_XOOPSPOLL_ENDS_ON, $xuEndFormattedTime));
444
            }
445
446
            $visibleText = '';
447
            switch ($this->getVar('visibility')) {
448
                case Constants::HIDE_ALWAYS:  // always hide the results - election mode
449
                default:
450
                    break;
451
                case Constants::HIDE_END:  // hide the results until the poll ends
452
                    $visibleText = \_MD_XOOPSPOLL_SEE_AFTER;
453
                    if ($this->hasExpired()) {
454
                        $visibleText = \_MD_XOOPSPOLL_SEE_AT;
455
                    }
456
                    break;
457
                case Constants::HIDE_VOTED: // hide the results until user votes
458
                case Constants::HIDE_NEVER:  // never hide the results - always show
459
                    $visibleText = \_MD_XOOPSPOLL_SEE_AT;
460
                    break;
461
            }
462
            $xoopsMailer->assign('POLL_VISIBLE', $visibleText);
463
            if (!empty($visibleText)) {
464
                $xoopsMailer->assign('LOCATION', $GLOBALS['xoops']->url('modules/xoopspoll/pollresults.php?poll_id=' . $this->getVar('poll_id')));
465
            } else {
466
                $xoopsMailer->assign('LOCATION', '');
467
            }
468
469
            $xoopsMailer->assign('POLL_ID', $this->getVar('poll_id'));
470
            $xoopsMailer->assign('SITENAME', $GLOBALS['xoopsConfig']['sitename']);
471
            $xoopsMailer->assign('ADMINMAIL', $GLOBALS['xoopsConfig']['adminmail']);
472
            $xoopsMailer->assign('SITEURL', $GLOBALS['xoops']->url());
473
474
            $xoopsMailer->setSubject(\sprintf(\_MD_XOOPSPOLL_YOURVOTEAT, $user->uname(), $GLOBALS['xoopsConfig']['sitename']));
475
            $status = $xoopsMailer->send();
476
        } else {
477
            $status = false;
478
        }
479
480
        return $status;
481
    }
482
483
    /**
484
     * The following method is provided for backward compatibility with newbb/xforum
485
     * deletes the object from the database
486
     * @return mixed results of deleting poll from db
487
     * @deprecated since Xoopspoll 1.40, please use PollHandler & Poll
488
     */    public function delete(): mixed
489
    {
490
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
491
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use PollHandler::' . __METHOD__ . ' instead.' . ". Called from {$trace[0]['file']}line {$trace[0]['line']}");
492
        $pollHandler = $this->getStaticPollHandler();
493
494
        return $pollHandler->delete($this->poll);
0 ignored issues
show
Bug introduced by
The property poll does not exist on XoopsModules\Xoopspoll\Poll. Did you mean poll_id?
Loading history...
495
    }
496
497
    /**
498
     * update the vote counter for this poll
499
     * @returns bool results of update counter
500
     * @deprecated since Xoopspoll 1.40, please use PollHandler & Poll
501
     */
502
    public function updateCount()
503
    {
504
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
505
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use PollHandler::' . __METHOD__ . ' instead.' . ". Called from {$trace[0]['file']}line {$trace[0]['line']}");
506
        $pollHandler = $this->getStaticPollHandler();
507
508
        return $pollHandler->updateCount($this->poll->getVar('poll_id'));
0 ignored issues
show
Bug introduced by
The property poll does not exist on XoopsModules\Xoopspoll\Poll. Did you mean poll_id?
Loading history...
509
    }
510
511
    /**
512
     * inserts the poll object into the database
513
     * @return mixed results of inserting poll into db
514
     * @deprecated since Xoopspoll 1.40, please use PollHandler & Poll
515
     */
516
    public function store(): mixed
517
    {
518
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
519
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use PollHandler::insert() instead.' . ". Called from {$trace[0]['file']}line {$trace[0]['line']}");
520
        $pollHandler = $this->getStaticPollHandler();
521
522
        return $pollHandler->insert($this->poll);
0 ignored issues
show
Bug introduced by
The property poll does not exist on XoopsModules\Xoopspoll\Poll. Did you mean poll_id?
Loading history...
523
    }
524
525
    /**
526
     * Set up a static Poll Handler for use by class methods
527
     */
528
    private function getStaticPollHandler()
529
    {
530
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
531
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use Poll and PollHandler classes instead.' . ". Called from {$trace[0]['file']}line {$trace[0]['line']}");
532
        static $pH;
533
534
        if (!isset($pH)) {
535
            $pH = Helper::getInstance()->getHandler('Poll');
536
        }
537
538
        return $pH;
539
    }
540
    /**#@-*/
541
}
542