Completed
Pull Request — master (#133)
by Goffy
16:45
created

XoopsUserUtility::getIP()   C

Complexity

Conditions 11
Paths 48

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 24
nc 48
nop 1
dl 0
loc 34
rs 5.2653
c 0
b 0
f 0

How to fix   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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 27 and the first side effect is on line 19.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 *  Xoops Form Class Elements
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
13
 * @license             GNU GPL 2 (http://www.gnu.org/licenses/gpl-2.0.html)
14
 * @package             kernel
15
 * @since               2.3.0
16
 * @author              Taiwen Jiang <[email protected]>
17
 */
18
19
defined('XOOPS_ROOT_PATH') || exit('Restricted access');
20
21
/**
22
 * XoopsUserUtility
23
 *
24
 * @package Kernel
25
 * @author  Taiwen Jiang <[email protected]>
26
 */
27
class XoopsUserUtility
28
{
29
    /**
30
     * XoopsUserUtility::sendWelcome
31
     *
32
     * @param mixed $user
33
     *
34
     * @return bool
35
     */
36
    public static function sendWelcome($user)
37
    {
38
        global $xoopsConfigUser, $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
39
40
        if (empty($xoopsConfigUser)) {
41
            $config_handler  = xoops_getHandler('config');
42
            $xoopsConfigUser = $config_handler->getConfigsByCat(XOOPS_CONF_USER);
43
        }
44
        if (empty($xoopsConfigUser['welcome_type'])) {
45
            return true;
46
        }
47
48
        if (!empty($user) && !is_object($user)) {
49
            $member_handler = xoops_getHandler('member');
50
            $user           = $member_handler->getUser($user);
51
        }
52
        if (!is_object($user)) {
53
            return false;
54
        }
55
56
        xoops_loadLanguage('user');
57
        $xoopsMailer =& xoops_getMailer();
58
        if ($xoopsConfigUser['welcome_type'] == 1 || $xoopsConfigUser['welcome_type'] == 3) {
59
            $xoopsMailer->useMail();
60
        }
61
        if ($xoopsConfigUser['welcome_type'] == 2 || $xoopsConfigUser['welcome_type'] == 3) {
62
            $xoopsMailer->usePM();
63
        }
64
        $xoopsMailer->setTemplate('welcome.tpl');
65
        $xoopsMailer->setSubject(sprintf(_US_WELCOME_SUBJECT, $xoopsConfig['sitename']));
66
        $xoopsMailer->setToUsers($user);
67
        if ($xoopsConfigUser['reg_dispdsclmr'] && $xoopsConfigUser['reg_disclaimer']) {
68
            $xoopsMailer->assign('TERMSOFUSE', $xoopsConfigUser['reg_disclaimer']);
69
        } else {
70
            $xoopsMailer->assign('TERMSOFUSE', '');
71
        }
72
73
        return $xoopsMailer->send();
74
    }
75
    /**
76
     * $uname, $email, $pass = null, $vpass = null
77
     */
78
    /**
79
     * XoopsUserUtility::validate
80
     *
81
     * @return bool|string
82
     */
83
    public static function validate()
84
    {
85
        global $xoopsUser;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
86
87
        $args     = func_get_args();
88
        $args_num = func_num_args();
89
90
        $user  = null;
91
        $uname = null;
92
        $email = null;
93
        $pass  = null;
94
        $vpass = null;
95
96
        switch ($args_num) {
97
            case 1:
98
                $user = $args[0];
99
                break;
100
            case 2:
101
                list($uname, $email) = $args;
102
                break;
103
            case 3:
104
                list($user, $pass, $vpass) = $args;
105
                break;
106
            case 4:
107
                list($uname, $email, $pass, $vpass) = $args;
108
                break;
109
            default:
110
                return false;
111
        }
112
        if (is_object($user)) {
113
            $uname = $user->getVar('uname', 'n');
114
            $email = $user->getVar('email', 'n');
115
        }
116
117
        $config_handler  = xoops_getHandler('config');
118
        $xoopsConfigUser = $config_handler->getConfigsByCat(XOOPS_CONF_USER);
119
120
        xoops_loadLanguage('user');
121
        $myts = MyTextSanitizer::getInstance();
0 ignored issues
show
Unused Code introduced by
$myts is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
122
123
        $xoopsUser_isAdmin = is_object($xoopsUser) && $xoopsUser->isAdmin();
124
        $stop              = '';
125
        // Invalid email address
126
        if (!checkEmail($email)) {
127
            $stop .= _US_INVALIDMAIL . '<br>';
128
        }
129
        if (strrpos($email, ' ') > 0) {
130
            $stop .= _US_EMAILNOSPACES . '<br>';
131
        }
132
        // Check forbidden email address if current operator is not an administrator
133 View Code Duplication
        if (!$xoopsUser_isAdmin) {
134
            foreach ($xoopsConfigUser['bad_emails'] as $be) {
135
                if (!empty($be) && preg_match('/' . $be . '/i', $email)) {
136
                    $stop .= _US_INVALIDMAIL . '<br>';
137
                    break;
138
                }
139
            }
140
        }
141
        $uname = xoops_trim($uname);
142
        switch ($xoopsConfigUser['uname_test_level']) {
143
            case 0:
144
                // strict
145
                $restriction = '/[^a-zA-Z0-9\_\-]/';
146
                break;
147
            case 1:
148
                // medium
149
                $restriction = '/[^a-zA-Z0-9\_\-\<\>\,\.\$\%\#\@\!\\\'\']/';
150
                break;
151
            case 2:
152
                // loose
153
                $restriction = '/[\000-\040]/';
154
                break;
155
        }
156
        if (empty($uname) || preg_match($restriction, $uname)) {
0 ignored issues
show
Bug introduced by
The variable $restriction does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
157
            $stop .= _US_INVALIDNICKNAME . '<br>';
158
        }
159
        // Check uname settings if current operator is not an administrator
160
        if (!$xoopsUser_isAdmin) {
161
            if (strlen($uname) > $xoopsConfigUser['maxuname']) {
162
                $stop .= sprintf(_US_NICKNAMETOOLONG, $xoopsConfigUser['maxuname']) . '<br>';
163
            }
164
            if (strlen($uname) < $xoopsConfigUser['minuname']) {
165
                $stop .= sprintf(_US_NICKNAMETOOSHORT, $xoopsConfigUser['minuname']) . '<br>';
166
            }
167
            foreach ($xoopsConfigUser['bad_unames'] as $bu) {
168
                if (!empty($bu) && preg_match('/' . $bu . '/i', $uname)) {
169
                    $stop .= _US_NAMERESERVED . '<br>';
170
                    break;
171
                }
172
            }
173
            /**
174
             * if (strrpos($uname, ' ') > 0) {
175
             * $stop .= _US_NICKNAMENOSPACES . '<br>';
176
             * }
177
             */
178
        }
179
        $xoopsDB = XoopsDatabaseFactory::getDatabaseConnection();
180
        // Check if uname/email already exists if the user is a new one
181
        $uid    = is_object($user) ? $user->getVar('uid') : 0;
182
        $sql    = 'SELECT COUNT(*) FROM `' . $xoopsDB->prefix('users') . '` WHERE `uname` = ' . $xoopsDB->quote(addslashes($uname)) . (($uid > 0) ? " AND `uid` <> {$uid}" : '');
183
        $result = $xoopsDB->query($sql);
184
        list($count) = $xoopsDB->fetchRow($result);
185
        if ($count > 0) {
186
            $stop .= _US_NICKNAMETAKEN . '<br>';
187
        }
188
        $sql    = 'SELECT COUNT(*) FROM `' . $xoopsDB->prefix('users') . '` WHERE `email` = ' . $xoopsDB->quote(addslashes($email)) . (($uid > 0) ? " AND `uid` <> {$uid}" : '');
189
        $result = $xoopsDB->query($sql);
190
        list($count) = $xoopsDB->fetchRow($result);
191
        if ($count > 0) {
192
            $stop .= _US_EMAILTAKEN . '<br>';
193
        }
194
        // If password is not set, skip password validation
195
        if ($pass === null && $vpass === null) {
196
            return $stop;
197
        }
198
199
        if (!isset($pass) || $pass == '' || !isset($vpass) || $vpass == '') {
200
            $stop .= _US_ENTERPWD . '<br>';
201
        }
202
        if (isset($pass) && ($pass != $vpass)) {
203
            $stop .= _US_PASSNOTSAME . '<br>';
204
        } elseif (($pass != '') && (strlen($pass) < $xoopsConfigUser['minpass'])) {
205
            $stop .= sprintf(_US_PWDTOOSHORT, $xoopsConfigUser['minpass']) . '<br>';
206
        }
207
208
        return $stop;
209
    }
210
211
    /**
212
     * Get client IP
213
     *
214
     * Adapted from PMA_getIp() [phpmyadmin project]
215
     *
216
     * @param  bool $asString requiring integer or dotted string
217
     * @return mixed string or integer value for the IP
218
     */
219
    public static function getIP($asString = false)
220
    {
221
        // Gets the proxy ip sent by the user
222
        $proxy_ip = '';
223
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
224
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
225
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
226
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
227
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
228
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
229
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
230
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
231
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
232
            $proxy_ip = $_SERVER['HTTP_VIA'];
233
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
234
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
235
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
236
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
237
        }
238
        if (!empty($proxy_ip)) {
239
            $ip = new \Xmf\IPAddress($proxy_ip);
240
            if (false === $ip->asReadable()) {
241
                $ip = \Xmf\IPAddress::fromRequest();
242
            }
243
        } else {
244
            $ip = \Xmf\IPAddress::fromRequest();
245
        }
246
247
        // this really should return $ip->asBinary() instead of ip2long, but for IPv6, this will
248
        // return false when the ip2long() fails. Callers are not expecting binary strings.
249
        $the_IP = $asString ? $ip->asReadable() : ip2long($ip->asReadable());
250
251
        return $the_IP;
252
    }
253
254
    /**
255
     * XoopsUserUtility::getUnameFromIds()
256
     *
257
     * @param  mixed $uid
258
     * @param  mixed $usereal
259
     * @param  mixed $linked
260
     * @return array
261
     */
262
    public static function getUnameFromIds($uid, $usereal = false, $linked = false)
263
    {
264
        if (!is_array($uid)) {
265
            $uid = array($uid);
266
        }
267
        $userid = array_map('intval', array_filter($uid));
268
269
        $myts  = MyTextSanitizer::getInstance();
270
        $users = array();
271
        if (count($userid) > 0) {
272
            $xoopsDB = XoopsDatabaseFactory::getDatabaseConnection();
273
            $sql     = 'SELECT uid, uname, name FROM ' . $xoopsDB->prefix('users') . ' WHERE level > 0 AND uid IN(' . implode(',', array_unique($userid)) . ')';
274
            if (!$result = $xoopsDB->query($sql)) {
275
                return $users;
276
            }
277
            while ($row = $xoopsDB->fetchArray($result)) {
278
                $uid = $row['uid'];
279
                if ($usereal && $row['name']) {
280
                    $users[$uid] = $myts->htmlSpecialChars($row['name']);
281
                } else {
282
                    $users[$uid] = $myts->htmlSpecialChars($row['uname']);
283
                }
284
                if ($linked) {
285
                    $users[$uid] = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $uid . '" title="' . $users[$uid] . '">' . $users[$uid] . '</a>';
286
                }
287
            }
288
        }
289
        if (in_array(0, $users, true)) {
290
            $users[0] = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
291
        }
292
293
        return $users;
294
    }
295
296
    /**
297
     * XoopsUserUtility::getUnameFromId()
298
     *
299
     * @param  mixed $userid
300
     * @param  mixed $usereal
301
     * @param  mixed $linked
302
     * @return string
303
     */
304
    public static function getUnameFromId($userid, $usereal = false, $linked = false)
305
    {
306
        $myts     = MyTextSanitizer::getInstance();
307
        $userid   = (int)$userid;
308
        $username = '';
309
        if ($userid > 0) {
310
            $member_handler = xoops_getHandler('member');
311
            $user           = $member_handler->getUser($userid);
312
            if (is_object($user)) {
313
                if ($usereal && $user->getVar('name')) {
314
                    $username = $user->getVar('name');
315
                } else {
316
                    $username = $user->getVar('uname');
317
                }
318
                if (!empty($linked)) {
319
                    $username = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $userid . '" title="' . $username . '">' . $username . '</a>';
320
                }
321
            }
322
        }
323
        if (empty($username)) {
324
            $username = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
325
        }
326
327
        return $username;
328
    }
329
}
330