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

Poll::notifyVoter()   B

Complexity

Conditions 11
Paths 49

Size

Total Lines 68
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 50
c 0
b 0
f 0
nc 49
nop 1
dl 0
loc 68
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        //        xoops_load('constants', 'xoopspoll');
43
        $this->initVar('poll_id', \XOBJ_DTYPE_INT, null, false);
44
        $this->initVar('question', \XOBJ_DTYPE_TXTBOX, null, true, 255);
45
        $this->initVar('description', \XOBJ_DTYPE_TXTAREA, null, false);
46
        $this->initVar('user_id', \XOBJ_DTYPE_INT, null, false);
47
        $this->initVar('start_time', \XOBJ_DTYPE_INT, $current_timestamp, false);
48
        $this->initVar('end_time', \XOBJ_DTYPE_INT, $current_timestamp + Constants::DEFAULT_POLL_DURATION, true);
49
        $this->initVar('votes', \XOBJ_DTYPE_INT, 0, false);
50
        $this->initVar('voters', \XOBJ_DTYPE_INT, 0, false);
51
        $this->initVar('display', \XOBJ_DTYPE_INT, Constants::DISPLAY_POLL_IN_BLOCK, false);
52
        $this->initVar('visibility', \XOBJ_DTYPE_INT, Constants::HIDE_NEVER, false);
53
        $this->initVar('anonymous', \XOBJ_DTYPE_INT, Constants::ANONYMOUS_VOTING_DISALLOWED, false);
54
        $this->initVar('weight', \XOBJ_DTYPE_INT, Constants::DEFAULT_WEIGHT, false);
55
        $this->initVar('multiple', \XOBJ_DTYPE_INT, Constants::NOT_MULTIPLE_SELECT_POLL, false);
56
        $this->initVar('multilimit', \XOBJ_DTYPE_INT, Constants::MULTIPLE_SELECT_LIMITLESS, false);
57
        $this->initVar('mail_status', \XOBJ_DTYPE_INT, Constants::POLL_NOT_MAILED, false);
58
        $this->initVar('mail_voter', \XOBJ_DTYPE_INT, Constants::NOT_MAIL_POLL_TO_VOTER, false);
59
60
        /**
61
         * {@internal This code added to support previous versions of newbb/xForum}
62
         */
63
        if (!empty($id)) {
64
            $trace   = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
65
            $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']}";
66
            if (isset($GLOBALS['xoopsLogger'])) {
67
                $GLOBALS['xoopsLogger']->addDeprecated($err_msg);
68
            } else {
69
                \trigger_error($err_msg, \E_USER_WARNING);
70
            }
71
72
            if (\is_array($id)) {
73
                $this->assignVars($id);
74
            } else {
75
                $pollHandler = Helper::getInstance()->getHandler('Poll');
76
                $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

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

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

199
        $criteria->add(new \Criteria('com_itemid', /** @scrutinizer ignore-type */ $this->getVar('poll_id'), '='));
Loading history...
200
        $criteria->add(new \Criteria('com_modid', $pollModule->getVar('mid'), '='));
201
        $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

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

237
        $pollForm->addElement(new \XoopsFormText(\_AM_XOOPSPOLL_DISPLAYORDER, 'weight', 6, 5, /** @scrutinizer ignore-type */ $this->getVar('weight')));
Loading history...
238
        $questionText = new \XoopsFormText(\_AM_XOOPSPOLL_POLLQUESTION, 'question', 50, 255, $this->getVar('question', 'E'));
239
        $pollForm->addElement($questionText, true);
240
        /*
241
                $descTarea = new \XoopsFormTextarea(_AM_XOOPSPOLL_POLLDESC, "description", $this->getVar('description', 'E'));
242
                $pollForm->addElement($descTarea);
243
        */
244
        $moduleHandler = \xoops_getHandler('module');
245
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
0 ignored issues
show
Unused Code introduced by
The assignment to $pollModule is dead and can be removed.
Loading history...
246
247
        /** @var \XoopsModuleHandler $moduleHandler */
248
        $moduleHandler = \xoops_getHandler('module');
249
        $configHandler = \xoops_getHandler('config');
250
        //        $xp_module      = $moduleHandler->getByDirname("xoopspoll");
251
        //        $module_id      = $xp_module->getVar("mid");
252
        //        $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
253
        $sys_module = $moduleHandler->getByDirname('system');
254
        $sys_id     = $sys_module->getVar('mid');
255
        $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

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

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

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

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

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