Completed
Push — master ( fbe197...e7e29c )
by Alexey
05:05
created

Users::logOut()   C

Complexity

Conditions 7
Paths 18

Size

Total Lines 22
Code Lines 14

Duplication

Lines 7
Ratio 31.82 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 7
loc 22
rs 6.9811
cc 7
eloc 14
nc 18
nop 1
1
<?php
2
3
/**
4
 * Users module
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
class Users extends Module
12
{
13
    public $cookiePrefix = '';
14
15
    public function init()
2 ignored issues
show
Coding Style introduced by
init uses the super-global variable $_GET 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...
Coding Style introduced by
init uses the super-global variable $_POST 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...
16
    {
17
        if (!empty($this->config['cookieSplit'])) {
18
            $this->cookiePrefix = \App::$cur->type;
19
        }
20
        \Users\User::$cur = new Users\User(array('group_id' => 1, 'role_id' => 1));
21
        if (!App::$cur->db->connect) {
22
            return;
23
        }
24
        if (isset($_GET['logout'])) {
25
            return $this->logOut();
26
        }
27
        if (filter_input(INPUT_COOKIE, $this->cookiePrefix . '_user_session_hash') && filter_input(INPUT_COOKIE, $this->cookiePrefix . '_user_id')) {
28
            return $this->cuntinueSession(filter_input(INPUT_COOKIE, $this->cookiePrefix . '_user_session_hash'), filter_input(INPUT_COOKIE, $this->cookiePrefix . '_user_id'));
29
        }
30
        if (isset($_POST['autorization']) && trim(filter_input(INPUT_POST, 'user_login')) && trim(filter_input(INPUT_POST, 'user_pass'))) {
31
            unset($_POST['autorization']);
32
            return $this->autorization(trim(filter_input(INPUT_POST, 'user_login')), trim(filter_input(INPUT_POST, 'user_pass')), strpos(filter_input(INPUT_POST, 'user_login'), '@') ? 'mail' : 'login', false);
33
        }
34
        if (isset($_GET['passre']) && filter_input(INPUT_GET, 'user_mail')) {
35
            return $this->passre(trim(filter_input(INPUT_GET, 'user_mail')));
36
        }
37
        if (!empty($_GET['passrecont']) && filter_input(INPUT_GET, 'hash')) {
38
            return $this->passrecont(filter_input(INPUT_GET, 'hash'));
39
        }
40
    }
41
42
    public function logOut($redirect = true)
1 ignored issue
show
Coding Style introduced by
logOut uses the super-global variable $_COOKIE 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...
43
    {
44
        if (!empty($_COOKIE[$this->cookiePrefix . "_user_session_hash"]) && !empty($_COOKIE[$this->cookiePrefix . "_user_id"])) {
45
            $session = Users\Session::get([
46
                        ['user_id', $_COOKIE[$this->cookiePrefix . "_user_id"]],
47
                        ['hash', $_COOKIE[$this->cookiePrefix . "_user_session_hash"]]
48
            ]);
49
            if ($session) {
50
                $session->delete();
51
            }
52
        }
53 View Code Duplication
        if (!headers_sent()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
            setcookie($this->cookiePrefix . "_user_session_hash", '', 0, "/");
55
            setcookie($this->cookiePrefix . "_user_id", '', 0, "/");
56
        }
57
        if ($redirect) {
58 View Code Duplication
            if (!empty($this->config['logoutUrl'][$this->app->type])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
59
                Tools::redirect($this->config['logoutUrl'][$this->app->type]);
60
            }
61
            Tools::redirect('/', 'Вы вышли из своего профиля', 'success');
62
        }
63
    }
64
65
    public function cuntinueSession($hash, $userId)
66
    {
67
        $session = Users\Session::get([
68
                    ['user_id', $userId],
69
                    ['hash', $hash]
70
        ]);
71
        if ($session && $session->user && $session->user->blocked) {
72 View Code Duplication
            if (!headers_sent()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
73
                setcookie($this->cookiePrefix . "_user_session_hash", '', 0, "/");
74
                setcookie($this->cookiePrefix . "_user_id", '', 0, "/");
75
            }
76
            Msg::add('Ваш аккаунт заблокирован', 'info');
77
            return;
78
        }
79
        if ($session && $session->user && !$session->user->blocked) {
80 View Code Duplication
            if (!headers_sent()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
81
                setcookie($this->cookiePrefix . "_user_session_hash", $session->hash, time() + 360000, "/");
82
                setcookie($this->cookiePrefix . "_user_id", $session->user_id, time() + 360000, "/");
83
            }
84
            if (!empty($this->config['needActivation']) && $session->user->activation) {
85 View Code Duplication
                if (!headers_sent()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                    setcookie($this->cookiePrefix . "_user_session_hash", '', 0, "/");
87
                    setcookie($this->cookiePrefix . "_user_id", '', 0, "/");
88
                }
89
                Tools::redirect('/', 'Этот аккаунт ещё не активирован. <br />Если вы не получали письмо с ссылкой для активации, нажмите на - <a href = "/users/resendActivation/' . $session->user->id . '"><b>повторно выслать ссылку активации</b></a>');
90
            } elseif ($session->user->activation) {
91
                Msg::add('Этот аккаунт ещё не активирован, не все функции могут быть доступны. <br />Если вы не получали письмо с ссылкой для активации, нажмите на - <a href = "/users/resendActivation/' . $session->user->id . '"><b>повторно выслать ссылку активации</b></a>');
92
            }
93 View Code Duplication
            if (!$session->user->mail && !empty($this->config['noMailNotify'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
                Msg::add($this->config['noMailNotify']);
95
            }
96
            Users\User::$cur = $session->user;
97
            Users\User::$cur->date_last_active = 'CURRENT_TIMESTAMP';
98
            Users\User::$cur->save();
99 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
            if (!headers_sent()) {
101
                setcookie($this->cookiePrefix . "_user_session_hash", '', 0, "/");
102
                setcookie($this->cookiePrefix . "_user_id", '', 0, "/");
103
            }
104
            Msg::add('Ваша сессия устарела или более недействительна, вам необходимо пройти <a href = "/users/login">авторизацию</a> заново', 'info');
105
        }
106
    }
107
108
    public function passre($user_mail)
109
    {
110
        $user = $this->get($user_mail, 'mail');
111
        if (!$user) {
112
            Msg::add('Пользователь ' . $user_mail . ' не найден, проверьте првильность ввода e-mail или зарегистрируйтесь', 'danger');
113
            return false;
114
        }
115
        $passre = Users\Passre::get([['user_id', $user->id], ['status', 1]]);
116
        if ($passre) {
117
            $passre->status = 2;
118
            $passre->save();
119
        }
120
        $hash = $user->id . '_' . Tools::randomString(50);
121
        $passre = new Users\Passre(['user_id' => $user->id, 'status' => 1, 'hash' => $hash]);
122
        $passre->save();
123
        Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, $user_mail, 'Восстановление пароля на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME), 'Было запрошено восстановление пароля на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME) . '<br />для продолжения восстановления пароля перейдите по ссылке: <a href = "http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/?passrecont=1&hash=' . $hash . '">' . idn_to_utf8(INJI_DOMAIN_NAME) . '/?passrecont=1&hash=' . $hash . '</a>');
124
        Tools::redirect('/', 'На указанный почтовый ящик была выслана инструкция по восстановлению пароля', 'success');
125
    }
126
127
    public function passrecont($hash)
128
    {
129
        $passre = Users\Passre::get([['hash', $hash]]);
130
        if ($passre) {
131
            if ($passre->status != 1) {
132
                Tools::redirect('/', 'Этот код восстановление более недействителен', 'danger');
133
            }
134
            $passre->status = 3;
135
            $passre->save();
136
            $pass = Tools::randomString(10);
137
            $user = Users\User::get($passre->user_id);
138
            $user->pass = $this->hashpass($pass);
139
            $user->save();
140
            $this->autorization($user->mail, $user->pass, 'mail');
141
            Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, $user->mail, 'Новый пароль на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME), 'Было запрошено восстановление пароля на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME) . '<br />Ваш новый пароль: ' . $pass);
142
            Tools::redirect('/', 'На указанный почтовый ящик был выслан новый пароль', 'success');
143
        }
144
    }
145
146
    public function autorization($login, $pass, $ltype = 'login', $noMsg = true)
147
    {
148
149
        sleep(3); //simple anti brute
150
151
        $user = $this->get($login, $ltype);
152
        if ($user && $this->verifypass($pass, $user->pass) && !$user->blocked) {
153
            if (!empty($this->config['needActivation']) && $session->user->activation) {
154
                Tools::redirect('/', 'Этот аккаунт ещё не активирован. <br />Если вы не получали письмо с ссылкой для активации, нажмите на - <a href = "/users/resendActivation/' . $session->user->id . '"><b>повторно выслать ссылку активации</b></a>');
0 ignored issues
show
Bug introduced by
The variable $session does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
155
            } elseif ($user->activation) {
156
                Msg::add('Этот аккаунт ещё не активирован, не все функции могут быть доступны. <br />Если вы не получали письмо с ссылкой для активации, нажмите на - <a href = "/users/resendActivation/' . $user->id . '"><b>повторно выслать ссылку активации</b></a>');
157
            }
158 View Code Duplication
            if (!$user->mail && !empty($this->config['noMailNotify'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
                Msg::add($this->config['noMailNotify']);
160
            }
161
            $this->newSession($user);
162
163
            Users\User::$cur = $user;
164
            Users\User::$cur->date_last_active = 'CURRENT_TIMESTAMP';
165
            Users\User::$cur->save();
166 View Code Duplication
            if (!$noMsg && !empty($this->config['loginUrl'][$this->app->type])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167
                Tools::redirect($this->config['loginUrl'][$this->app->type]);
168
            }
169
            return true;
170
        }
171
        if (!$noMsg) {
172
            if ($user && $user->blocked) {
173
                Msg::add('Вы заблокированы', 'danger');
174
            } elseif ($user) {
175
                Msg::add('Вы ошиблись при наборе пароля или логина, попробуйте ещё раз или воспользуйтесь <a href = "?passre=1&user_mail=' . $user->mail . '">Восстановлением пароля</a>', 'danger');
176
            } else {
177
                Msg::add('Данный почтовый ящик не зарегистрирован в системе', 'danger');
178
            }
179
        }
180
181
        return false;
182
    }
183
184
    public function newSession($user)
1 ignored issue
show
Coding Style introduced by
newSession 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...
185
    {
186
        $hash = Tools::randomString(255);
187
188
        $session = new Users\Session([
189
            'user_id' => $user->id,
190
            'agent' => $_SERVER['HTTP_USER_AGENT'],
191
            'ip' => $_SERVER['REMOTE_ADDR']
192
        ]);
193
194
        $session->hash = $hash;
195
        $session->save();
196
197 View Code Duplication
        if (!headers_sent()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
198
            setcookie($this->cookiePrefix . "_user_session_hash", $session->hash, time() + 360000, "/");
199
            setcookie($this->cookiePrefix . "_user_id", $session->user_id, time() + 360000, "/");
200
        } else {
201
            Msg::add('Не удалось провести авторизацию. Попробуйте позже', 'info');
202
        }
203
    }
204
205
    /**
206
     * Return user
207
     * 
208
     * @param integer|string $idn
209
     * @param type $ltype
210
     * @return boolean|\User\User
211
     */
212
    public function get($idn, $ltype = 'id')
213
    {
214
        if (!$idn)
215
            return false;
216
217
        if (is_numeric($idn) && $ltype != 'login')
218
            $user = Users\User::get($idn, 'id');
219
        elseif ($ltype == 'login')
220
            $user = Users\User::get($idn, 'login');
221
        else
222
            $user = Users\User::get($idn, 'mail');
223
        if (!$user)
224
            return [];
225
226
        return $user;
227
    }
228
229
    public function registration($data, $autorization = false)
3 ignored issues
show
Coding Style introduced by
registration uses the super-global variable $_POST 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...
Coding Style introduced by
registration uses the super-global variable $_COOKIE 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...
Coding Style introduced by
registration uses the super-global variable $_GET 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...
230
    {
231
        extract($data);
232
233
        if (empty($user_mail)) {
234
            Msg::add('Вы не ввели E-mail', 'danger');
235
            return false;
236
        }
237
        $user_mail = trim($user_mail);
238
        if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) {
239
            Msg::add('Вы ввели не корректный E-mail', 'danger');
240
            return false;
241
        }
242
243
        $user = $this->get($user_mail, 'mail');
244
        if ($user) {
245
            Msg::add('Введенный вами почтовый ящик зарегистрирован в нашей системе, войдите или введите другой почтовый ящик', 'danger');
246
            return false;
247
        }
248
        if (empty($user_login)) {
249
            $user_login = $user_mail;
250
        }
251
        $user_login = trim($user_login);
252
        $user = $this->get($user_login, 'login');
253
        if ($user) {
254
            Msg::add('Введенный вами логин зарегистрирован в нашей системе, войдите или введите другой логин', 'danger');
255
            return false;
256
        }
257
        if (empty($user_name)) {
258
            $user_name = '';
259
        }
260
        if (empty($user_city)) {
261
            $user_city = '';
262
        }
263
        if (empty($user_birthday)) {
264
            $user_birthday = '';
265
        }
266
        if (empty($user_phone)) {
267
            $user_phone = '';
268
        }
269
        $invite_code = (!empty($data['invite_code']) ? $data['invite_code'] : (!empty($_POST['invite_code']) ? $_POST['invite_code'] : ((!empty($_COOKIE['invite_code']) ? $_COOKIE['invite_code'] : ((!empty($_GET['invite_code']) ? $_GET['invite_code'] : ''))))));
270
        if (!empty($invite_code)) {
271
            $invite = Users\User\Invite::get($invite_code, 'code');
272
            if (!$invite) {
273
                Msg::add('Такой код приглашения не найден', 'danger');
274
                return false;
275
            }
276
            if ($invite->limit && !($invite->limit - $invite->count)) {
277
                Msg::add('Лимит приглашений для данного кода исчерпан', 'danger');
278
                return false;
279
            }
280
            $parent_id = $invite->user_id;
281
            $inviter = $parent_id;
282
            $invite->count++;
283
            $invite->save();
284
        }
285
        if (empty($parent_id) && !empty($this->config['defaultPartner'])) {
286
            $parent_id = $this->config['defaultPartner'];
287
        }
288
289
        $pass = Tools::randomString(10);
290
        $user = new Users\User([
291
            'pass' => $this->hashpass($pass),
292
            'mail' => $user_mail,
293
            'login' => htmlspecialchars($user_login),
294
            'role_id' => 2,
295
            'group_id' => 2,
296
            'parent_id' => !empty($parent_id) ? $parent_id : 0
297
        ]);
298
        if (!empty($this->config['needActivation'])) {
299
            $user->activation = Tools::randomString();
300
        }
301
        $user->save();
302
        if (!$user->id) {
303
            Msg::add('Не удалось зарегистрировать', 'danger');
304
            return false;
305
        }
306
        $info = new \Users\User\Info([
307
            'user_id' => $user->id,
308
            'first_name' => htmlspecialchars($user_name),
309
            'city' => htmlspecialchars($user_city),
310
            'bday' => htmlspecialchars($user_birthday),
311
            'phone' => htmlspecialchars($user_phone),
312
        ]);
313
        $info->save();
314
        if (isset($inviter)) {
315
            $this->AddUserActivity($inviter, 2, "У вас зарегистрировался новый партнер, {$info->first_name} {$info->last_name} (id: {$user->id}, email: {$user->mail})");
316
        }
317
        if ($autorization) {
318
            $this->autorization($user_mail, $pass, 'mail');
319
        }
320
        if (!empty($this->config['needActivation'])) {
321
            $from = 'noreply@' . INJI_DOMAIN_NAME;
322
            $to = $user_mail;
323
            $subject = 'Регистрация на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
324
            $text = 'Вы были зарегистрированы на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME) . '<br />для входа используйте ваш почтовый ящик в качестве логина и пароль: ' . $pass;
325
            $text .='<br />';
326
            $text .= '<br />';
327
            $text .= 'Для активации вашего аккаунта перейдите по ссылке <a href = "http://' . INJI_DOMAIN_NAME . '/users/activation/' . $user->id . '/' . $user->activation . '">http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/users/activation/' . $user->id . '/' . $user->activation . '</a>';
328
            Tools::sendMail($from, $to, $subject, $text);
329
            Msg::add('Вы были зарегистрированы. На указанный почтовый ящик был выслан ваш пароль и ссылка для активации', 'success');
330
        } else {
331
            $from = 'noreply@' . INJI_DOMAIN_NAME;
332
            $to = $user_mail;
333
            $subject = 'Регистрация на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
334
            $text = 'Вы были зарегистрированы на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME) . '<br />для входа используйте ваш почтовый ящик в качестве логина и пароль: ' . $pass;
335
            Tools::sendMail($from, $to, $subject, $text);
336
            Msg::add('Вы были зарегистрированы. На указанный почтовый ящик был выслан ваш пароль', 'success');
337
        }
338
        return $user->id;
339
    }
340
341
    public function hashpass($pass)
342
    {
343
        return password_hash($pass, PASSWORD_DEFAULT);
344
    }
345
346
    public function verifypass($pass, $hash)
347
    {
348
        return password_verify($pass, $hash);
349
    }
350
351
    public function getUserPartners($user, $levels = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $levels is not used and could be removed.

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

Loading history...
352
    {
353
        $return = [
354
            'users' => [],
355
            'levels' => [],
356
            'count' => 0,
357
            'lastLevel' => 0
358
        ];
359
        $levels = [];
360
        $userIds = $user->user_id;
361
        for ($i = 1; $i <= $levels || !$levels; $i++) {
362
            if (!$userIds && $levels) {
363
                $levels[$i] = [];
364
                continue;
365
            } elseif (!$userIds && !$levels) {
366
                break;
367
            }
368
            $usersLevel = \Users\User::getList(['where' => [['parent_id', $userIds, 'IN']]]);
369
            $return['users'] += $usersLevel;
370
            $return['levels'][$i] = array_keys($usersLevel);
371
            $userIds = implode(',', $return['levels'][$i]);
372
            $return['lastLevel'] = $i;
373
        }
374
        $return['count'] = count($return['users']);
375
        return $return;
376
    }
377
378
    public function addUserActivity($user_id, $cat_id, $text = '')
379
    {
380
        $ua = new Users\Activity([
381
            'user_id' => $user_id,
382
            'category_id' => $cat_id,
383
            'text' => $text,
384
        ]);
385
        $ua->save();
386
    }
387
388
}
389