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

xoopspollBlockSinglepollShow()   F

Complexity

Conditions 25
Paths 785

Size

Total Lines 148
Code Lines 100

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 25
eloc 100
c 1
b 0
f 0
nc 785
nop 1
dl 0
loc 148
rs 0.2388

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
 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 http://www.fsf.org/copyleft/gpl.html GNU public license}
16
 * @package   :: xoopspoll
17
 * @subpackage:: blocks
18
 * @since     :: 1.40
19
 */
20
21
use XoopsModules\Newbb;
22
use XoopsModules\Xoopspoll\{
23
    Constants,
24
    Helper,
25
    Poll,
26
    Utility
27
};
28
29
xoops_loadLanguage('main', 'xoopspoll');
30
31
/*
32
require_once $GLOBALS['xoops']->path( "modules"
33
                                    . "/xoopspoll"
34
                                    . "/class"
35
                                    . "/pollutility.php"
36
);
37
*/
38
/**
39
 * Display a single XOOPS Polls in a block
40
 *
41
 * @access public
42
 * @param mixed  $options
43
 * @return array block keys and values to be used by block template
44
 * @global mixed $GLOBALS ['xoopsUser']
45
 * @uses   CriteriaCompo
46
 * @uses   Criteria
47
 * @uses   xoops_getUserTimestamp() function to convert time to user time
48
 * @uses   formatTimestamp() takes timestamp and converts to human readable format
49
 */
50
function xoopspollBlockSinglepollShow($options)
51
{
52
    $block = [];
53
54
    $configHandler      = xoops_getHandler('config');
55
    $pollHandler   = Helper::getInstance()->getHandler('Poll');
56
    /** @var \XoopsModuleHandler $moduleHandler */
57
    $moduleHandler = xoops_getHandler('module');
58
    $thisModule         = $moduleHandler->getByDirname('xoopspoll');
59
    $this_module_config = $configHandler->getConfigsByCat(0, $thisModule->getVar('mid'));
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

59
    /** @scrutinizer ignore-call */ 
60
    $this_module_config = $configHandler->getConfigsByCat(0, $thisModule->getVar('mid'));
Loading history...
60
61
    /* if admin hasn't initialized block then we'll pick a poll for them
62
     * provided that one exists in the database
63
     */
64
    if (0 === $options[1]) {
65
        $criteria = null;
66
        /**
67
         * check to see if we want to include polls created with forum (newbb)
68
         */
69
        if ($this_module_config['hide_forum_polls']
70
            && ($thisModule instanceof \XoopsModule)
71
            && $thisModule->isactive()) {
72
            $newbbModule = $moduleHandler->getByDirname('newbb');
73
            if ($newbbModule instanceof \XoopsModule && $newbbModule->isactive()) {
74
                /** @var Newbb\TopicHandler $topicHandler */
75
                $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
76
                $tFields      = ['topic_id', 'poll_id'];
77
                $tArray       = $topicHandler->getAll(new \Criteria('topic_haspoll', 0, '>'), $tFields, false);
78
                if (!empty($tArray)) {
79
                    $tcriteria = [];
80
                    foreach ($tArray as $t) {
81
                        $tcriteria[] = $t['poll_id'];
82
                    }
83
                    if (!empty($tcriteria)) {
84
                        $tstring  = '(' . implode(',', $tcriteria) . ')';
85
                        $criteria = new \Criteria('poll_id', $tstring, 'NOT IN');
86
                    }
87
                }
88
                unset($topicHandler, $tFields, $tArray);
89
            }
90
            unset($newbbModule);
91
        }
92
93
        if ($pollHandler->getCount($criteria) > 0) {
94
            $pollIdArray = $pollHandler->getIds();
95
            $thisId      = array_shift($pollIdArray);
96
            $pollObj     = $pollHandler->get($thisId);
97
        } else {
98
            return $block;
99
        }
100
    } else {
101
        $pollObj = $pollHandler->get((int)$options[1]);
102
    }
103
104
    if ($pollObj instanceof Poll) {
105
        if ((1 === $options[0]) || !$pollObj->hasExpired()) {
106
            $block['langVote']        = _MD_XOOPSPOLL_VOTE;
107
            $block['langResults']     = _MD_XOOPSPOLL_RESULTS;
108
            $block['langExpires']     = _MB_XOOPSPOLL_WILLEXPIRE;
109
            $block['langExpired']     = _MB_XOOPSPOLL_HASEXPIRED;
110
            $block['langComments']    = _MB_XOOPSPOLL_COMMENTS;
111
            $block['langComment']     = _MB_XOOPSPOLL_COMMENT;
112
            $block['showResultsLink'] = $options[2];
113
            $block['asList']          = $options[3];
114
            $block['thisModuleDir']   = 'xoopspoll';
115
            $block['url']             = 'http' . (!empty($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
116
            $block['dispVotes']       = $this_module_config['disp_vote_nums'];
117
118
            $optionHandler = Helper::getInstance()->getHandler('Option');
119
120
            $pollVars = $pollObj->getValues();
121
            $criteria = new \CriteriaCompo();
122
            $criteria->add(new \Criteria('poll_id', $pollVars['poll_id'], '='));
123
            $criteria->setSort('option_id');
124
            $optionsObjArray = $optionHandler->getAll($criteria);
125
            //            $optionsObjArray = $optionHandler->getAll($criteria, null, false);
126
127
            if (Constants::MULTIPLE_SELECT_POLL === $pollVars['multiple']) {
128
                $pollOptionType = 'checkbox';
129
                $pollOptionName = 'option_id[]';
130
            } else {
131
                $pollOptionType = 'radio';
132
                $pollOptionName = 'option_id';
133
            }
134
135
                $uid = 0;
136
            if (isset($GLOBALS['xoopsUser']) && ($GLOBALS['xoopsUser'] instanceof \XoopsUser)) {
137
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
138
            }
139
140
            $totalVotes       = $pollVars['votes'];
141
            $logHandler       = Helper::getInstance()->getHandler('Log');
142
            $hasVoted         = $logHandler->hasVoted($pollVars['poll_id'], xoops_getenv('REMOTE_ADDR'), $uid) ? true : false;
143
            $canVote          = (!$hasVoted) && $pollObj->isAllowedToVote();
144
            $pollOptionsArray = [];
145
            foreach ($optionsObjArray as $optionObj) {
146
                $percent = ($totalVotes > 0) ? (100 * $optionObj->getVar('option_count') / $totalVotes) : 0;
147
                //                $percent = ($totalVotes > 0) ? ceil(100 * $optionObj->getVar('option_count') / $totalVotes) . '%' : '0%';
148
                /*@TODO::  Change block templates to use Smarty html_options to support this... then comment
149
                           out old $pollOptionsArray assignment
150
                $pollOptionsArray[] = array('options' => array($optionObj['option_id'] => $optionObj['option_text']),
151
                                              'count' => $optionObj['option_count'],
152
                                            'percent' => $percent,
153
                                              'color' => $optionObj['option_color']
154
                ); */
155
                $pollOptionsArray[] = [
156
                    'id'      => $optionObj->getVar('option_id'),
157
                    'text'    => $optionObj->getVar('option_text'),
158
                    'count'   => $optionObj->getVar('option_count'),
159
                    'percent' => sprintf(' %01.1f%%', $percent),
160
                    'color'   => $optionObj->getVar('option_color'),
161
                ];
162
            }
163
164
            $xuEndTimestamp     = xoops_getUserTimestamp($pollObj->getVar('end_time'));
165
            $xuEndFormattedTime = ucfirst(date(_MEDIUMDATESTRING, $xuEndTimestamp));
166
167
            $isVisible = true === $pollObj->isResultVisible();
168
169
            $multiple   = $pollVars['multiple'] ? true : false;
170
            $multiLimit = (int)$pollVars['multilimit'];
171
            $lang_multi = '';
172
            if ($multiple && ($multiLimit > 0)) {
173
                $lang_multi = sprintf(_MB_XOOPSPOLL_MULTITEXT, $multiLimit);
174
            }
175
176
            $block['id']          = $pollVars['poll_id'];
177
            $block['visible']     = $isVisible;
178
            $block['question']    = $pollVars['question'];
179
            $block['multiple']    = $multiple;
180
            $block['lang_multi']  = $lang_multi;
181
            $block['optionType']  = $pollOptionType;
182
            $block['optionName']  = $pollOptionName;
183
            $block['options']     = $pollOptionsArray;
184
            $block['hasExpired']  = $pollObj->hasExpired();
185
            $block['votes']       = $pollVars['votes'];
186
            $block['hasVoted']    = $hasVoted;
187
            $block['canVote']     = $canVote;
188
            $block['totalVotes']  = sprintf(_MD_XOOPSPOLL_TOTALVOTES, $totalVotes);
189
            $block['endTime']     = $xuEndFormattedTime; // formatted output for current user
190
            $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

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