tiki-login.php 32.2 KB
Newer Older
1
<?php
2

changi67's avatar
changi67 committed
3
4
5
/**
 * @package tikiwiki
 */
6

7
// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
chealer's avatar
chealer committed
8
//
9
10
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
11
// $Id$
changi67's avatar
changi67 committed
12

rjsmelo's avatar
rjsmelo committed
13
$inputConfiguration = [
14
15
16
17
18
    [ 'staticKeyFilters' => [
        'user' => 'text',
        'username' => 'text',
        'pass' => 'none',
    ] ]
rjsmelo's avatar
rjsmelo committed
19
];
20

21
$bypass_siteclose_check = 'y';
22
23

if (empty($_POST['user'])) {
24
    unset($_POST['user']);  // $_POST['user'] is not allowed to be empty if set in tiki-setup.php
25
}
rjsmelo's avatar
rjsmelo committed
26
require_once('tiki-setup.php');
27
global $prefs;
28

29
$login_url_params = '';
30
$isOpenIdValid = false;
31

32
if (! empty($_REQUEST['code']) && $prefs['auth_method'] == 'openid_connect' && TikiLib::lib('openidconnect')->isAvailable()) {
33
    $_REQUEST['user'] = '';
34
} elseif (isset($_REQUEST['cas']) && $_REQUEST['cas'] == 'y' && $prefs['auth_method'] == 'cas') {
35
36
    $login_url_params = '?cas=y';
    $_REQUEST['user'] = '';
rjsmelo's avatar
rjsmelo committed
37
} elseif (! (isset($_REQUEST['user']) or isset($_REQUEST['username']))) {
38
39
40
41
42
43
    if (! $https_mode && $prefs['https_login'] == 'required') {
        header('Location: ' . $base_url_https . 'tiki-login_scr.php');
    } else {
        header('Location: ' . $base_url . 'tiki-login_scr.php');
    }
    die;
44
}
45
$smarty->assign('errortype', 'login'); // to avoid any redirection to the login box if error
mose's avatar
mose committed
46
// Alert user if cookies are switched off
rjsmelo's avatar
rjsmelo committed
47
if (ini_get('session.use_cookies') == 1 && ! isset($_COOKIE[ session_name() ]) && $prefs['session_silent'] != 'y') {
48
49
50
    $smarty->assign('msg', tra('Cookies must be enabled to log in to this site'));
    $smarty->display('error.tpl');
    exit;
mose's avatar
mose committed
51
}
52

53
// Redirect to HTTPS if we are not in HTTPS but we require HTTPS login
rjsmelo's avatar
rjsmelo committed
54
if (! $https_mode && $prefs['https_login'] == 'required') {
55
56
    header('Location: ' . $base_url_https . $prefs['login_url'] . $login_url_params);
    exit;
57
}
58

rjsmelo's avatar
rjsmelo committed
59
if ($prefs['session_silent'] == 'y') {
60
    session_start();
61
62
}

63
// Remember where user is logging in from and send them back later; using session variable for those of us who use WebISO services
64
// Note that login from will always be a complete URL (http://...)
rjsmelo's avatar
rjsmelo committed
65
if (! isset($_SESSION['loginfrom']) && isset($_SERVER['HTTP_REFERER']) && ! preg_match('|/login|', $_SERVER['HTTP_REFERER']) && ! preg_match('|logout|', $_SERVER['HTTP_REFERER'])) {
66
67
68
    $_SESSION['loginfrom'] = $_SERVER['HTTP_REFERER'];
    if (! preg_match('/^http/', $_SESSION['loginfrom'])) {
        if (
69
            $_SESSION['loginfrom'] [
70
            0] == '/'
71
        ) {
72
73
74
75
76
            $_SESSION['loginfrom'] = $url_scheme . '://' . $url_host . (($url_port != '') ? ":$url_port" : '') . $_SESSION['loginfrom'];
        } else {
            $_SESSION['loginfrom'] = $base_url . $_SESSION['loginfrom'];
        }
    }
77
}
78
if (isset($_REQUEST['su']) && $access->checkCsrf(true)) {
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    $loginlib = TikiLib::lib('login');

    if ($loginlib->isSwitched() && $_REQUEST['su'] == 'revert') {
        $loginlib->revertSwitch();
        $access->redirect($_SESSION['loginfrom']);
    } elseif ($tiki_p_admin == 'y') {
        if (empty($_REQUEST['username'])) {
            $smarty->assign('msg', tra('Username field cannot be empty. Please go back and try again.'));
            $smarty->display('error.tpl');
            exit;
        }
        if ($prefs['user_show_realnames'] == 'y') {
            $finalusers = $userlib->find_best_user([$_REQUEST['username']], '', 'login');
            if (count($finalusers[0]) === 1 && ! empty($finalusers[0])) {
                $_REQUEST['username'] = $finalusers[0];
            }
        }
        if ($userlib->user_exists($_REQUEST['username'])) {
            $loginlib->switchUser($_REQUEST['username']);
        }

        $access->redirect($_SESSION['loginfrom']);
    }
lrargerich's avatar
lrargerich committed
102
}
103
$requestedUser = isset($_REQUEST['user']) ? $_REQUEST['user'] : false;
104
105
106
$pass = isset($_REQUEST['pass']) ? $_REQUEST['pass'] : false;
$isvalid = false;
$isdue = false;
107
// admin is always local
rjsmelo's avatar
rjsmelo committed
108
if ($requestedUser == 'admin') {
109
    $prefs['feature_intertiki'] = 'n';
rjsmelo's avatar
rjsmelo committed
110
}
111
// Determine the intertiki domain
112
if ($prefs['feature_intertiki'] == 'y' && $prefs['feature_intertiki_server'] != 'y') {
113
114
115
116
117
118
    if (! empty($prefs['feature_intertiki_mymaster'])) {
        $_REQUEST['intertiki'] = $prefs['feature_intertiki_mymaster'];
    } elseif (strstr($requestedUser, '@')) {
        list($requestedUser, $intertiki_domain) = explode('@', $requestedUser);
        $_REQUEST['intertiki'] = $intertiki_domain;
    }
rjsmelo's avatar
rjsmelo committed
119
} else {
120
    unset($_REQUEST['intertiki']);
rjsmelo's avatar
rjsmelo committed
121
}
122

123
124
125
//Enable Two-Factor Auth Input
$twoFactorForm = 'n';
if (isset($_REQUEST["$twoFactorForm"])) {
126
    $twoFactorForm = 'y';
127
128
129
}
$smarty->assign('twoFactorForm', $twoFactorForm);

130
// Go through the intertiki process
131
132
if (
    isset($_REQUEST['intertiki']) and in_array($_REQUEST['intertiki'], array_keys($prefs['interlist']))
133
    && $access->checkCsrf(null, null, null, null, null, 'page')
134
) {
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    $rpcauth = $userlib->intervalidate($prefs['interlist'][$_REQUEST['intertiki']], $requestedUser, $pass, ! empty($prefs['feature_intertiki_mymaster']) ? true : false);
    if (! $rpcauth) {
        $logslib->add_log('login', 'intertiki : ' . $requestedUser . '@' . $_REQUEST['intertiki'] . ': Failed');
        $smarty->assign('msg', tra('Unable to contact remote server.'));
        $smarty->display('error.tpl');
        exit;
    } else {
        if ($faultCode = $rpcauth->faultCode()) {
            if ($faultCode == 102) {
                $faultCode = 101; // disguise inexistent user
                $userlib->remove_user($requestedUser);
            }
            $user_msg = tra('XMLRPC Error: ') . $faultCode . ' - ' . tra($rpcauth->faultString());
            $log_msg = tra('XMLRPC Error: ') . $rpcauth->faultCode() . ' - ' . tra($rpcauth->faultString());
            $logslib->add_log('login', 'intertiki : ' . $requestedUser . '@' . $_REQUEST['intertiki'] . ': ' . $log_msg);
            $smarty->assign('msg', $user_msg);
            $smarty->display('error.tpl');
            exit;
        } else {
            $isvalid = true;
            $isdue = false;
            $logslib->add_log('login', 'intertiki : ' . $requestedUser . '@' . $_REQUEST['intertiki']);
            if (! empty($prefs['feature_intertiki_mymaster'])) {
                // this is slave intertiki site
                $response_value = $rpcauth->value();
                $avatarData = '';
                if ($response_value->kindOf() == 'struct') {
                    for (;;) {
                        list($key, $value) = $response_value->structeach();
                        if ($key == '') {
                            break;
                        } elseif ($key == 'user_details') {
                            $user_details = unserialize($value->scalarval());
                        } elseif ($key == 'avatarData') {
                            $avatarData = $value->scalarval();
                        }
                    }
                } else {
                    $user_details = unserialize($response_value->scalarval());
                }
                $requestedUser = $user_details['info']['login']; // use the correct capitalization
                if (! $userlib->user_exists($requestedUser)) {
                    if (! $userlib->add_user($requestedUser, '', $user_details['info']['email'])) {
                        $logslib->add_log('login', 'intertiki : login creation failed');
                        $smarty->assign('msg', tra('Unable to create login'));
                        $smarty->display('error.tpl');
                        die;
                    }
                } else {
                    $userlib->update_lastlogin($requestedUser);
                }
                $userlib->set_user_fields($user_details['info']);
                $user = $requestedUser;
                if ($prefs['feature_userPreferences'] == 'y' && $prefs['feature_intertiki_import_preferences'] == 'y') {
                    $userprefslib = TikiLib::lib('userprefs');
                    if (! empty($avatarData)) {
                        $userprefslib->set_user_avatar($user, 'u', '', $user_details['info']['avatarName'], $user_details['info']['avatarSize'], $user_details['info']['avatarFileType'], $avatarData, false);
                    }
                    $userlib->set_user_preferences($user, $user_details['preferences']);
                }
                if ($prefs['feature_intertiki_import_groups'] == 'y') {
                    if ($prefs['feature_intertiki_imported_groups']) {
                        $groups = preg_split('/\s*,\s*/', $prefs['feature_intertiki_imported_groups']);
                        foreach ($groups as $group) {
                            if (in_array(trim($group), $user_details['groups']) && $userlib->group_exists(trim($group))) {
                                $userlib->assign_user_to_group($user, trim($group));
                            }
                        }
                    } else {
                        $filteredGroups = array_filter(
                            $user_details['groups'],
                            function ($group) use ($userlib) {
                                return $userlib->group_exists($group);
                            }
                        );
                        $userlib->assign_user_to_groups($user, $filteredGroups);
                    }
                } else {
                    $groups = preg_split('/\s*,\s*/', $prefs['interlist'][$prefs['feature_intertiki_mymaster']]['groups']);
                    if (empty($groups) || empty($groups[0])) {
                        $smarty->assign('msg', tra('No groups set on Intertiki client.'));
                        $smarty->display('error.tpl');
                        exit;
                    }
                    foreach ($groups as $group) {
                        $userlib->assign_user_to_group($user, trim($group));
                    }
                }
            } else {
                $user = $requestedUser . '@' . $_REQUEST['intertiki'];
                $prefs['feature_userPreferences'] = 'n';
            }
        }
    }
229
} elseif ($prefs['auth_method'] == 'openid_connect' && isset($_GET['code'])) {
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    try {
        $oicLib = TikiLib::lib('openidconnect');
        $token = $oicLib->getAccessToken($_GET['code']);
        $idToken = $token->getIdToken();
        $name = $idToken->getClaim('preferred_username', false) ?: $idToken->getClaim('name', false);
        $email = $idToken->getClaim('email', false);

        $username = $userlib->get_user_by_email($email);

        if (! $username && $email && $oicLib->canCreateUserTiki()) {
            // Remove invalid characters, based on username_pattern pref
            $username = preg_replace('/[^ \'\-_a-zA-Z0-9@\.]/', '_', $name);
            $user = $userlib->add_user($username, '', $email);

            if (! $user) {
                $logslib->add_log(
                    'login',
                    'openid_connect : login creation failed'
                );
                $smarty->assign('msg', tra('Unable to create login'));
                $smarty->display('error.tpl');
                exit;
            }

            $userlib->disable_tiki_auth($username); //disable that user's password in tiki - since we use OpenIdConnect
        }

        if ($username) {
            $userlib->update_lastlogin($username);
            $isvalid = true;
            $isOpenIdValid = true;
            $user = $username;
        } else {
            $error = USER_NOT_FOUND;
            $isvalid = false;
        }
    } catch (Exception $e) {
        $logslib->add_log('login', 'openid_connect : ' . $e->getMessage());
        $smarty->assign('msg', tra('An error occurred trying to login. Please contact the administrator.'));
        $smarty->display('error.tpl');
        exit;
    }
272
} else {
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    // Verify user is valid
    $ret = $userlib->validate_user($requestedUser, $pass);
    if (count($ret) == 3) {
        $ret[] = null;
    }
    list($isvalid, $requestedUser, $error, $method) = $ret;
    // If the password is valid but it is due then force the user to change the password by
    // sending the user to the new password change screen without letting him use tiki
    // The user must re-enter the old password so no security risk here
    if (! $isvalid && $error === ACCOUNT_WAITING_USER && $access->checkCsrf(null, null, null, null, null, 'page')) {
        if ($requestedUser != 'admin') { // admin has not necessarely an email
            if ($userlib->is_email_due($requestedUser)) {
                $userlib->send_confirm_email($requestedUser);
                $userlib->change_user_waiting($requestedUser, 'u');
                $user = '';
                $smarty->assign('user', '');
                $msg = $smarty->fetch('tiki-login_confirm_email.tpl');
                $smarty->assign('msg', explode("\n", $msg));
                $smarty->assign('mid', 'tiki-information.tpl');
                $smarty->display("tiki.tpl");
                die;
            }
        }
    } elseif ($isvalid) {
        $twoFactorSecret = $userlib->get_2_factor_secret($requestedUser);
        if ($prefs['twoFactorAuth'] == 'y' && ! empty($twoFactorSecret) && ! $userlib->validate_two_factor($twoFactorSecret, $_REQUEST["twoFactorAuthCode"])) {
            $error = TWO_FA_INCORRECT;
            $isvalid = false;
            $smarty->assign('twoFactorForm', 'y');
        } else {
            $isdue = $userlib->is_due($requestedUser, $method);
            $user = $requestedUser;
        }
    }
307
}
chealer's avatar
chealer committed
308

309
if ($isvalid && ($isOpenIdValid || $access->checkCsrf(null, null, null, null, null, 'page'))) {
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    $userlib->set_unsuccessful_logins($requestedUser, 0);
    if ($prefs['feature_invite'] == 'y') {
        // tiki-invite, this part is just here to add groups to users which just registered after received an
        // invitation via tiki-invite.php and set the redirect to wiki page if required by the invitation
        $res = $tikilib->query("SELECT `id`,`id_invite` FROM `tiki_invited` WHERE `used_on_user`=? AND used=?", [$user, "registered"]);
        $inviterow = $res->fetchRow();
        if (is_array($inviterow)) {
            $id_invited = $inviterow['id'];
            $id_invite = $inviterow['id_invite'];
            // set groups

            $groups = $tikilib->getOne("SELECT `groups` FROM `tiki_invite` WHERE `id` = ?", [(int)$id_invite]);
            $groups = explode(',', $groups);
            foreach ($groups as $group) {
                $userlib->assign_user_to_group($user, trim($group));
            }
            $tikilib->query("UPDATE `tiki_invited` SET `used`=? WHERE id_invite=?", ["logged", (int)$id_invited]);

            // set wiki page required by invitation
            if (! empty($inviterow['wikipageafter'])) {
                $_REQUEST['page'] = $inviterow['wikipageafter'];
            }
        }
    }

    if ($isdue) {
        // Redirect the user to the screen where he must change his password.
        // Note that the user is not logged in he's just validated to change his password
        // The user must re-enter his old password so no security risk involved
        $url = 'tiki-change_password.php?user=' . urlencode($user);
    } else {
        // User is valid and not due to change pass.. start session
        $userlib->update_expired_groups();
        TikiLib::lib('login')->activateSession($user);
        if (isset($_SESSION['openid_url'])) {
            $userlib->assign_openid($user, $_SESSION['openid_url']);
        }
        $url = $_SESSION['loginfrom'];

        // When logging into a multi-lingual Tiki, $_SESSION['loginfrom'] contains the main-language page, and not the translated one
        //  This only applies if feature_best_language and only seems to affect SEFURL
        if (($prefs['feature_best_language'] == 'y') && ($prefs['feature_sefurl'] == 'y')) {
            // If the URL contains the 'main' home page, remove the page name and let Tiki choose the correct home page upon reload
            $homePageUrl = urlencode($prefs['wikiHomePage']);
            if (strpos($url, 'page=' . $homePageUrl) !== false) {
                $url = str_replace('page=' . $homePageUrl, '', $url);
            } elseif (strpos($url, $homePageUrl) !== false) {
                // Strip away the page name from the URL
                $parts = parse_url($url);
                $url = '';
                if (! empty($parts['scheme'])) {
                    $url = $parts['scheme'] . '://';
                }
                if (! empty($parts['host'])) {
                    $url .= $parts['host'];
                }
                if (! empty($parts['path'])) {
                    $pathParts = explode('/', $parts['path']);
                    $cnt = count($pathParts);
                    if ($cnt > 0) {
                        $pathParts[$cnt - 1] = null;    // Drop the page name
                    }
                    $newPath .= implode('/', $pathParts);
                    $url .= $newPath;
                }
            }
        }

        $logslib->add_log('login', 'logged from ' . $url);
        // Special '?page=...' case. Accept only some values to avoid security problems
        if (isset($_REQUEST['page']) and $_REQUEST['page'] === 'tikiIndex') {
            $url = ${$_REQUEST['page']};
        } else {
            if (! empty($_REQUEST['url'])) {
                $cachelib = TikiLib::lib('cache');
                preg_match('/(.*)\?cache=(.*)/', $_REQUEST['url'], $matches);
                if (! empty($matches[2]) && $cdata = $cachelib->getCached($matches[2], 'edit')) {
                    if (! empty($matches[1])) {
                        $url = $matches[1] . '?' . $cdata;
                    }
                    $cachelib->invalidate($matches[2], 'edit');
                }
            } elseif ($prefs['useGroupHome'] == 'y') { // Go to the group page ?
                if ($prefs['limitedGoGroupHome'] == 'y') {
                    // Handle spaces (that could be written as '%20' in referer, but are generated as '+' with urlencode)
                    $url = str_replace('%20', '+', $url);
                    $url_vars = parse_url($url);
                    $url_path = $url_vars['path'];
                    if ($url_vars['query'] != '') {
                        $url_path .= '?' . $url_vars['query'];
                    }
                    // Get a valid URL for anonymous group homepage
                    // It has to be rewritten when the following two syntaxes are used :
                    //  - http:tiki-something.php => tiki-something.php
                    //  - pageName => tiki-index.php?page=pageName
                    $anonymous_homepage = $userlib->get_group_home('Anonymous');
                    if (! preg_match('#^https?://#', $anonymous_homepage)) {
                        if (substr($anonymous_homepage, 0, 5) == 'http:') {
                            $anonymous_homepage = substr($anonymous_homepage, 5);
                        } else {
                            $anonymous_homepage = 'tiki-index.php?page=' . urlencode($anonymous_homepage);
                        }
                    }
                    // Determine the complete tikiIndex URL for not logged users
                    // when tikiIndex's page has not been explicitely specified
                    //   (this only handles wiki default page for the moment)
                    if (preg_match('/tiki-index.php$/', $prefs['site_tikiIndex']) || preg_match('/tiki-index.php$/', $anonymous_homepage)) {
                        $tikiIndex_full = 'tiki-index.php?page=' . urlencode($prefs['site_wikiHomePage']);
                    } else {
                        $tikiIndex_full = '';
                    }
                }
                // Go to the group page instead of the referer url if we are in one of those cases :
                //   - pref 'Go to the group homepage only if logging in from the default homepage' (limitedGoGroupHome) is disabled,
                //   - referer url (e.g. http://example.com/tiki/tiki-index.php?page=Homepage ) is the homepage (tikiIndex),
                //   - referer url complete path ( e.g. /tiki/tiki-index.php?page=Homepage ) is the homepage,
                //   - referer url relative path ( e.g. tiki-index.php?page=Homepage ) is the homepage
                //   - referer url SEF page ( e.g. /tiki/Homepage ) is the homepage
                //   - one of the three cases listed above, but compared to anonymous page instead of global homepage
                //   - first login after registration
                //   - last case ($tikiIndex_full != '') :
                //       wiki homepage could have been saved as 'tiki-index.php' instead of 'tiki-index.php?page=Homepage'.
                //       ... so we also need to check against : homepage + '?page=' + default wiki pagename
                //
                include_once('tiki-sefurl.php');
                if (
436
                    $url == '' || preg_match('/(tiki-register|tiki-login_validate|tiki-login_scr)\.php/', $url) || $prefs['limitedGoGroupHome'] == 'n'
437
438
439
440
                    || $url == $prefs['site_tikiIndex'] || $url_path == $prefs['site_tikiIndex'] || basename($url_path) == $prefs['site_tikiIndex']
                    || ($anonymous_homepage != '' && ($url == $anonymous_homepage || $url_path == $anonymous_homepage || basename($url_path) == $anonymous_homepage))
                    || filter_out_sefurl($anonymous_homepage) == basename($url_path)
                    || ($tikiIndex_full != '' && ( basename($url_path) == $tikiIndex_full || basename($url_path) == filter_out_sefurl($tikiIndex_full) ))
441
                ) {
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
                    $groupHome = $userlib->get_user_default_homepage($user);
                    if ($groupHome != '') {
                        $url = (preg_match('/^(\/|https?:)/', $groupHome)) ? $groupHome : filter_out_sefurl('tiki-index.php?page=' . urlencode($groupHome));
                    }
                }
            }
            // Unset session variable in case user su's
            unset($_SESSION['loginfrom']);
            // No sense in sending user to registration page or no page at all
            // This happens if the user has just registered and it's first login
            if ($url == '' || preg_match('/(tiki-register|tiki-login_validate|tiki-login_scr)\.php/', $url)) {
                $url = $prefs['tikiIndex'];
            }
            // Now if the remember me feature is on and the user checked the rememberme checkbox then ...
            if ($prefs['rememberme'] == 'always' || $prefs['rememberme'] != 'disabled' && isset($_REQUEST['rme']) && $_REQUEST['rme'] == 'on') {
                $userInfo = $userlib->get_user_info($user);
                $userId = $userInfo['userId'];
                $secret = $userlib->create_user_cookie($userId);
                setcookie($user_cookie_site, $secret . '.' . $userId, $tikilib->now + $prefs['remembertime'], $prefs['feature_intertiki_sharedcookie'] == 'y' ? '/' : $prefs['cookie_path'], $prefs['cookie_domain']);
                $logslib->add_log('login', 'got a cookie for ' . $prefs['remembertime'] . ' seconds');
            }
        }
    }
} else {    // if ($isvalid) = false
    // check if site is closed
    if ($prefs['site_closed'] === 'y') {
        unset($bypass_siteclose_check);
        if (isset($_REQUEST['ticket'])) {
            unset($_SESSION['tickets'][$_REQUEST['ticket']]);
        }
        switch ($error) {
            case PASSWORD_INCORRECT:
                http_response_code(401);
                $error = tra('Invalid username or password');
                break;
            case TWO_FA_INCORRECT:
                http_response_code(401);
                $error = tra('Invalid two-factor code ');
                break;
            case USER_NOT_FOUND:
                http_response_code(401);
                $error = tra('Invalid username or password');
                break;
            case ACCOUNT_DISABLED:
                http_response_code(403);
                $error = tra('Account requires administrator approval.');
                break;
            case ACCOUNT_WAITING_USER:
                http_response_code(403);
                $error = tra('You did not validate your account.');
                break;
            case USER_AMBIGOUS:
                http_response_code(400);
                $error = tra('You must use the right case for your username.');
                break;
            case USER_NOT_VALIDATED:
                http_response_code(403);
                $error = tra('You are not yet validated.');
                break;
            case USER_ALREADY_LOGGED:
                http_response_code(400);
                $error = tra('You are already logged in.');
                break;
            case EMAIL_AMBIGUOUS:
                http_response_code(400);
                $error = tra("There is more than one user account with this email. Please contact the administrator.");
                break;
            default:
                http_response_code(401);
                $error = tra('Authentication error');
        }
        $error_login = $error;
        include 'lib/setup/site_closed.php';
    }

    if (isset($_REQUEST['url'])) {
        $smarty->assign('url', $_REQUEST['url']);
    }
    $module_params['show_forgot'] = ($prefs['forgotPass'] == 'y' && $prefs['change_password'] == 'y') ? 'y' : 'n';
    $module_params['show_register'] = ($prefs['allowRegister'] === 'y') ? 'y' : 'n';
    $smarty->assign('module_params', $module_params);
    if (
524
        ($error == PASSWORD_INCORRECT || $error == TWO_FA_INCORRECT)
525
        && ($prefs['unsuccessful_logins'] >= 0 || $prefs['unsuccessful_logins_invalid'] >= 0)
526
    ) {
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
        $nb_bad_logins = $userlib->unsuccessful_logins($requestedUser);
        $nb_bad_logins++ ;
        $userlib->set_unsuccessful_logins($requestedUser, $nb_bad_logins);
        if ($prefs['unsuccessful_logins_invalid'] > 0 && ($nb_bad_logins >= $prefs['unsuccessful_logins_invalid'])) {
            $info = $userlib->get_user_info($requestedUser);
            $userlib->change_user_waiting($requestedUser, 'a');
            $msg = sprintf(tra('%d or more unsuccessful login attempts have been made.'), $prefs['unsuccessful_logins_invalid']);
            $msg .= ' ' . tra('Your account has been suspended.') . ' ' . tra('Contact your site administrator to reactivate it.');
            $smarty->assign('msg', $msg);
            if ($nb_bad_logins % $prefs['unsuccessful_logins_invalid'] == 0) {
                //don't send an email after every failed login
                include_once('lib/webmail/tikimaillib.php');
                $mail = new TikiMail();
                $smarty->assign('mail_user', $requestedUser);
                $foo = parse_url($_SERVER['REQUEST_URI']);
                $mail_machine = $tikilib->httpPrefix(true) . str_replace('tiki-login.php', '', $foo['path']);
                $smarty->assign('mail_machine', $mail_machine);
                $mail->setText($smarty->fetch('mail/unsuccessful_logins_suspend.tpl'));
                $mail->setSubject($smarty->fetch('mail/unsuccessful_logins_suspend_subject.tpl'));
                $emails = ! empty($prefs['validator_emails']) ? preg_split('/,/', $prefs['validator_emails']) : (! empty($prefs['sender_email']) ? [$prefs['sender_email']] : '');
                if (! $mail->send([$info['email']]) || ! $mail->send($emails)) {
                    $smarty->assign('msg', tra("The mail can't be sent. Contact the administrator"));
                    $smarty->display("error.tpl");
                    die;
                }
            }
            $smarty->assign('mid', 'tiki-information.tpl');
            $smarty->display('tiki.tpl');
            die;
        } elseif ($prefs['unsuccessful_logins'] > 0 && ($nb_bad_logins >= $prefs['unsuccessful_logins'])) {
            $msg = sprintf(tra('%d or more unsuccessful login attempts have been made.'), $prefs['unsuccessful_logins']);
            $smarty->assign('msg', $msg);
            if ($nb_bad_logins % $prefs['unsuccessful_logins'] == 0) {
                //don't send an email after every failed login
                if ($userlib->send_confirm_email($requestedUser, 'unsuccessful_logins')) {
                    $smarty->assign('msg', $msg . ' ' . tra('An email has been sent to you with the instructions to follow.'));
                }
            }
            $show_history_back_link = 'y';
            $smarty->assign_by_ref('show_history_back_link', $show_history_back_link);
            $smarty->assign('mid', 'tiki-information.tpl');
            $smarty->display("tiki.tpl");
            die;
        }
    }
    switch ($error) {
        case PASSWORD_INCORRECT:
            http_response_code(401);
            $error = tra('Invalid username or password');
            break;
        case TWO_FA_INCORRECT:
            http_response_code(401);
            $error = tra('Invalid two-factor code');
            break;
        case USER_NOT_FOUND:
            http_response_code(401);
            $smarty->assign('error_login', $error);
            $smarty->assign('mid', 'tiki-login.tpl');
            $smarty->assign('error_user', $_REQUEST["user"]);
            $smarty->display('tiki.tpl');
            exit;

        case ACCOUNT_DISABLED:
            http_response_code(403);
            $error = tra('Account requires administrator approval.');
            break;

        case ACCOUNT_WAITING_USER:
            http_response_code(403);
            $error = tra('You did not validate your account.');
            $extraButton = ['href' => 'tiki-send_mail.php?user=' . urlencode($_REQUEST['user']), 'text' => tra('Resend'), 'comment' => tra('You should have received an email. Check your mailbox and your spam box. Otherwise click on the button to resend the email')];
            break;

        case USER_AMBIGOUS:
            http_response_code(400);
            $error = tra('You must use the right case for your username.');
            break;

        case USER_NOT_VALIDATED:
            http_response_code(403);
            $error = tra('You are not yet validated.');
            break;

        case USER_ALREADY_LOGGED:
            http_response_code(400);
            $error = tra('You are already logged in.');
            break;

        case EMAIL_AMBIGUOUS:
            http_response_code(400);
            $error = tra("There is more than one user account with this email. Please contact the administrator.");
            break;

        default:
            http_response_code(401);
            $error = tra('Authentication error');
    }
    if (isset($extraButton)) {
        $smarty->assign_by_ref('extraButton', $extraButton);
    }

    //  Report error "inline" with the login module
    $smarty->assign('error_login', $error);
    $smarty->assign('mid', 'tiki-login.tpl');
    $smarty->display('tiki.tpl');
    exit;
633
}
634
if (isset($user) && ($isOpenIdValid || $access->checkCsrf(null, null, null, null, null, 'page'))) {
635
636
637
638
639
640
641
642
    TikiLib::events()->trigger(
        'tiki.user.login',
        [
            'type' => 'user',
            'object' => $user,
            'user' => $user,
        ]
    );
chealer's avatar
chealer committed
643
}
644

chealer's avatar
chealer committed
645
// RFC 2616 defines that the 'Location' HTTP headerconsists of an absolute URI
rjsmelo's avatar
rjsmelo committed
646
if (! preg_match('/^https?\:/i', $url)) {
647
    $url = (preg_match('/^\//', $url) ? $url_scheme . '://' . $url_host . (($url_port != '') ? ":$url_port" : '') : $base_url) . $url;
chealer's avatar
chealer committed
648
649
}
// Force HTTP mode if needed
rjsmelo's avatar
rjsmelo committed
650
if ($stay_in_ssl_mode != 'y' || ! $https_mode) {
651
    $url = str_replace('https://', 'http://', $url);
chealer's avatar
chealer committed
652
}
653

rjsmelo's avatar
rjsmelo committed
654
/*
655
656
657
 * If user logged in with HTTPS after requesting a non-TLS URL but "stay"ing in TLS mode was requested, redirect to HTTPS equivalent of the original URL requested.
 * Not sure why we don't just use the initial URI requested. Chealer 2017-04-19
 */
chealer's avatar
chealer committed
658
if ($stay_in_ssl_mode == 'y' && $https_mode) {
659
    $url = str_replace('http://', 'https://', $url);
chealer's avatar
chealer committed
660
}
661

rjsmelo's avatar
rjsmelo committed
662
if (defined('SID') && SID != '') {
663
    $url .= ((strpos($url, '?') === false) ? '?' : '&') . SID;
rjsmelo's avatar
rjsmelo committed
664
}
665

666
// Check if a wizard should be run.
arildb's avatar
arildb committed
667
// If a wizard is run, it will return to the $url location when it has completed. Thus no code after $wizardlib->onLogin will be executed
668
// The user must be actually logged in before onLogin is called. If $isdue is set, then: "Note that the user is not logged in he's just validated to change his password"
669
if (! $isdue && ($isOpenIdValid || $access->checkCsrf(null, null, null, null, null, 'page'))) {
670
671
672
673
674
675
676
677
678
    if ($prefs['feature_user_encryption'] === 'y') {
        // Notify CryptLib about the login
        $cryptlib = TikiLib::lib('crypt');
        $cryptlib->onUserLogin($pass);
    }

    // Process wizard
    $wizardlib = TikiLib::lib('wizard');
    $wizardlib->onLogin($user, $url);
679
}
680

chealer's avatar
chealer committed
681
682
header('Location: ' . $url);
exit;