XoopsUserUtility   F
last analyzed

Complexity

Total Complexity 80

Size/Duplication

Total Lines 307
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 173
dl 0
loc 307
rs 2
c 0
b 0
f 0
wmc 80

5 Methods

Rating   Name   Duplication   Size   Complexity  
B getUnameFromIds() 0 34 9
C getIP() 0 40 12
B getUnameFromId() 0 25 7
B sendWelcome() 0 32 10
F validate() 0 127 42

How to fix   Complexity   

Complex Class

Complex classes like XoopsUserUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use XoopsUserUtility, and based on these observations, apply Extract Interface, too.

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
 *  Xoops Form Class Elements
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         class
18
 * @since           2.3.0
19
 * @author          Taiwen Jiang <[email protected]>
20
 * @version         $Id$
21
 */
22
23
class XoopsUserUtility
24
{
25
    /**
26
     * XoopsUserUtility::sendWelcome
27
     *
28
     * @param int|XoopsUser $user id or user object
29
     *
30
     * @return bool
31
     */
32
    public static function sendWelcome($user)
33
    {
34
        $xoops = Xoops::getInstance();
35
36
        if (!$xoops->getConfig('welcome_type')) {
37
            return true;
38
        }
39
40
        if (!empty($user) && !is_object($user)) {
41
            $member_handler = $xoops->getHandlerMember();
42
            $user = $member_handler->getUser($user);
43
        }
44
        if (!is_object($user)) {
45
            return false;
46
        }
47
48
        $xoopsMailer = $xoops->getMailer();
49
        if ($xoops->getConfig('welcome_type') == 1 || $xoops->getConfig('welcome_type') == 3) {
50
            $xoopsMailer->useMail();
51
        }
52
        if ($xoops->getConfig('welcome_type') == 2 || $xoops->getConfig('welcome_type') == 3) {
53
            $xoopsMailer->usePM();
54
        }
55
        $xoopsMailer->setTemplate('welcome.tpl');
56
        $xoopsMailer->setSubject(sprintf(XoopsLocale::F_WELCOME_TO, $xoops->getConfig('sitename')));
57
        $xoopsMailer->setToUsers($user);
58
        if ($xoops->getConfig('reg_disclaimer')) {
59
            $xoopsMailer->assign('TERMSOFUSE', $xoops->getConfig('reg_disclaimer'));
60
        } else {
61
            $xoopsMailer->assign('TERMSOFUSE', '');
62
        }
63
        return $xoopsMailer->send();
64
    }
65
66
    /**
67
     * XoopsUserUtility::validate
68
     *
69
     * @return false|string
70
     */
71
    public static function validate()
72
    {
73
        $xoops = Xoops::getInstance();
74
        $args = func_get_args();
75
        $args_num = func_num_args();
76
77
        /* @var $user XoopsUser|null */
78
        $user = null;
79
        $uname = null;
80
        $email = null;
81
        $pass = null;
82
        $vpass = null;
83
84
        switch ($args_num) {
85
            case 1:
86
                $user = $args[0];
87
                break;
88
            case 2:
89
                list ($uname, $email) = $args;
90
                break;
91
            case 3:
92
                list ($user, $pass, $vpass) = $args;
93
                break;
94
            case 4:
95
                list ($uname, $email, $pass, $vpass) = $args;
96
                break;
97
            default:
98
                return false;
99
        }
100
        if (is_object($user)) {
101
            $uname = $user->getVar('uname', 'n');
102
            $email = $user->getVar('email', 'n');
103
        }
104
105
        //$user = empty($user) ? null : trim($user);
106
        $uname = empty($uname) ? null : trim($uname);
107
        $email = empty($email) ? null : trim($email);
108
        $pass = empty($pass) ? null : trim($pass);
109
        $vpass = empty($vpass) ? null : trim($vpass);
110
111
        $xoops->getConfigs();
112
113
        $stop = '';
114
        // Invalid email address
115
        if (!$xoops->checkEmail($email)) {
116
            $stop .= XoopsLocale::E_INVALID_EMAIL . '<br />';
117
        }
118
        if (strrpos($email, ' ') > 0) {
0 ignored issues
show
Bug introduced by
It seems like $email can also be of type null; however, parameter $haystack of strrpos() does only seem to accept string, 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

118
        if (strrpos(/** @scrutinizer ignore-type */ $email, ' ') > 0) {
Loading history...
119
            $stop .= XoopsLocale::E_EMAIL_SHOULD_NOT_CONTAIN_SPACES . '<br />';
120
        }
121
        // Check forbidden email address if current operator is not an administrator
122
        if (!$xoops->userIsAdmin) {
123
            $bad_emails = $xoops->getConfig('bad_emails');
124
            if (!empty($bad_emails)) {
125
                foreach ($bad_emails as $be) {
126
                    if (!empty($be) && preg_match('/' . $be . '/i', $email)) {
0 ignored issues
show
Bug introduced by
It seems like $email can also be of type null; however, parameter $subject of preg_match() does only seem to accept string, 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

126
                    if (!empty($be) && preg_match('/' . $be . '/i', /** @scrutinizer ignore-type */ $email)) {
Loading history...
127
                        $stop .= XoopsLocale::E_INVALID_EMAIL . '<br />';
128
                        break;
129
                    }
130
                }
131
            }
132
        }
133
        // $uname = XoopsLocale::trim($uname);
134
        // no controls, puctuation, symbols, spaces or invisible separators
135
        if (!preg_match('/^[^\p{C}\p{P}\p{S}\p{Z}]+$/u', $uname)) {
136
            $stop .= XoopsLocale::E_INVALID_USERNAME . '<br />';
137
        }
138
        // Check uname settings if current operator is not an administrator
139
        if (!$xoops->userIsAdmin) {
140
            $maxuname = $xoops->getConfig('maxuname');
141
            if (!empty($maxuname) && mb_strlen($uname) > $maxuname) {
0 ignored issues
show
Bug introduced by
It seems like $uname can also be of type null; however, parameter $string of mb_strlen() does only seem to accept string, 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

141
            if (!empty($maxuname) && mb_strlen(/** @scrutinizer ignore-type */ $uname) > $maxuname) {
Loading history...
142
                $stop .= sprintf(XoopsLocale::EF_USERNAME_MUST_BE_LESS_THAN, $maxuname) . '<br />';
143
            }
144
            $minuname = $xoops->getConfig('minuname');
145
            if (!empty($minuname) && mb_strlen($uname) < $minuname) {
146
                $stop .= sprintf(XoopsLocale::EF_USERNAME_MUST_BE_MORE_THAN, $minuname) . '<br />';
147
            }
148
            $bad_unames = $xoops->getConfig('bad_unames');
149
            if (!empty($bad_unames)) {
150
                foreach ($bad_unames as $bu) {
151
                    if (!empty($bu) && preg_match('/' . $bu . '/i', $uname)) {
152
                        $stop .= XoopsLocale::E_NAME_IS_RESERVED . '<br />';
153
                        break;
154
                    }
155
                }
156
            }
157
        }
158
        // Check if uname/email already exists if the user is a new one
159
        $uid = is_object($user) ? $user->getVar('uid') : 0;
160
161
        $user_handler = $xoops->getHandlerUser();
162
163
        $criteria = new CriteriaCompo(new Criteria('uname', $uname));
164
        if ($uid > 0) {
165
            $criteria->add(new Criteria('uid', $uid, '<>'));
166
        }
167
        $count = $user_handler->getCount($criteria);
168
        if ($count > 0) {
169
            $stop .= XoopsLocale::E_USERNAME_TAKEN . '<br />';
170
        }
171
172
        $criteria = new CriteriaCompo(new Criteria('email', $email));
173
        if ($uid > 0) {
174
            $criteria->add(new Criteria('uid', $uid, '<>'));
175
        }
176
        $count = $user_handler->getCount($criteria);
177
        if ($count > 0) {
178
            $stop .= XoopsLocale::E_EMAIL_TAKEN . '<br />';
179
        }
180
181
        // If password is not set, skip password validation
182
        if ($pass === null && $vpass === null) {
183
            return $stop;
184
        }
185
186
        if (empty($pass) || empty($vpass)) {
187
            $stop .= XoopsLocale::E_MUST_PROVIDE_PASSWORD . '<br />';
188
        }
189
        if (isset($pass) && isset($vpass) && ($pass != $vpass)) {
190
            $stop .= XoopsLocale::E_PASSWORDS_MUST_MATCH . '<br />';
191
        } else {
192
            $minpass = $xoops->getConfig('minpass');
193
            if (($pass != '') && (!empty($minpass)) && (mb_strlen($pass) < $minpass)) {
194
                $stop .= sprintf(XoopsLocale::EF_PASSWORD_MUST_BE_GREATER_THAN, $minpass) . '<br />';
195
            }
196
        }
197
        return $stop;
198
    }
199
200
    /**
201
     * Get client IP
202
     *
203
     * Adapted from PMA_getIp() [phpmyadmin project]
204
     *
205
     * @param bool $asString requiring integer or dotted string
206
     *
207
     * @return mixed string or integer value for the IP
208
     */
209
    public static function getIP($asString = false)
210
    {
211
        // Gets the proxy ip sent by the user
212
        $proxy_ip = '';
213
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
214
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
215
        } else {
216
            if (!empty($_SERVER['HTTP_X_FORWARDED'])) {
217
                $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
218
            } else {
219
                if (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
220
                    $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
221
                } else {
222
                    if (!empty($_SERVER['HTTP_FORWARDED'])) {
223
                        $proxy_ip = $_SERVER['HTTP_FORWARDED'];
224
                    } else {
225
                        if (!empty($_SERVER['HTTP_VIA'])) {
226
                            $proxy_ip = $_SERVER['HTTP_VIA'];
227
                        } else {
228
                            if (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
229
                                $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
230
                            } else {
231
                                if (!empty($_SERVER['HTTP_COMING_FROM'])) {
232
                                    $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
233
                                }
234
                            }
235
                        }
236
                    }
237
                }
238
            }
239
        }
240
        if (!empty($proxy_ip) && preg_match('/^([0-9]{1,3}\.){3,3}[0-9]{1,3}/', $proxy_ip, $regs) && count($regs) > 0) {
241
            $the_IP = $regs[0];
242
        } else {
243
            $the_IP = $_SERVER['REMOTE_ADDR'];
244
        }
245
246
        $the_IP = ($asString) ? $the_IP : ip2long($the_IP);
247
248
        return $the_IP;
249
    }
250
251
    /**
252
     * XoopsUserUtility::getUnameFromIds()
253
     *
254
     * @param array $uids    array of int ids
255
     * @param bool  $usereal use real names if true
256
     * @param bool  $linked  show names as link to userinfo.php
257
     *
258
     * @return array of strings, names or links
259
     */
260
    public static function getUnameFromIds($uids, $usereal = false, $linked = false)
261
    {
262
        $xoops = Xoops::getInstance();
263
        if (!is_array($uids)) {
0 ignored issues
show
introduced by
The condition is_array($uids) is always true.
Loading history...
264
            $uids = array($uids);
265
        }
266
        $userids = array_map('intval', array_filter($uids));
267
268
        $myts = \Xoops\Core\Text\Sanitizer::getInstance();
269
        $users = array();
270
        if (count($userids) > 0) {
271
            $criteria = new CriteriaCompo(new Criteria('level', 0, '>'));
272
            $criteria->add(new Criteria('uid', "('" . implode(',', array_unique($userids)) . "')", 'IN'));
273
274
            $user_handler = $xoops->getHandlerUser();
275
            if (!$rows = $user_handler->getAll($criteria, array('uid', 'uname', 'name'), false, true)) {
276
                return $users;
277
            }
278
            foreach ($rows as $uid => $row) {
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="' . \XoopsBaseConfig::get('url') . '/userinfo.php?uid='
286
                        . $uid . '" title="' . $users[$uid] . '">' . $users[$uid] . '</a>';
287
                }
288
            }
289
        }
290
        if (in_array(0, $users, true)) {
291
            $users[0] = $myts->htmlSpecialChars($xoops->getConfig('anonymous'));
292
        }
293
        return $users;
294
    }
295
296
    /**
297
     * XoopsUserUtility::getUnameFromId()
298
     *
299
     * @param int  $userid  id of user
300
     * @param bool $usereal use real name if true
301
     * @param bool $linked  show username as link to userinfo.php
302
     *
303
     * @return string name or link
304
     */
305
    public static function getUnameFromId($userid, $usereal = false, $linked = false)
306
    {
307
        $xoops = Xoops::getInstance();
308
        $myts = \Xoops\Core\Text\Sanitizer::getInstance();
309
        $userid = (int)($userid);
310
        $username = '';
311
        if ($userid > 0) {
312
            $member_handler = $xoops->getHandlerMember();
313
            $user = $member_handler->getUser($userid);
314
            if (is_object($user)) {
315
                if ($usereal && $user->getVar('name')) {
316
                    $username = $user->getVar('name');
317
                } else {
318
                    $username = $user->getVar('uname');
319
                }
320
                if (!empty($linked)) {
321
                    $username = '<a href="' . \XoopsBaseConfig::get('url') . '/userinfo.php?uid='
322
                        . $userid . '" title="' . $username . '">' . $username . '</a>';
323
                }
324
            }
325
        }
326
        if (empty($username)) {
327
            $username = $myts->htmlSpecialChars($xoops->getConfig('anonymous'));
328
        }
329
        return $username;
330
    }
331
}
332