Completed
Pull Request — master (#489)
by Richard
10:39
created

XoopsUserUtility::sendWelcome()   D

Complexity

Conditions 10
Paths 19

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110
Metric Value
dl 0
loc 33
ccs 0
cts 21
cp 0
rs 4.8196
cc 10
eloc 22
nc 19
nop 1
crap 110

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
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)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $xoops->checkEmail($email) of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
116
            $stop .= XoopsLocale::E_INVALID_EMAIL . '<br />';
117
        }
118
        if (strrpos($email, ' ') > 0) {
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)) {
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 View Code Duplication
            if (!empty($maxuname) && mb_strlen($uname) > $maxuname) {
142
                $stop .= sprintf(XoopsLocale::EF_USERNAME_MUST_BE_LESS_THAN, $maxuname) . '<br />';
143
            }
144
            $minuname = $xoops->getConfig('minuname');
145 View Code Duplication
            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);
0 ignored issues
show
Bug introduced by
The method getCount does only exist in XoopsPersistableObjectHandler, but not in XoopsObjectHandler.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
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)
0 ignored issues
show
Coding Style introduced by
getIP uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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)) {
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)) {
0 ignored issues
show
Bug introduced by
The method getAll does only exist in XoopsPersistableObjectHandler, but not in XoopsObjectHandler.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
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