xoopspollBlockSinglepollEdit()   D
last analyzed

Complexity

Conditions 16
Paths 80

Size

Total Lines 143
Code Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 16
eloc 96
c 1
b 0
f 0
nc 80
nop 1
dl 0
loc 143
rs 4.5406

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 declare(strict_types=1);
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
 This program is distributed in the hope that it will be useful,
7
 but WITHOUT ANY WARRANTY; without even the implied warranty of
8
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
 */
10
11
/**
12
 * XoopsPoll Single Poll Block Definition (clonable)
13
 *
14
 * @copyright ::  {@link https://xoops.org/ XOOPS Project}
15
 * @license   :: {@link https://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2.0 or later}
16
 * @subpackage:: blocks
17
 * @since     :: 1.40
18
 */
19
20
use XoopsModules\Newbb;
21
use XoopsModules\Xoopspoll\{
22
    Constants,
23
    Helper,
24
    Poll,
25
    Utility
26
};
27
28
xoops_loadLanguage('main', 'xoopspoll');
29
30
/*
31
require_once $GLOBALS['xoops']->path( "modules"
32
                                    . "/xoopspoll"
33
                                    . "/class"
34
                                    . "/pollutility.php"
35
);
36
*/
37
/**
38
 * Display a single XOOPS Polls in a block
39
 *
40
 * @param mixed  $options
41
 * @return array block keys and values to be used by block template
42
 * @global mixed $GLOBALS ['xoopsUser']
43
 * @uses   CriteriaCompo
44
 * @uses   Criteria
45
 * @uses   xoops_getUserTimestamp() function to convert time to user time
46
 * @uses   formatTimestamp() takes timestamp and converts to human-readable format
47
 */
48
function xoopspollBlockSinglepollShow(mixed $options): array
49
{
50
    $block = [];
51
52
    /** @var \XoopsConfigHandler $configHandler */
53
    $configHandler = xoops_getHandler('config');
54
    $pollHandler   = Helper::getInstance()->getHandler('Poll');
55
    /** @var \XoopsModuleHandler $moduleHandler */
56
    $moduleHandler    = xoops_getHandler('module');
57
    $thisModule       = $moduleHandler->getByDirname('xoopspoll');
58
    $thisModuleConfig = $configHandler->getConfigsByCat(0, $thisModule->getVar('mid'));
59
60
    /* if admin hasn't initialized block then we'll pick a poll for them
61
     * provided that one exists in the database
62
     */
63
    if (0 === $options[1]) {
64
        $criteria = null;
65
        /**
66
         * check to see if we want to include polls created with forum (newbb)
67
         */
68
        if ($thisModuleConfig['hide_forum_polls']
69
            && ($thisModule instanceof \XoopsModule)
70
            && $thisModule->isactive()) {
71
            $newbbModule = $moduleHandler->getByDirname('newbb');
72
            if ($newbbModule instanceof \XoopsModule && $newbbModule->isactive()) {
73
                /** @var Newbb\TopicHandler $topicHandler */
74
                $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
75
                $tFields      = ['topic_id', 'poll_id'];
76
                $tArray       = $topicHandler->getAll(new \Criteria('topic_haspoll', 0, '>'), $tFields, false);
77
                if (!empty($tArray)) {
78
                    $tcriteria = [];
79
                    foreach ($tArray as $t) {
80
                        $tcriteria[] = $t['poll_id'];
81
                    }
82
                    if (!empty($tcriteria)) {
83
                        $tstring  = '(' . implode(',', $tcriteria) . ')';
84
                        $criteria = new \Criteria('poll_id', $tstring, 'NOT IN');
85
                    }
86
                }
87
                unset($topicHandler, $tFields, $tArray);
88
            }
89
            unset($newbbModule);
90
        }
91
92
        if ($pollHandler->getCount($criteria) > 0) {
93
            $pollIdArray = $pollHandler->getIds();
94
            $thisId      = array_shift($pollIdArray);
95
            $pollObj     = $pollHandler->get($thisId);
96
        } else {
97
            return $block;
98
        }
99
    } else {
100
        $pollObj = $pollHandler->get((int)$options[1]);
101
    }
102
103
    if ($pollObj instanceof Poll) {
104
        if ((1 === $options[0]) || !$pollObj->hasExpired()) {
105
            $block['langVote']        = _MD_XOOPSPOLL_VOTE;
106
            $block['langResults']     = _MD_XOOPSPOLL_RESULTS;
107
            $block['langExpires']     = _MB_XOOPSPOLL_WILLEXPIRE;
108
            $block['langExpired']     = _MB_XOOPSPOLL_HASEXPIRED;
109
            $block['langComments']    = _MB_XOOPSPOLL_COMMENTS;
110
            $block['langComment']     = _MB_XOOPSPOLL_COMMENT;
111
            $block['showResultsLink'] = $options[2];
112
            $block['asList']          = $options[3];
113
            $block['thisModuleDir']   = 'xoopspoll';
114
            $block['url']             = 'http' . (!empty($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
115
            $block['dispVotes']       = $thisModuleConfig['disp_vote_nums'];
116
117
            $optionHandler = Helper::getInstance()->getHandler('Option');
118
119
            $pollVars = $pollObj->getValues();
120
            $criteria = new \CriteriaCompo();
121
            $criteria->add(new \Criteria('poll_id', $pollVars['poll_id'], '='));
122
            $criteria->setSort('option_id');
123
            $optionsObjArray = $optionHandler->getAll($criteria);
124
            //            $optionsObjArray = $optionHandler->getAll($criteria, null, false);
125
126
            if (Constants::MULTIPLE_SELECT_POLL === $pollVars['multiple']) {
127
                $pollOptionType = 'checkbox';
128
                $pollOptionName = 'option_id[]';
129
            } else {
130
                $pollOptionType = 'radio';
131
                $pollOptionName = 'option_id';
132
            }
133
134
            $uid = 0;
135
            if (isset($GLOBALS['xoopsUser']) && ($GLOBALS['xoopsUser'] instanceof \XoopsUser)) {
136
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
137
            }
138
139
            $totalVotes       = $pollVars['votes'];
140
            $logHandler       = Helper::getInstance()->getHandler('Log');
141
            $hasVoted         = (bool)$logHandler->hasVoted($pollVars['poll_id'], xoops_getenv('REMOTE_ADDR'), $uid);
142
            $canVote          = (!$hasVoted) && $pollObj->isAllowedToVote();
143
            $pollOptionsArray = [];
144
            foreach ($optionsObjArray as $optionObj) {
145
                $percent = ($totalVotes > 0) ? (100 * $optionObj->getVar('option_count') / $totalVotes) : 0;
146
                //                $percent = ($totalVotes > 0) ? ceil(100 * $optionObj->getVar('option_count') / $totalVotes) . '%' : '0%';
147
                /*@TODO::  Change block templates to use Smarty html_options to support this... then comment
148
                           out old $pollOptionsArray assignment
149
                $pollOptionsArray[] = array('options' => array($optionObj['option_id'] => $optionObj['option_text']),
150
                                              'count' => $optionObj['option_count'],
151
                                            'percent' => $percent,
152
                                              'color' => $optionObj['option_color']
153
                ); */
154
                $pollOptionsArray[] = [
155
                    'id'      => $optionObj->getVar('option_id'),
156
                    'text'    => $optionObj->getVar('option_text'),
157
                    'count'   => $optionObj->getVar('option_count'),
158
                    'percent' => sprintf(' %01.1f%%', $percent),
159
                    'color'   => $optionObj->getVar('option_color'),
160
                ];
161
            }
162
163
            $xuEndTimestamp     = xoops_getUserTimestamp($pollObj->getVar('end_time'));
164
            $xuEndFormattedTime = ucfirst(date(_MEDIUMDATESTRING, (int)$xuEndTimestamp));
165
166
            $isVisible = true === $pollObj->isResultVisible();
167
168
            $multiple   = (bool)$pollVars['multiple'];
169
            $multiLimit = (int)$pollVars['multilimit'];
170
            $lang_multi = '';
171
            if ($multiple && ($multiLimit > 0)) {
172
                $lang_multi = sprintf(_MB_XOOPSPOLL_MULTITEXT, $multiLimit);
173
            }
174
175
            $block['id']          = $pollVars['poll_id'];
176
            $block['visible']     = $isVisible;
177
            $block['question']    = $pollVars['question'];
178
            $block['multiple']    = $multiple;
179
            $block['lang_multi']  = $lang_multi;
180
            $block['optionType']  = $pollOptionType;
181
            $block['optionName']  = $pollOptionName;
182
            $block['options']     = $pollOptionsArray;
183
            $block['hasExpired']  = $pollObj->hasExpired();
184
            $block['votes']       = $pollVars['votes'];
185
            $block['hasVoted']    = $hasVoted;
186
            $block['canVote']     = $canVote;
187
            $block['totalVotes']  = sprintf(_MD_XOOPSPOLL_TOTALVOTES, $totalVotes);
188
            $block['endTime']     = $xuEndFormattedTime; // formatted output for current user
189
            $block['comments']    = $pollObj->getComments($pollVars['poll_id']);
0 ignored issues
show
Unused Code introduced by
The call to XoopsModules\Xoopspoll\Poll::getComments() has too many arguments starting with $pollVars['poll_id']. ( Ignorable by Annotation )

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

189
            /** @scrutinizer ignore-call */ 
190
            $block['comments']    = $pollObj->getComments($pollVars['poll_id']);

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...
190
            $block['commentMode'] = Utility::commentMode();
191
192
            unset($optionsObjArray, $pollOptionsArray, $pollObj, $pollVars, $timeArray);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $timeArray seems to be never defined.
Loading history...
193
        }
194
    }
195
196
    return $block;
197
}
198
199
/**
200
 * Display a form to edit poll block display option
201
 *
202
 * @param mixed  $options
203
 * @return string HTML form for display by block admin
204
 * @global mixed $GLOBALS ['xoopsUser']
205
 * @uses   xoops_getModuleHandler() function to get class handler for this modules class(es)
206
 */
207
function xoopspollBlockSinglepollEdit(mixed $options): string
208
{
209
    /**
210
     * Options[]
211
     *            0 = show expired polls in block
212
     *            1 = poll id to show
213
     *              if hiding expired poll then the next non-expired poll
214
     *              will show if the selected poll is hidden
215
     *          2 = show results button in block
216
     *          3 = show options as list|select
217
     */
218
219
    // find out if you want to show expired polls in block
220
    // (otherwise it will hide block once it expires)
221
    if (0 === $options[0]) {
222
        $chk0no  = ' checked';
223
        $chk0yes = '';
224
    } else {
225
        $chk0no  = '';
226
        $chk0yes = ' checked';
227
    }
228
    $form = "<table><tr><td class='width25 middle'>"
229
            . _MB_XOOPSPOLL_SHOW_EXP
230
            . ':</td><td>'
231
            . "<label class='middle' for='yes'>"
232
            . _YES
233
            . "</label>\n"
234
            . "<input type='radio' name='options[0]' value='1'{$chk0yes} id='yes'>\n"
235
            . "<label class='middle' style='margin-left: 2em;' for='no'>&nbsp;&nbsp;&nbsp;"
236
            . _NO
237
            . "</label>\n"
238
            . "<input type='radio' name='options[0]' value='0'{$chk0no} id='no'>\n"
239
            . "</td></tr>\n";
240
241
    $pollHandler = Helper::getInstance()->getHandler('Poll');
242
    $pollFields  = ['poll_id', 'start_time', 'end_time', 'question', 'weight'];
243
    $criteria    = new \CriteriaCompo();
244
    //    $criteria->add(new \Criteria('end_time', time(), '>'));
245
    $criteria->setOrder('ASC');
246
    $criteria->setSort('weight');
247
    /**
248
     * Note that you can select polls that have not started yet, so they will automatically show
249
     * up in the block once they have started.  To only allow selection of active polls uncomment
250
     * the following line in the code - this could be made a module config option if desired
251
     */
252
253
    // $criteria->add(new \Criteria('start_time', time(), '<='));
254
255
    /**
256
     * now check to see if we want to hide polls that were created using newbb
257
     */
258
    /** @var \XoopsConfigHandler $configHandler */
259
    $configHandler = xoops_getHandler('config');
260
    /** @var \XoopsModuleHandler $moduleHandler */
261
    $moduleHandler    = xoops_getHandler('module');
262
    $thisModule       = $moduleHandler->getByDirname('xoopspoll');
263
    $thisModuleConfig = $configHandler->getConfigsByCat(0, $thisModule->getVar('mid'));
264
265
    if ($thisModuleConfig['hide_forum_polls'] && ($thisModule instanceof \XoopsModule) && $thisModule->isactive()) {
266
        $newbbModule = $moduleHandler->getByDirname('newbb');
267
        if ($newbbModule instanceof \XoopsModule && $newbbModule->isactive()) {
268
            /** @var Newbb\TopicHandler $topicHandler */
269
            $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
270
            $tFields      = ['topic_id', 'poll_id'];
271
            $tArray       = $topicHandler->getAll(new \Criteria('topic_haspoll', 0, '>'), $tFields, false);
272
            if (!empty($tArray)) {
273
                $tcriteria = [];
274
                foreach ($tArray as $t) {
275
                    $tcriteria[] = $t['poll_id'];
276
                }
277
                if (!empty($tcriteria)) {
278
                    $tstring = '(' . implode(',', $tcriteria) . ')';
279
                    $criteria->add(new \Criteria('poll_id', $tstring, 'NOT IN'));
280
                }
281
            }
282
            unset($topicHandler, $tFields, $tArray);
283
        }
284
        unset($newbbModule);
285
    }
286
287
    $allPollsArray = $pollHandler->getAll($criteria, $pollFields, false);
288
289
    // next get a list of all available polls for select box
290
    $form .= '<tr><td>' . _MB_XOOPSPOLL_POLLS . ":</td><td style='text-align: left; margin-left: 1em;'>\n";
291
    if (empty($allPollsArray)) {
292
        $form .= "<span class='errorMsg'>" . _MB_XOOPSPOLL_NONE_ACTIVE . '</span>';
293
    } else {
294
        $form .= "<select name='options[1]'>\n";
295
        foreach ($allPollsArray as $thisPoll) {
296
            $selected       = ($thisPoll['poll_id'] === $options[1]) ? ' selected' : '';
297
            $taggedQuestion = ($thisPoll['end_time'] < time()) ? $thisPoll['question'] . '**' : $thisPoll['question'];
298
            $form           .= "  <option value='" . $thisPoll['poll_id'] . "'{$selected}>" . $taggedQuestion . "</option>\n";
299
        }
300
        $form .= "</select>\n" . '&nbsp;** - ' . _MB_XOOPSPOLL_EXPIRED_INDICATOR . "\n";
301
    }
302
    if (0 === $options[2]) {
303
        $chk2no  = ' checked';
304
        $chk2yes = '';
305
    } else {
306
        $chk2no  = '';
307
        $chk2yes = ' checked';
308
    }
309
    $form .= "</td></tr>\n"
310
             . "<tr><td class='width25 middle'>"
311
             . _MB_XOOPSPOLL_SHOW_RESULT_LINK
312
             . ':</td><td>'
313
             . "<label class='middle' for='yesr'>"
314
             . _YES
315
             . "</label>\n"
316
             . "<input type='radio' name='options[2]' value='1'{$chk2yes} id='yesr'>\n"
317
             . "<label class='middle' style='margin-left: 2em;' for='nor'>&nbsp;&nbsp;&nbsp;"
318
             . _NO
319
             . "</label>\n"
320
             . "<input type='radio' name='options[2]' value='0'{$chk2no} id='nor'>\n"
321
             . "</td></tr>\n";
322
323
    /* find out if you want to show options as a list or as a select box */
324
    if (Constants::POLL_OPTIONS_SELECT === $options[3]) {
325
        $chk3select = ' checked';
326
        $chk3list   = '';
327
    } else {
328
        $chk3select = '';
329
        $chk3list   = ' checked';
330
    }
331
    $form .= "<table><tr><td class='width25 middle'>"
332
             . _MB_XOOPSPOLL_SHOW_OPTIONS
333
             . ':</td><td>'
334
             . "<label class='middle' for='list'>"
335
             . _MB_XOOPSPOLL_LIST
336
             . "</label>\n"
337
             . "<input type='radio' name='options[3]' value='"
338
             . Constants::POLL_OPTIONS_LIST
339
             . "'{$chk3list} id='list'>\n"
340
             . "<label class='middle' style='margin-left: 2em;' for='select'>&nbsp;&nbsp;&nbsp;"
341
             . _MB_XOOPSPOLL_SELECT
342
             . "</label>\n"
343
             . "<input type='radio' name='options[3]' value='"
344
             . Constants::POLL_OPTIONS_SELECT
345
             . "'{$chk3select} id='select'>\n"
346
             . "</td></tr>\n"
347
             . "</table>\n";
348
349
    return $form;
350
}
351