Passed
Pull Request — master (#18)
by Michael
04:31
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
use XoopsModules\Xoopspoll\Constants;
24
25
xoops_loadLanguage('main', 'xoopspoll');
26
//xoops_load('pollUtility', 'xoopspoll');
27
/*
28
require_once $GLOBALS['xoops']->path( "modules"
29
                                    . "/xoopspoll"
30
                                    . "/class"
31
                                    . "/pollutility.php"
32
);
33
*/
34
/**
35
 * Display a single XOOPS Polls in a block
36
 *
37
 * @access public
38
 * @param mixed  $options
39
 * @return array block keys and values to be used by block template
40
 * @global mixed $GLOBALS ['xoopsUser']
41
 * @uses   CriteriaCompo
42
 * @uses   Criteria
43
 * @uses   xoops_getUserTimestamp() function to convert time to user time
44
 * @uses   formatTimestamp() takes timestamp and converts to human readable format
45
 */
46
function xoopspollBlockSinglepollShow($options)
47
{
48
    $block = [];
49
50
    $configHandler      = xoops_getHandler('config');
51
    $pollHandler   = Xoopspoll\Helper::getInstance()->getHandler('Poll');
52
    /** @var \XoopsModuleHandler $moduleHandler */
53
    $moduleHandler = xoops_getHandler('module');
54
    $thisModule         = $moduleHandler->getByDirname('xoopspoll');
55
    $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

55
    /** @scrutinizer ignore-call */ 
56
    $this_module_config = $configHandler->getConfigsByCat(0, $thisModule->getVar('mid'));
Loading history...
56
57
    /* if admin hasn't initialized block then we'll pick a poll for them
58
     * provided that one exists in the database
59
     */
60
    if (0 === $options[1]) {
61
        $criteria = null;
62
        /**
63
         * check to see if we want to include polls created with forum (newbb)
64
         */
65
        if ($this_module_config['hide_forum_polls']
66
            && ($thisModule instanceof \XoopsModule)
67
            && $thisModule->isactive()) {
68
            $newbbModule = $moduleHandler->getByDirname('newbb');
69
            if ($newbbModule instanceof \XoopsModule && $newbbModule->isactive()) {
70
                /** @var Newbb\TopicHandler $topicHandler */
71
                $topicHandler = Newbb\Helper::getInstance()->getHandler('Topic');
0 ignored issues
show
Bug introduced by
The type XoopsModules\Newbb\Helper 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...
72
                $tFields      = ['topic_id', 'poll_id'];
73
                $tArray       = $topicHandler->getAll(new \Criteria('topic_haspoll', 0, '>'), $tFields, false);
74
                if (!empty($tArray)) {
75
                    $tcriteria = [];
76
                    foreach ($tArray as $t) {
77
                        $tcriteria[] = $t['poll_id'];
78
                    }
79
                    if (!empty($tcriteria)) {
80
                        $tstring  = '(' . implode(',', $tcriteria) . ')';
81
                        $criteria = new \Criteria('poll_id', $tstring, 'NOT IN');
82
                    }
83
                }
84
                unset($topicHandler, $tFields, $tArray);
85
            }
86
            unset($newbbModule);
87
        }
88
89
        if ($pollHandler->getCount($criteria) > 0) {
90
            $pollIdArray = $pollHandler->getIds();
91
            $thisId      = array_shift($pollIdArray);
92
            $pollObj     = $pollHandler->get($thisId);
93
        } else {
94
            return $block;
95
        }
96
    } else {
97
        $pollObj = $pollHandler->get((int)$options[1]);
98
    }
99
100
    if ($pollObj instanceof \Xoopspoll\Poll) {
0 ignored issues
show
Bug introduced by
The type Xoopspoll\Poll 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...
101
        if ((1 === $options[0]) || !$pollObj->hasExpired()) {
0 ignored issues
show
Bug introduced by
The method hasExpired() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

101
        if ((1 === $options[0]) || !$pollObj->/** @scrutinizer ignore-call */ hasExpired()) {
Loading history...
102
            $block['langVote']        = _MD_XOOPSPOLL_VOTE;
103
            $block['langResults']     = _MD_XOOPSPOLL_RESULTS;
104
            $block['langExpires']     = _MB_XOOPSPOLL_WILLEXPIRE;
105
            $block['langExpired']     = _MB_XOOPSPOLL_HASEXPIRED;
106
            $block['langComments']    = _MB_XOOPSPOLL_COMMENTS;
107
            $block['langComment']     = _MB_XOOPSPOLL_COMMENT;
108
            $block['showResultsLink'] = $options[2];
109
            $block['asList']          = $options[3];
110
            $block['thisModuleDir']   = 'xoopspoll';
111
            $block['url']             = 'http' . (!empty($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
112
            $block['dispVotes']       = $this_module_config['disp_vote_nums'];
113
114
            $optionHandler = Xoopspoll\Helper::getInstance()->getHandler('Option');
115
116
            $pollVars = $pollObj->getValues();
117
            $criteria = new \CriteriaCompo();
118
            $criteria->add(new \Criteria('poll_id', $pollVars['poll_id'], '='));
119
            $criteria->setSort('option_id');
120
            $optionsObjArray = $optionHandler->getAll($criteria);
121
            //            $optionsObjArray = $optionHandler->getAll($criteria, null, false);
122
123
            if (Constants::MULTIPLE_SELECT_POLL === $pollVars['multiple']) {
124
                $pollOptionType = 'checkbox';
125
                $pollOptionName = 'option_id[]';
126
            } else {
127
                $pollOptionType = 'radio';
128
                $pollOptionName = 'option_id';
129
            }
130
131
                $uid = 0;
132
            if (isset($GLOBALS['xoopsUser']) && ($GLOBALS['xoopsUser'] instanceof \XoopsUser)) {
133
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
134
            }
135
136
            $totalVotes       = $pollVars['votes'];
137
            $logHandler       = Xoopspoll\Helper::getInstance()->getHandler('Log');
138
            $hasVoted         = $logHandler->hasVoted($pollVars['poll_id'], xoops_getenv('REMOTE_ADDR'), $uid) ? true : false;
139
            $canVote          = (!$hasVoted) && $pollObj->isAllowedToVote();
0 ignored issues
show
Bug introduced by
The method isAllowedToVote() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

139
            $canVote          = (!$hasVoted) && $pollObj->/** @scrutinizer ignore-call */ isAllowedToVote();
Loading history...
140
            $pollOptionsArray = [];
141
            foreach ($optionsObjArray as $optionObj) {
142
                $percent = ($totalVotes > 0) ? (100 * $optionObj->getVar('option_count') / $totalVotes) : 0;
143
                //                $percent = ($totalVotes > 0) ? ceil(100 * $optionObj->getVar('option_count') / $totalVotes) . '%' : '0%';
144
                /*@TODO::  Change block templates to use Smarty html_options to support this... then comment
145
                           out old $pollOptionsArray assignment
146
                $pollOptionsArray[] = array('options' => array($optionObj['option_id'] => $optionObj['option_text']),
147
                                              'count' => $optionObj['option_count'],
148
                                            'percent' => $percent,
149
                                              'color' => $optionObj['option_color']
150
                ); */
151
                $pollOptionsArray[] = [
152
                    'id'      => $optionObj->getVar('option_id'),
153
                    'text'    => $optionObj->getVar('option_text'),
154
                    'count'   => $optionObj->getVar('option_count'),
155
                    'percent' => sprintf(' %01.1f%%', $percent),
156
                    'color'   => $optionObj->getVar('option_color'),
157
                ];
158
            }
159
160
            $xuEndTimestamp     = xoops_getUserTimestamp($pollObj->getVar('end_time'));
161
            $xuEndFormattedTime = ucfirst(date(_MEDIUMDATESTRING, $xuEndTimestamp));
162
163
            $isVisible = true === $pollObj->isResultVisible();
0 ignored issues
show
Bug introduced by
The method isResultVisible() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

163
            $isVisible = true === $pollObj->/** @scrutinizer ignore-call */ isResultVisible();
Loading history...
164
165
            $multiple   = $pollVars['multiple'] ? true : false;
166
            $multiLimit = (int)$pollVars['multilimit'];
167
            $lang_multi = '';
168
            if ($multiple && ($multiLimit > 0)) {
169
                $lang_multi = sprintf(_MB_XOOPSPOLL_MULTITEXT, $multiLimit);
170
            }
171
172
            $block['id']          = $pollVars['poll_id'];
173
            $block['visible']     = $isVisible;
174
            $block['question']    = $pollVars['question'];
175
            $block['multiple']    = $multiple;
176
            $block['lang_multi']  = $lang_multi;
177
            $block['optionType']  = $pollOptionType;
178
            $block['optionName']  = $pollOptionName;
179
            $block['options']     = $pollOptionsArray;
180
            $block['hasExpired']  = $pollObj->hasExpired();
181
            $block['votes']       = $pollVars['votes'];
182
            $block['hasVoted']    = $hasVoted;
183
            $block['canVote']     = $canVote;
184
            $block['totalVotes']  = sprintf(_MD_XOOPSPOLL_TOTALVOTES, $totalVotes);
185
            $block['endTime']     = $xuEndFormattedTime; // formatted output for current user
186
            $block['comments']    = $pollObj->getComments($pollVars['poll_id']);
0 ignored issues
show
Bug introduced by
The method getComments() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

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