Completed
Pull Request — master (#568)
by Michael
06:11
created

XoopsGTicket::XoopsGTicket()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 6
nop 0
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
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
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
/**
13
 * Protector
14
 *
15
 * @copyright       XOOPS Project (http://xoops.org)
16
 * @license         GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
17
 * @package         protector
18
 * @author          trabis <[email protected]>
19
 * @version         $Id$
20
 */
21
22
// GIJOE's Ticket Class (based on Marijuana's Oreteki XOOPS)
23
// nobunobu's suggestions are applied
24
25
if (!class_exists('XoopsGTicket')) {
26
    class XoopsGTicket
27
    {
28
        public $_errors = array();
29
        public $_latest_token = '';
30
        public $messages = array();
31
32
        public function __construct()
33
        {
34
            $xoops = Xoops::getInstance();
35
            $language = $xoops->getConfig('language');
36
37
            // language file
38
            if ($language && !strstr($language, '/')) {
39
                if (XoopsLoad::fileExists(dirname(__DIR__) . '/language/' . $language . '/gticket_messages.phtml')) {
40
                    include dirname(__DIR__) . '/language/' . $language . '/gticket_messages.phtml';
41
                }
42
            }
43
44
            // default messages
45
            if (empty($this->messages)) {
46
                $this->messages = array(
47
                    'err_general' => 'GTicket Error', 'err_nostubs' => 'No stubs found',
48
                    'err_noticket' => 'No ticket found', 'err_nopair' => 'No valid ticket-stub pair found',
49
                    'err_timeout' => 'Time out', 'err_areaorref' => 'Invalid area or referer',
50
                    'fmt_prompt4repost' => 'error(s) found:<br><span style="background-color:red;font-weight:bold;color:white;">%s</span><br>Confirm it.<br>And do you want to post again?',
51
                    'btn_repost' => 'repost',
52
                );
53
            }
54
        }
55
56
        // render form as plain html
57
        public function getTicketHtml($salt = '', $timeout = 1800, $area = '')
58
        {
59
            return '<input type="hidden" name="XOOPS_G_TICKET" value="' . $this->issue($salt, $timeout, $area) . '" />';
60
        }
61
62
        // returns an object of XoopsFormHidden including the ticket
63
        public function getTicketXoopsForm($salt = '', $timeout = 1800, $area = '')
64
        {
65
            return new Xoops\Form\Hidden('XOOPS_G_TICKET', $this->issue($salt, $timeout, $area));
66
        }
67
68
        // add a ticket as Hidden Element into XoopsForm
69
        public function addTicketXoopsFormElement(&$form, $salt = '', $timeout = 1800, $area = '')
70
        {
71
            $form->addElement(new Xoops\Form\Hidden('XOOPS_G_TICKET', $this->issue($salt, $timeout, $area)));
72
        }
73
74
        // returns an array for xoops_confirm() ;
75
        public function getTicketArray($salt = '', $timeout = 1800, $area = '')
76
        {
77
            return array('XOOPS_G_TICKET' => $this->issue($salt, $timeout, $area));
78
        }
79
80
        // return GET parameter string.
81
        public function getTicketParamString($salt = '', $noamp = false, $timeout = 1800, $area = '')
82
        {
83
            return ($noamp ? '' : '&amp;') . 'XOOPS_G_TICKET=' . $this->issue($salt, $timeout, $area);
84
        }
85
86
        // issue a ticket
87
        public function issue($salt = '', $timeout = 1800, $area = '')
88
        {
89
            $xoops = Xoops::getInstance();
90
91
            // create a token
92
            list($usec, $sec) = explode(" ", microtime());
93
            $appendix_salt = empty($_SERVER['PATH']) ? \XoopsBaseConfig::get('db-name') : $_SERVER['PATH'];
94
            $token = crypt($salt . $usec . $appendix_salt . $sec);
95
            $this->_latest_token = $token;
96
97
            if (empty($_SESSION['XOOPS_G_STUBS'])) {
98
                $_SESSION['XOOPS_G_STUBS'] = array();
99
            }
100
101
            // limit max stubs 10
102
            if (sizeof($_SESSION['XOOPS_G_STUBS']) > 10) {
103
                $_SESSION['XOOPS_G_STUBS'] = array_slice($_SESSION['XOOPS_G_STUBS'], -10);
104
            }
105
106
            // record referer if browser send it
107
            $referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['REQUEST_URI'];
108
109
            // area as module's dirname
110
            if (!$area && $xoops->isModule()) {
111
                $area = $xoops->module->getVar('dirname');
0 ignored issues
show
Bug introduced by
The method getVar() does not exist on null. ( Ignorable by Annotation )

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

111
                /** @scrutinizer ignore-call */ 
112
                $area = $xoops->module->getVar('dirname');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
112
            }
113
114
            // store stub
115
            $_SESSION['XOOPS_G_STUBS'][] = array(
116
                'expire' => time() + $timeout, 'referer' => $referer, 'area' => $area, 'token' => $token
117
            );
118
119
            // paid md5ed token as a ticket
120
            return md5($token . \XoopsBaseConfig::get('db-prefix'));
121
        }
122
123
        // check a ticket
124
        public function check($post = true, $area = '', $allow_repost = true)
125
        {
126
            $xoops = Xoops::getInstance();
127
            $this->_errors = array();
128
129
            // CHECK: stubs are not stored in session
130
            if (!is_array(@$_SESSION['XOOPS_G_STUBS'])) {
131
                $this->_errors[] = $this->messages['err_nostubs'];
132
                $_SESSION['XOOPS_G_STUBS'] = array();
133
            }
134
135
            // get key&val of the ticket from a user's query
136
            $ticket = $post ? @$_POST['XOOPS_G_TICKET'] : @$_GET['XOOPS_G_TICKET'];
137
138
            // CHECK: no tickets found
139
            if (empty($ticket)) {
140
                $this->_errors[] = $this->messages['err_noticket'];
141
            }
142
143
            // gargage collection & find a right stub
144
            $stubs_tmp = $_SESSION['XOOPS_G_STUBS'];
145
            $_SESSION['XOOPS_G_STUBS'] = array();
146
            foreach ($stubs_tmp as $stub) {
147
                // default lifetime 30min
148
                if ($stub['expire'] >= time()) {
149
                    if (md5($stub['token'] . \XoopsBaseConfig::get('db-prefix')) === $ticket) {
150
                        $found_stub = $stub;
151
                    } else {
152
                        // store the other valid stubs into session
153
                        $_SESSION['XOOPS_G_STUBS'][] = $stub;
154
                    }
155
                } else {
156
                    if (md5($stub['token'] . \XoopsBaseConfig::get('db-prefix')) === $ticket) {
157
                        // not CSRF but Time-Out
158
                        $timeout_flag = true;
159
                    }
160
                }
161
            }
162
163
            // CHECK: the right stub found or not
164
            if (empty($found_stub)) {
165
                if (empty($timeout_flag)) {
166
                    $this->_errors[] = $this->messages['err_nopair'];
167
                } else {
168
                    $this->_errors[] = $this->messages['err_timeout'];
169
                }
170
            } else {
171
172
                // set area if necessary
173
                // area as module's dirname
174
                if (!$area && $xoops->isModule()) {
175
                    $area = $xoops->module->getVar('dirname');
176
                }
177
178
                // check area or referer
179
                if (@$found_stub['area'] == $area) {
180
                    $area_check = true;
181
                }
182
                if (!empty($found_stub['referer']) && strstr(@$_SERVER['HTTP_REFERER'], $found_stub['referer'])) {
183
                    $referer_check = true;
184
                }
185
186
                if (empty($area_check) && empty($referer_check)) { // loose
187
                    $this->_errors[] = $this->messages['err_areaorref'];
188
                }
189
            }
190
191
            if (!empty($this->_errors)) {
192
                if ($allow_repost) {
193
                    // repost form
194
                    $this->draw_repost_form($area);
195
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
196
                } else {
197
                    // failed
198
                    $this->clear();
199
                    return false;
200
                }
201
            } else {
202
                // all green
203
                return true;
204
            }
205
        }
206
207
        // draw form for repost
208
        public function draw_repost_form($area = '')
209
        {
210
            // Notify which file is broken
211
            if (headers_sent()) {
212
                restore_error_handler();
213
                set_error_handler(array(&$this, 'errorHandler4FindOutput'));
214
                header('Dummy: for warning');
215
                restore_error_handler();
216
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
217
            }
218
219
            error_reporting(0);
220
            while (ob_get_level()) {
221
                ob_end_clean();
222
            }
223
224
            $table = '<table>';
225
            $form = '<form action="?' . htmlspecialchars(@$_SERVER['QUERY_STRING'], ENT_QUOTES) . '" method="post" >';
226
            foreach ($_POST as $key => $val) {
227
                if ($key === 'XOOPS_G_TICKET') {
228
                    continue;
229
                }
230
                if (get_magic_quotes_gpc()) {
231
                    $key = stripslashes($key);
232
                }
233
                if (is_array($val)) {
234
                    list($tmp_table, $tmp_form) = $this->extract_post_recursive(htmlspecialchars($key, ENT_QUOTES), $val);
235
                    $table .= $tmp_table;
236
                    $form .= $tmp_form;
237
                } else {
238
                    if (get_magic_quotes_gpc()) {
239
                        $val = stripslashes($val);
240
                    }
241
                    $table .= '<tr><th>' . htmlspecialchars($key, ENT_QUOTES) . '</th><td>' . htmlspecialchars($val, ENT_QUOTES) . '</td></tr>' . "\n";
242
                    $form .= '<input type="hidden" name="' . htmlspecialchars($key, ENT_QUOTES) . '" value="' . htmlspecialchars($val, ENT_QUOTES) . '" />' . "\n";
243
                }
244
            }
245
            $table .= '</table>';
246
            $form .= $this->getTicketHtml(__LINE__, 300, $area) . '<input type="submit" value="' . $this->messages['btn_repost'] . '" /></form>';
247
248
            echo '<html><head><title>' . $this->messages['err_general'] . '</title><style>table,td,th {border:solid black 1px; border-collapse:collapse;}</style></head><body>' . sprintf($this->messages['fmt_prompt4repost'], $this->getErrors()) . $table . $form . '</body></html>';
249
        }
250
251
        /**
252
         * @param string $key_name
253
         * @return array
254
         */
255
        public function extract_post_recursive($key_name, $tmp_array)
256
        {
257
            $table = '';
258
            $form = '';
259
            foreach ($tmp_array as $key => $val) {
260
                if (get_magic_quotes_gpc()) {
261
                    $key = stripslashes($key);
262
                }
263
                if (is_array($val)) {
264
                    list($tmp_table, $tmp_form) = $this->extract_post_recursive($key_name . '[' . htmlspecialchars($key, ENT_QUOTES) . ']', $val);
265
                    $table .= $tmp_table;
266
                    $form .= $tmp_form;
267
                } else {
268
                    if (get_magic_quotes_gpc()) {
269
                        $val = stripslashes($val);
270
                    }
271
                    $table .= '<tr><th>' . $key_name . '[' . htmlspecialchars($key, ENT_QUOTES) . ']</th><td>' . htmlspecialchars($val, ENT_QUOTES) . '</td></tr>' . "\n";
272
                    $form .= '<input type="hidden" name="' . $key_name . '[' . htmlspecialchars($key, ENT_QUOTES) . ']" value="' . htmlspecialchars($val, ENT_QUOTES) . '" />' . "\n";
273
                }
274
            }
275
            return array($table, $form);
276
        }
277
278
279
        // clear all stubs
280
        public function clear()
281
        {
282
            $_SESSION['XOOPS_G_STUBS'] = array();
283
        }
284
285
286
        // Ticket Using
287
        public function using()
288
        {
289
            if (!empty($_SESSION['XOOPS_G_STUBS'])) {
290
                return true;
291
            } else {
292
                return false;
293
            }
294
        }
295
296
297
        // return errors
298
        public function getErrors($ashtml = true)
299
        {
300
            if ($ashtml) {
301
                $ret = '';
302
                foreach ($this->_errors as $msg) {
303
                    $ret .= "$msg<br>\n";
304
                }
305
            } else {
306
                $ret = $this->_errors;
307
            }
308
            return $ret;
309
        }
310
311
        public function errorHandler4FindOutput($errNo, $errStr, $errFile, $errLine)
0 ignored issues
show
Unused Code introduced by
The parameter $errFile is not used and could be removed. ( Ignorable by Annotation )

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

311
        public function errorHandler4FindOutput($errNo, $errStr, /** @scrutinizer ignore-unused */ $errFile, $errLine)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $errLine is not used and could be removed. ( Ignorable by Annotation )

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

311
        public function errorHandler4FindOutput($errNo, $errStr, $errFile, /** @scrutinizer ignore-unused */ $errLine)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
312
        {
313
            if (preg_match('?' . preg_quote(\XoopsBaseConfig::get('root-path')) . '([^:]+)\:(\d+)?', $errStr, $regs)) {
314
                echo "Irregular output! check the file " . htmlspecialchars($regs[1]) . " line " . htmlspecialchars($regs[2]);
315
            } else {
316
                echo "Irregular output! check language files etc.";
317
            }
318
            return;
319
        }
320
        // end of class
321
    }
322
323
    // create a instance in global scope
324
    $GLOBALS['xoopsGTicket'] = new XoopsGTicket();
325
}
326
327
if (!function_exists('admin_refcheck')) {
328
329
    //Admin Referer Check By Marijuana(Rev.011)
330
    function admin_refcheck($chkref = "")
331
    {
332
        if (empty($_SERVER['HTTP_REFERER'])) {
333
            return true;
334
        } else {
335
            $ref = $_SERVER['HTTP_REFERER'];
336
        }
337
        $cr = \XoopsBaseConfig::get('url');
338
        if ($chkref != "") {
339
            $cr .= $chkref;
340
        }
341
        if (strpos($ref, $cr) !== 0) {
342
            return false;
343
        }
344
        return true;
345
    }
346
}
347