XoopsUserUtility::validate()   F
last analyzed

Complexity

Conditions 39
Paths > 20000

Size

Total Lines 127
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 39
eloc 84
nc 5963777
nop 0
dl 0
loc 127
rs 0
c 1
b 0
f 0

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
 *  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 (https://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;
39
40
        if (empty($xoopsConfigUser)) {
41
            /* @var XoopsConfigHandler $config_handler */
42
            $config_handler  = xoops_getHandler('config');
43
            $xoopsConfigUser = $config_handler->getConfigsByCat(XOOPS_CONF_USER);
44
        }
45
        if (empty($xoopsConfigUser['welcome_type'])) {
46
            return true;
47
        }
48
49
        if (!empty($user) && !is_object($user)) {
50
            /* @var XoopsMemberHandler $member_handler */
51
            $member_handler = xoops_getHandler('member');
52
            $user           = $member_handler->getUser($user);
53
        }
54
        if (!is_object($user)) {
55
            return false;
56
        }
57
58
        xoops_loadLanguage('user');
59
        $xoopsMailer = xoops_getMailer();
60
        if ($xoopsConfigUser['welcome_type'] == 1 || $xoopsConfigUser['welcome_type'] == 3) {
61
            $xoopsMailer->useMail();
62
        }
63
        if ($xoopsConfigUser['welcome_type'] == 2 || $xoopsConfigUser['welcome_type'] == 3) {
64
            $xoopsMailer->usePM();
65
        }
66
        $xoopsMailer->setTemplate('welcome.tpl');
67
        $xoopsMailer->setSubject(sprintf(_US_WELCOME_SUBJECT, $xoopsConfig['sitename']));
68
        $xoopsMailer->setToUsers($user);
69
        if ($xoopsConfigUser['reg_dispdsclmr'] && $xoopsConfigUser['reg_disclaimer']) {
70
            $xoopsMailer->assign('TERMSOFUSE', $xoopsConfigUser['reg_disclaimer']);
71
        } else {
72
            $xoopsMailer->assign('TERMSOFUSE', '');
73
        }
74
75
        return $xoopsMailer->send();
76
    }
77
    /**
78
     * $uname, $email, $pass = null, $vpass = null
79
     */
80
    /**
81
     * XoopsUserUtility::validate
82
     *
83
     * @return bool|string
84
     */
85
    public static function validate()
86
    {
87
        global $xoopsUser;
88
89
        $args     = func_get_args();
90
        $args_num = func_num_args();
91
92
        $user  = null;
93
        $uname = null;
94
        $email = null;
95
        $pass  = null;
96
        $vpass = null;
97
98
        switch ($args_num) {
99
            case 1:
100
                $user = $args[0];
101
                break;
102
            case 2:
103
                list($uname, $email) = $args;
104
                break;
105
            case 3:
106
                list($user, $pass, $vpass) = $args;
107
                break;
108
            case 4:
109
                list($uname, $email, $pass, $vpass) = $args;
110
                break;
111
            default:
112
                return false;
113
        }
114
        if (is_object($user)) {
115
            $uname = $user->getVar('uname', 'n');
116
            $email = $user->getVar('email', 'n');
117
        }
118
        /* @var XoopsConfigHandler $config_handler */
119
        $config_handler  = xoops_getHandler('config');
120
        $xoopsConfigUser = $config_handler->getConfigsByCat(XOOPS_CONF_USER);
121
122
        xoops_loadLanguage('user');
123
        $myts = MyTextSanitizer::getInstance();
0 ignored issues
show
Unused Code introduced by geekwright
The assignment to $myts is dead and can be removed.
Loading history...
124
125
        $xoopsUser_isAdmin = is_object($xoopsUser) && $xoopsUser->isAdmin();
126
        $stop              = '';
127
        // Invalid email address
128
        if (!checkEmail($email)) {
129
            $stop .= _US_INVALIDMAIL . '<br>';
130
        }
131
        if (strrpos($email, ' ') > 0) {
132
            $stop .= _US_EMAILNOSPACES . '<br>';
133
        }
134
        // Check forbidden email address if current operator is not an administrator
135
        if (!$xoopsUser_isAdmin) {
136
            foreach ($xoopsConfigUser['bad_emails'] as $be) {
137
                if (!empty($be) && preg_match('/' . $be . '/i', $email)) {
138
                    $stop .= _US_INVALIDMAIL . '<br>';
139
                    break;
140
                }
141
            }
142
        }
143
        $uname = xoops_trim($uname);
144
        switch ($xoopsConfigUser['uname_test_level']) {
145
            case 0:
146
                // strict
147
                $restriction = '/[^a-zA-Z0-9\_\-]/';
148
                break;
149
            case 1:
150
                // medium
151
                $restriction = '/[^a-zA-Z0-9\_\-\<\>\,\.\$\%\#\@\!\\\'\']/';
152
                break;
153
            case 2:
154
                // loose
155
                $restriction = '/[\000-\040]/';
156
                break;
157
        }
158
        if (empty($uname) || preg_match($restriction, $uname)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by beckmi
The variable $restriction does not seem to be defined for all execution paths leading up to this point.
Loading history...
159
            $stop .= _US_INVALIDNICKNAME . '<br>';
160
        }
161
        // Check uname settings if current operator is not an administrator
162
        if (!$xoopsUser_isAdmin) {
163
            if (strlen($uname) > $xoopsConfigUser['maxuname']) {
164
                $stop .= sprintf(_US_NICKNAMETOOLONG, $xoopsConfigUser['maxuname']) . '<br>';
165
            }
166
            if (strlen($uname) < $xoopsConfigUser['minuname']) {
167
                $stop .= sprintf(_US_NICKNAMETOOSHORT, $xoopsConfigUser['minuname']) . '<br>';
168
            }
169
            foreach ($xoopsConfigUser['bad_unames'] as $bu) {
170
                if (!empty($bu) && preg_match('/' . $bu . '/i', $uname)) {
171
                    $stop .= _US_NAMERESERVED . '<br>';
172
                    break;
173
                }
174
            }
175
            /**
176
             * if (strrpos($uname, ' ') > 0) {
177
             * $stop .= _US_NICKNAMENOSPACES . '<br>';
178
             * }
179
             */
180
        }
181
        /** @var XoopsMySQLDatabase $xoopsDB */
182
        $xoopsDB = XoopsDatabaseFactory::getDatabaseConnection();
183
        // Check if uname/email already exists if the user is a new one
184
        $uid    = is_object($user) ? $user->getVar('uid') : 0;
185
        $sql    = 'SELECT COUNT(*) FROM `' . $xoopsDB->prefix('users') . '` WHERE `uname` = ' . $xoopsDB->quote(addslashes($uname)) . (($uid > 0) ? " AND `uid` <> {$uid}" : '');
186
        $result = $xoopsDB->query($sql);
187
        list($count) = $xoopsDB->fetchRow($result);
0 ignored issues
show
Bug introduced by mambax7
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchRow() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

187
        list($count) = $xoopsDB->fetchRow(/** @scrutinizer ignore-type */ $result);
Loading history...
188
        if ($count > 0) {
189
            $stop .= _US_NICKNAMETAKEN . '<br>';
190
        }
191
        $sql    = 'SELECT COUNT(*) FROM `' . $xoopsDB->prefix('users') . '` WHERE `email` = ' . $xoopsDB->quote(addslashes($email)) . (($uid > 0) ? " AND `uid` <> {$uid}" : '');
192
        $result = $xoopsDB->query($sql);
193
        list($count) = $xoopsDB->fetchRow($result);
194
        if ($count > 0) {
195
            $stop .= _US_EMAILTAKEN . '<br>';
196
        }
197
        // If password is not set, skip password validation
198
        if ($pass === null && $vpass === null) {
199
            return $stop;
200
        }
201
202
        if (!isset($pass) || $pass == '' || !isset($vpass) || $vpass == '') {
203
            $stop .= _US_ENTERPWD . '<br>';
204
        }
205
        if (isset($pass) && ($pass != $vpass)) {
206
            $stop .= _US_PASSNOTSAME . '<br>';
207
        } elseif (($pass != '') && (strlen($pass) < $xoopsConfigUser['minpass'])) {
208
            $stop .= sprintf(_US_PWDTOOSHORT, $xoopsConfigUser['minpass']) . '<br>';
209
        }
210
211
        return $stop;
212
    }
213
214
    /**
215
     * Get client IP
216
     *
217
     * Adapted from PMA_getIp() [phpmyadmin project]
218
     *
219
     * @param  bool $asString requiring integer or dotted string
220
     * @return mixed string or integer value for the IP
221
     */
222
    public static function getIP($asString = false)
223
    {
224
        // Gets the proxy ip sent by the user
225
        $proxy_ip = '';
226
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
227
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
228
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
229
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
230
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
231
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
232
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
233
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
234
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
235
            $proxy_ip = $_SERVER['HTTP_VIA'];
236
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
237
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
238
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
239
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
240
        }
241
        if (!empty($proxy_ip)) {
242
            $ip = new \Xmf\IPAddress($proxy_ip);
243
            if (false === $ip->asReadable()) {
0 ignored issues
show
introduced by geekwright
The condition false === $ip->asReadable() is always false.
Loading history...
244
                $ip = \Xmf\IPAddress::fromRequest();
245
            }
246
        } else {
247
            $ip = \Xmf\IPAddress::fromRequest();
248
        }
249
250
        // this really should return $ip->asBinary() instead of ip2long, but for IPv6, this will
251
        // return false when the ip2long() fails. Callers are not expecting binary strings.
252
        $the_IP = $asString ? $ip->asReadable() : ip2long($ip->asReadable());
253
254
        return $the_IP;
255
    }
256
257
    /**
258
     * XoopsUserUtility::getUnameFromIds()
259
     *
260
     * @param  mixed $uid
261
     * @param  mixed $usereal
262
     * @param  mixed $linked
263
     * @return array
264
     */
265
    public static function getUnameFromIds($uid, $usereal = false, $linked = false)
266
    {
267
        if (!is_array($uid)) {
268
            $uid = array($uid);
269
        }
270
        $userid = array_map('intval', array_filter($uid));
271
272
        $myts  = MyTextSanitizer::getInstance();
273
        $users = array();
274
        if (count($userid) > 0) {
275
            /** @var XoopsMySQLDatabase $xoopsDB */
276
            $xoopsDB = XoopsDatabaseFactory::getDatabaseConnection();
277
            $sql     = 'SELECT uid, uname, name FROM ' . $xoopsDB->prefix('users') . ' WHERE level > 0 AND uid IN(' . implode(',', array_unique($userid)) . ')';
278
            if (!$result = $xoopsDB->query($sql)) {
279
                return $users;
280
            }
281
            while (false !== ($row = $xoopsDB->fetchArray($result))) {
0 ignored issues
show
Bug introduced by mambax7
It seems like $result can also be of type true; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

281
            while (false !== ($row = $xoopsDB->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
282
                $uid = $row['uid'];
283
                if ($usereal && $row['name']) {
284
                    $users[$uid] = $myts->htmlSpecialChars($row['name']);
285
                } else {
286
                    $users[$uid] = $myts->htmlSpecialChars($row['uname']);
287
                }
288
                if ($linked) {
289
                    $users[$uid] = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $uid . '" title="' . $users[$uid] . '">' . $users[$uid] . '</a>';
290
                }
291
            }
292
        }
293
        if (in_array(0, $users, true)) {
294
            $users[0] = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
295
        }
296
297
        return $users;
298
    }
299
300
    /**
301
     * XoopsUserUtility::getUnameFromId()
302
     *
303
     * @param  mixed $userid
304
     * @param  mixed $usereal
305
     * @param  mixed $linked
306
     * @return string
307
     */
308
    public static function getUnameFromId($userid, $usereal = false, $linked = false)
309
    {
310
        $myts     = MyTextSanitizer::getInstance();
311
        $userid   = (int)$userid;
312
        $username = '';
313
        if ($userid > 0) {
314
            /* @var XoopsMemberHandler $member_handler */
315
            $member_handler = xoops_getHandler('member');
316
            $user           = $member_handler->getUser($userid);
317
            if (is_object($user)) {
318
                if ($usereal && $user->getVar('name')) {
319
                    $username = $user->getVar('name');
320
                } else {
321
                    $username = $user->getVar('uname');
322
                }
323
                if (!empty($linked)) {
324
                    $username = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $userid . '" title="' . $username . '">' . $username . '</a>';
325
                }
326
            }
327
        }
328
        if (empty($username)) {
329
            $username = $myts->htmlSpecialChars($GLOBALS['xoopsConfig']['anonymous']);
330
        }
331
332
        return $username;
333
    }
334
}
335