Passed
Pull Request — master (#18)
by Michael
04:31
created

Poll   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 512
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 259
c 0
b 0
f 0
dl 0
loc 512
rs 3.44
wmc 62

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 4 1
A delete() 0 7 1
A store() 0 7 1
A __construct() 0 41 4
A getStaticPollHandler() 0 11 2
A updateCount() 0 7 1
B isResultVisible() 0 35 11
A Poll() 0 3 1
B notifyVoter() 0 67 11
A hasExpired() 0 8 2
C vote() 0 44 14
A isAllowedToVote() 0 11 5
B renderForm() 0 143 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
use XoopsModules\Xoopspoll;
26
27
 /**
28
 * Class Poll
29
 * @package XoopsModules\Xoopspoll
30
 */
31
class Poll extends \XoopsObject
32
{
33
    /**
34
     * Poll::__construct()
35
     *
36
     * @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...
37
     */
38
    public function __construct($id = null)
39
    {
40
        parent::__construct();
41
        //        $timestamp = xoops_getUserTimestamp(time());
42
        $current_timestamp = \time();
43
        //        xoops_load('constants', 'xoopspoll');
44
        $this->initVar('poll_id', \XOBJ_DTYPE_INT, null, false);
45
        $this->initVar('question', \XOBJ_DTYPE_TXTBOX, null, true, 255);
46
        $this->initVar('description', \XOBJ_DTYPE_TXTAREA, null, false);
47
        $this->initVar('user_id', \XOBJ_DTYPE_INT, null, false);
48
        $this->initVar('start_time', \XOBJ_DTYPE_INT, $current_timestamp, false);
49
        $this->initVar('end_time', \XOBJ_DTYPE_INT, $current_timestamp + Constants::DEFAULT_POLL_DURATION, true);
50
        $this->initVar('votes', \XOBJ_DTYPE_INT, 0, false);
51
        $this->initVar('voters', \XOBJ_DTYPE_INT, 0, false);
52
        $this->initVar('display', \XOBJ_DTYPE_INT, Constants::DISPLAY_POLL_IN_BLOCK, false);
53
        $this->initVar('visibility', \XOBJ_DTYPE_INT, Constants::HIDE_NEVER, false);
54
        $this->initVar('anonymous', \XOBJ_DTYPE_INT, Constants::ANONYMOUS_VOTING_DISALLOWED, false);
55
        $this->initVar('weight', \XOBJ_DTYPE_INT, Constants::DEFAULT_WEIGHT, false);
56
        $this->initVar('multiple', \XOBJ_DTYPE_INT, Constants::NOT_MULTIPLE_SELECT_POLL, false);
57
        $this->initVar('multilimit', \XOBJ_DTYPE_INT, Constants::MULTIPLE_SELECT_LIMITLESS, false);
58
        $this->initVar('mail_status', \XOBJ_DTYPE_INT, Constants::POLL_NOT_MAILED, false);
59
        $this->initVar('mail_voter', \XOBJ_DTYPE_INT, Constants::NOT_MAIL_POLL_TO_VOTER, false);
60
61
        /**
62
         * {@internal This code added to support previous versions of newbb/xForum}
63
         */
64
        if (!empty($id)) {
65
            $trace   = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
66
            $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']}";
67
            if (isset($GLOBALS['xoopsLogger'])) {
68
                $GLOBALS['xoopsLogger']->addDeprecated($err_msg);
69
            } else {
70
                \trigger_error($err_msg, \E_USER_WARNING);
71
            }
72
73
            if (\is_array($id)) {
74
                $this->assignVars($id);
75
            } else {
76
                $pollHandler = Xoopspoll\Helper::getInstance()->getHandler('Poll');
77
                $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

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

206
        /** @scrutinizer ignore-call */ 
207
        $pollModule    = $moduleHandler->getByDirname('xoopspoll');
Loading history...
207
208
        $commentHandler = \xoops_getHandler('comment');
209
        $criteria       = new \CriteriaCompo();
210
        $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

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

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

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

266
        /** @scrutinizer ignore-call */ 
267
        $sys_config = $configHandler->getConfigsByCat(0, $sys_id);
Loading history...
267
268
        $editorConfigs = [
269
            //                           'editor' => $GLOBALS['xoopsModuleConfig']['useeditor'],
270
            //                           'editor' => $xp_config['useeditor'],
271
            'editor' => $sys_config['general_editor'],
272
            'rows'   => 15,
273
            'cols'   => 60,
274
            'width'  => '100%',
275
            'height' => '350px',
276
            'name'   => 'description',
277
            //                           'value'  => $myts->stripSlashesGPC($this->getVar('description'))
278
            'value'  => $myts->htmlSpecialChars($this->getVar('description')),
279
        ];
280
        $desc_text     = new \XoopsFormEditor(\_AM_XOOPSPOLL_POLLDESC, 'description', $editorConfigs);
281
        $pollForm->addElement($desc_text);
282
283
        $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

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

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

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

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