Passed
Pull Request — master (#18)
by Michael
02:44
created

Poll   F

Complexity

Total Complexity 61

Size/Duplication

Total Lines 499
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 259
c 0
b 0
f 0
dl 0
loc 499
rs 3.52
wmc 61

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 4 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 35 11
B notifyVoter() 0 68 11
A hasExpired() 0 8 2
C vote() 0 44 14
A isAllowedToVote() 0 11 5
B renderForm() 0 140 7
A getComments() 0 13 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
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 http://www.fsf.org/copyleft/gpl.html GNU public license}
19
 * @package   ::    xoopspoll
20
 * @subpackage:: class
21
 * @since     ::         1.40
22
 * @author    ::     zyspec <[email protected]>
23
 */
24
25
26
 /**
27
 * Class Poll
28
 * @package XoopsModules\Xoopspoll
29
 */
30
class Poll extends \XoopsObject
31
{
32
    /**
33
     * Poll::__construct()
34
     *
35
     * @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...
36
     */
37
    public function __construct($id = null)
38
    {
39
        parent::__construct();
40
        //        $timestamp = xoops_getUserTimestamp(time());
41
        $current_timestamp = \time();
42
        $this->initVar('poll_id', \XOBJ_DTYPE_INT, null, false);
43
        $this->initVar('question', \XOBJ_DTYPE_TXTBOX, null, true, 255);
44
        $this->initVar('description', \XOBJ_DTYPE_TXTAREA, null, false);
45
        $this->initVar('user_id', \XOBJ_DTYPE_INT, null, false);
46
        $this->initVar('start_time', \XOBJ_DTYPE_INT, $current_timestamp, false);
47
        $this->initVar('end_time', \XOBJ_DTYPE_INT, $current_timestamp + Constants::DEFAULT_POLL_DURATION, true);
48
        $this->initVar('votes', \XOBJ_DTYPE_INT, 0, false);
49
        $this->initVar('voters', \XOBJ_DTYPE_INT, 0, false);
50
        $this->initVar('display', \XOBJ_DTYPE_INT, Constants::DISPLAY_POLL_IN_BLOCK, false);
51
        $this->initVar('visibility', \XOBJ_DTYPE_INT, Constants::HIDE_NEVER, false);
52
        $this->initVar('anonymous', \XOBJ_DTYPE_INT, Constants::ANONYMOUS_VOTING_DISALLOWED, false);
53
        $this->initVar('weight', \XOBJ_DTYPE_INT, Constants::DEFAULT_WEIGHT, false);
54
        $this->initVar('multiple', \XOBJ_DTYPE_INT, Constants::NOT_MULTIPLE_SELECT_POLL, false);
55
        $this->initVar('multilimit', \XOBJ_DTYPE_INT, Constants::MULTIPLE_SELECT_LIMITLESS, false);
56
        $this->initVar('mail_status', \XOBJ_DTYPE_INT, Constants::POLL_NOT_MAILED, false);
57
        $this->initVar('mail_voter', \XOBJ_DTYPE_INT, Constants::NOT_MAIL_POLL_TO_VOTER, false);
58
59
        /**
60
         * {@internal This code added to support previous versions of newbb/xForum}
61
         */
62
        if (!empty($id)) {
63
            $trace   = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
64
            $err_msg = __CLASS__ . " instantiation with 'id' set is deprecated since Xoopspoll 1.40, please use PollHandler instead." . " Called from {$trace[0]['file']}line {$trace[0]['line']}";
65
            if (isset($GLOBALS['xoopsLogger'])) {
66
                $GLOBALS['xoopsLogger']->addDeprecated($err_msg);
67
            } else {
68
                \trigger_error($err_msg, \E_USER_WARNING);
69
            }
70
71
            if (\is_array($id)) {
72
                $this->assignVars($id);
73
            } else {
74
                $pollHandler = Helper::getInstance()->getHandler('Poll');
75
                $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

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

194
        /** @scrutinizer ignore-call */ 
195
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
Loading history...
195
196
        $commentHandler = \xoops_getHandler('comment');
197
        $criteria       = new \CriteriaCompo();
198
        $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

198
        $criteria->add(new \Criteria('com_itemid', /** @scrutinizer ignore-type */ $this->getVar('poll_id'), '='));
Loading history...
199
        $criteria->add(new \Criteria('com_modid', $pollModule->getVar('mid'), '='));
200
        $commentCount = $commentHandler->getCount($criteria);
0 ignored issues
show
Bug introduced by
The method getCount() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of said class. However, the method does not exist in XoopsGroupHandler or XoopsConfigCategoryHandler or XoopsRankHandler or XoopsConfigOptionHandler or XoopsBlockHandler or XoopsImagesetHandler. Are you sure you never get one of those? ( Ignorable by Annotation )

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

200
        /** @scrutinizer ignore-call */ 
201
        $commentCount = $commentHandler->getCount($criteria);
Loading history...
201
        $commentCount = (int)$commentCount;
202
203
        return $commentCount;
204
    }
205
206
    /**
207
     * display the poll form
208
     * @param string $rtnPage   where to send the form result
209
     * @param string $rtnMethod return method  get|post
210
     * @param array  $addHidden
211
     */
212
    public function renderForm($rtnPage, $rtnMethod = 'post', $addHidden = [])
213
    {
214
        \xoops_load('xoopsformloader');
215
        $myts = \MyTextSanitizer::getInstance();
216
217
        $rtnMethod = mb_strtolower($rtnMethod);
218
        // force form to use xoopsSecurity if it's a 'post' form
219
        $rtnSecurity = 'post' === mb_strtolower($rtnMethod);
220
221
        //  set form titles, etc. depending on if it's a new object or not
222
        if ($this->isNew()) {
223
            $formTitle = \_AM_XOOPSPOLL_CREATENEWPOLL;
224
            $this->setVar('user_id', $GLOBALS['xoopsUser']->getVar('uid'));
225
        } else {
226
            $formTitle = \_AM_XOOPSPOLL_EDITPOLL;
227
        }
228
229
        /*  create the form */
230
        $pollForm    = new \XoopsThemeForm(\ucwords($formTitle), 'poll_form', $rtnPage, $rtnMethod, $rtnSecurity);
231
        $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>');
232
        $pollForm->addElement($authorLabel);
233
        $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

233
        $pollForm->addElement(new \XoopsFormText(\_AM_XOOPSPOLL_DISPLAYORDER, 'weight', 6, 5, /** @scrutinizer ignore-type */ $this->getVar('weight')));
Loading history...
234
        $questionText = new \XoopsFormText(\_AM_XOOPSPOLL_POLLQUESTION, 'question', 50, 255, $this->getVar('question', 'E'));
235
        $pollForm->addElement($questionText, true);
236
        /*
237
                $descTarea = new \XoopsFormTextarea(_AM_XOOPSPOLL_POLLDESC, "description", $this->getVar('description', 'E'));
238
                $pollForm->addElement($descTarea);
239
        */
240
        $moduleHandler = \xoops_getHandler('module');
241
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
0 ignored issues
show
Unused Code introduced by
The assignment to $pollModule is dead and can be removed.
Loading history...
242
243
        /** @var \XoopsModuleHandler $moduleHandler */
244
        $moduleHandler = \xoops_getHandler('module');
245
        $configHandler = \xoops_getHandler('config');
246
        //        $xp_module      = $moduleHandler->getByDirname("xoopspoll");
247
        //        $module_id      = $xp_module->getVar("mid");
248
        //        $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
249
        $sys_module = $moduleHandler->getByDirname('system');
250
        $sys_id     = $sys_module->getVar('mid');
251
        $sys_config = $configHandler->getConfigsByCat(0, $sys_id);
0 ignored issues
show
Bug introduced by
The method getConfigsByCat() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

251
        /** @scrutinizer ignore-call */ 
252
        $sys_config = $configHandler->getConfigsByCat(0, $sys_id);
Loading history...
252
253
        $editorConfigs = [
254
            //                           'editor' => $GLOBALS['xoopsModuleConfig']['useeditor'],
255
            //                           'editor' => $xp_config['useeditor'],
256
            'editor' => $sys_config['general_editor'],
257
            'rows'   => 15,
258
            'cols'   => 60,
259
            'width'  => '100%',
260
            'height' => '350px',
261
            'name'   => 'description',
262
            //                           'value'  => $myts->stripSlashesGPC($this->getVar('description'))
263
            'value'  => $myts->htmlSpecialChars($this->getVar('description')),
264
        ];
265
        $desc_text     = new \XoopsFormEditor(\_AM_XOOPSPOLL_POLLDESC, 'description', $editorConfigs);
266
        $pollForm->addElement($desc_text);
267
268
        $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

268
        $author = new \XoopsUser(/** @scrutinizer ignore-type */ $this->getVar('user_id'));
Loading history...
269
270
        /* setup time variables */
271
        $timeTray = new \XoopsFormElementTray(\_AM_XOOPSPOLL_POLL_TIMES, '&nbsp;&nbsp;', 'time_tray');
272
273
        $xuCurrentTimestamp = \xoops_getUserTimestamp(\time());
274
        $xuCurrentFormatted = \ucfirst(\date(_MEDIUMDATESTRING, $xuCurrentTimestamp));
275
        $xuStartTimestamp   = \xoops_getUserTimestamp($this->getVar('start_time'));
276
        $xuEndTimestamp     = \xoops_getUserTimestamp($this->getVar('end_time'));
277
278
        /* display start/end time fields on form */
279
        $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);
280
        if (!$this->hasExpired()) {
281
            $endTimeText = new FormDateTimePicker("<div class='bold middle'>" . \_AM_XOOPSPOLL_EXPIRATION . '</div>', 'xu_end_time', 20, $xuEndTimestamp);
282
        } else {
283
            /*
284
                        $extra = "";
285
                        foreach ($addHidden as $key=>$value) {
286
                            $extra="&amp;{$key}={$value}";
287
                        }
288
289
                        $xuEndFormattedTime = ucfirst(date(_MEDIUMDATESTRING, $xuEndTimestamp));
290
                        $endTimeText = new \XoopsFormLabel("<div class='bold middle'>" . _AM_XOOPSPOLL_EXPIRATION,
291
                                         sprintf(_AM_XOOPSPOLL_EXPIREDAT, $xuEndFormattedTime)
292
                                       . "<br><a href='{$rtnPage}?op=restart&amp;poll_id="
293
                                       . $this->getVar('poll_id') . "{$extra}'>" . _AM_XOOPSPOLL_RESTART . "</a></div>");
294
                    }
295
            */
296
            $extra              = \is_array($addHidden) ? $addHidden : [];
0 ignored issues
show
introduced by
The condition is_array($addHidden) is always true.
Loading history...
297
            $extra              = \array_merge($extra, ['op' => 'restart', 'poll_id' => $this->getVar('poll_id')]);
298
            $query              = \http_build_query($extra);
299
            $query              = \htmlentities($query, \ENT_QUOTES);
300
            $xuEndFormattedTime = \ucfirst(\date(_MEDIUMDATESTRING, $xuEndTimestamp));
301
            $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>');
302
        }
303
304
        $timeTray->addElement($startTimeText);
305
        $timeTray->addElement($endTimeText, true);
306
        $pollForm->addElement($timeTray);
307
        /* allow anonymous voting */
308
        //        $pollForm->addElement(new \XoopsFormRadioYN(_AM_XOOPSPOLL_ALLOWANONYMOUS, 'anonymous', $this->getVar('anonymous')));
309
        $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

309
        $temp = new \XoopsFormRadioYN(\_AM_XOOPSPOLL_ALLOWANONYMOUS, 'anonymous', /** @scrutinizer ignore-type */ $this->getVar('anonymous'));
Loading history...
310
        $pollForm->addElement($temp);
311
        /* add poll options to the form */
312
        $pollForm->addElement(new \XoopsFormLabel(\_AM_XOOPSPOLL_OPTION_SETTINGS, "<hr class='center'>"));
313
        $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...
314
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_ALLOWMULTI, 'multiple', $this->getVar('multiple')));
315
316
        /* add multiple selection limit to multiple selection polls */
317
        $multiLimit = new \XoopsFormText(\_AM_XOOPSPOLL_MULTI_LIMIT . '<br><small>' . \_AM_XOOPSPOLL_MULTI_LIMIT_DESC . '</small>', 'multilimit', 6, 5, $this->getVar('multilimit'));
318
        $pollForm->addElement($multiLimit);
319
320
        $optionHandler = Helper::getInstance()->getHandler('Option');
321
        $optionTray    = $optionHandler->renderOptionFormTray($this->getVar('poll_id'));
322
        $pollForm->addElement($optionTray);
323
324
        /* add preferences to the form */
325
        $pollForm->addElement(new \XoopsFormLabel(\_AM_XOOPSPOLL_PREFERENCES, "<hr class='center'>"));
326
        $visSelect = new \XoopsFormSelect(\_AM_XOOPSPOLL_BLIND, 'visibility', $this->getVar('visibility'), 1, false);
327
        /**
328
         * {@internal Do NOT add/delete from $vis_options after the module has been installed}
329
         */
330
        \xoops_loadLanguage('main', 'xoopspoll');
331
        $visSelect->addOptionArray(Utility::getVisibilityArray());
332
        $pollForm->addElement($visSelect);
333
        $notifyValue = (Constants::POLL_MAILED !== $this->getVar('mail_status')) ? Constants::NOTIFICATION_ENABLED : Constants::NOTIFICATION_DISABLED;
334
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_NOTIFY, 'notify', $notifyValue));
335
336
        // Add "notify voter" in the form
337
        $mail_voter_yn = new \XoopsFormRadioYN(\_AM_XOOPSPOLL_NOTIFY_VOTER, 'mail_voter', $this->getVar('mail_voter'));
338
        $pollForm->addElement($mail_voter_yn);
339
340
        $pollForm->addElement(new \XoopsFormRadioYN(\_AM_XOOPSPOLL_DISPLAYBLOCK, 'display', $this->getVar('display')));
341
342
        foreach ($addHidden as $key => $value) {
343
            $pollForm->addElement(new \XoopsFormHidden($key, $value));
344
        }
345
        $pollForm->addElement(new \XoopsFormHidden('op', 'update'));
346
        $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

346
        $pollForm->addElement(new \XoopsFormHidden('poll_id', /** @scrutinizer ignore-type */ $this->getVar('poll_id')));
Loading history...
347
        $pollForm->addElement(new \XoopsFormHidden('user_id', $this->getVar('user_id')));
348
        $pollForm->addElement(new \XoopsFormButtonTray('submit', _SUBMIT, null, null, true));
349
350
        //        $pollForm->addElement(new \XoopsFormButtonTray( "form_submit", _SUBMIT, "submit", "", true));
351
        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...
352
    }
353
354
    /**
355
     * Method determines if current user can view the results of this poll
356
     * @return mixed visibility of this poll's results (true if visible, msg if not)
357
     */
358
    public function isResultVisible()
359
    {
360
        \xoops_loadLanguage('main', 'xoopspoll');
361
        switch ($this->getVar('visibility')) {
362
            case Constants::HIDE_ALWAYS:  // always hide the results
363
            default:
364
                $isVisible  = false;
365
                $visibleMsg = \_MD_XOOPSPOLL_HIDE_ALWAYS_MSG;
366
                break;
367
            case Constants::HIDE_END:  // hide the results until the poll ends
368
                if (!$this->hasExpired()) {
369
                    $visibleMsg = \_MD_XOOPSPOLL_HIDE_END_MSG;
370
                    $isVisible  = false;
371
                } else {
372
                    $isVisible = true;
373
                }
374
                break;
375
            case Constants::HIDE_VOTED: // hide the results until user votes
376
                $logHandler = Helper::getInstance()->getHandler('Log');
377
                $uid        = (($GLOBALS['xoopsUser'] instanceof \XoopsUser)
378
                               && ($GLOBALS['xoopsUser']->getVar('uid') > 0)) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
379
                if ($this->isAllowedToVote()
380
                    && $logHandler->hasVoted($this->getVar('poll_id'), \xoops_getenv('REMOTE_ADDR'), $uid)) {
381
                    $isVisible = true;
382
                } else {
383
                    $visibleMsg = \_MD_XOOPSPOLL_HIDE_VOTED_MSG;
384
                    $isVisible  = false;
385
                }
386
                break;
387
            case Constants::HIDE_NEVER:  // never hide the results - always show
388
                $isVisible = true;
389
                break;
390
        }
391
392
        return $isVisible ? true : $visibleMsg;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $visibleMsg does not seem to be defined for all execution paths leading up to this point.
Loading history...
393
    }
394
395
    /**
396
     * Send copy of vote to the user at time of vote (if selected)
397
     *
398
     * @param null $user the Xoops user object for this user
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $user is correct as it would always require null to be passed?
Loading history...
399
     * @return bool      send status
400
     */
401
    public function notifyVoter($user = null)
402
    {
403
        if (($user instanceof \XoopsUser) && (Constants::MAIL_POLL_TO_VOTER === $this->getVar('mail_voter'))) {
404
            \xoops_loadLanguage('main', 'xoopspoll');
405
            $xoopsMailer = \xoops_getMailer();
406
            $xoopsMailer->useMail();
407
            $helper = Helper::getInstance();
408
409
            $language         = $GLOBALS['xoopsConfig']['language'];
410
            $templateDir      = $helper->path('language/' . $language . '/mail_template/');
411
            $templateFilename = 'mail_voter.tpl';
412
            if (!\file_exists($templateDir . $templateFilename)) {
413
                $language = 'english';
0 ignored issues
show
Unused Code introduced by
The assignment to $language is dead and can be removed.
Loading history...
414
            }
415
416
            $xoopsMailer->setTemplateDir($templateDir);
417
            $xoopsMailer->setTemplate($templateFilename);
418
419
            $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

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