]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Finish t() for src
[friendica.git] / src / Module / Login.php
1 <?php
2 /**
3  * @file src/Module/Login.php
4  */
5 namespace Friendica\Module;
6
7 use Friendica\BaseModule;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\User;
13 use dba;
14
15 require_once 'boot.php';
16 require_once 'include/datetime.php';
17 require_once 'include/pgettext.php';
18 require_once 'include/security.php';
19 require_once 'include/text.php';
20
21 /**
22  * Login module
23  *
24  * @author Hypolite Petovan mrpetovan@gmail.com
25  */
26 class Login extends BaseModule
27 {
28         public static function content()
29         {
30                 $a = self::getApp();
31
32                 if (x($_SESSION, 'theme')) {
33                         unset($_SESSION['theme']);
34                 }
35
36                 if (x($_SESSION, 'mobile-theme')) {
37                         unset($_SESSION['mobile-theme']);
38                 }
39
40                 if (local_user()) {
41                         goaway(self::getApp()->get_baseurl());
42                 }
43
44                 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
45         }
46
47         public static function post()
48         {
49                 session_unset();
50                 // OpenId Login
51                 if (
52                         !x($_POST, 'password')
53                         && (
54                                 x($_POST, 'openid_url')
55                                 || x($_POST, 'username')
56                         )
57                 ) {
58                         $noid = Config::get('system', 'no_openid');
59
60                         $openid_url = trim($_POST['openid_url'] ? : $_POST['username']);
61
62                         // if it's an email address or doesn't resolve to a URL, fail.
63                         if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) {
64                                 notice(L10n::t('Login failed.') . EOL);
65                                 goaway(self::getApp()->get_baseurl());
66                                 // NOTREACHED
67                         }
68
69                         // Otherwise it's probably an openid.
70                         try {
71                                 require_once 'library/openid.php';
72                                 $openid = new \LightOpenID;
73                                 $openid->identity = $openid_url;
74                                 $_SESSION['openid'] = $openid_url;
75                                 $_SESSION['remember'] = $_POST['remember'];
76                                 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
77                                 goaway($openid->authUrl());
78                         } catch (Exception $e) {
79                                 notice(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . L10n::t('The error message was:') . ' ' . $e->getMessage());
80                         }
81                         // NOTREACHED
82                 }
83
84                 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
85                         $record = null;
86
87                         $addon_auth = [
88                                 'username' => trim($_POST['username']),
89                                 'password' => trim($_POST['password']),
90                                 'authenticated' => 0,
91                                 'user_record' => null
92                         ];
93
94                         /*
95                          * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
96                          * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
97                          * and later addons should not interfere with an earlier one that succeeded.
98                          */
99                         Addon::callHooks('authenticate', $addon_auth);
100
101                         if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
102                                 $record = $addon_auth['user_record'];
103                         } else {
104                                 $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
105                                 if ($user_id) {
106                                         $record = dba::selectFirst('user', [], ['uid' => $user_id]);
107                                 }
108                         }
109
110                         if (!$record || !count($record)) {
111                                 logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
112                                 notice(L10n::t('Login failed.') . EOL);
113                                 goaway(self::getApp()->get_baseurl());
114                         }
115
116                         if (!$_POST['remember']) {
117                                 new_cookie(0); // 0 means delete on browser exit
118                         }
119
120                         // if we haven't failed up this point, log them in.
121                         $_SESSION['remember'] = $_POST['remember'];
122                         $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
123                         authenticate_success($record, true, true);
124
125                         if (x($_SESSION, 'return_url')) {
126                                 $return_url = $_SESSION['return_url'];
127                                 unset($_SESSION['return_url']);
128                         } else {
129                                 $return_url = '';
130                         }
131
132                         goaway($return_url);
133                 }
134         }
135
136         /**
137          * @brief Tries to auth the user from the cookie or session
138          *
139          * @todo Should be moved to Friendica\Core\Session when it's created
140          */
141         public static function sessionAuth()
142         {
143                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
144                 if (isset($_COOKIE["Friendica"])) {
145                         $data = json_decode($_COOKIE["Friendica"]);
146                         if (isset($data->uid)) {
147
148                                 $user = dba::selectFirst('user', [],
149                                         [
150                                                 'uid'             => $data->uid,
151                                                 'blocked'         => false,
152                                                 'account_expired' => false,
153                                                 'account_removed' => false,
154                                                 'verified'        => true,
155                                         ]
156                                 );
157                                 if (DBM::is_result($user)) {
158                                         if ($data->hash != cookie_hash($user)) {
159                                                 logger("Hash for user " . $data->uid . " doesn't fit.");
160                                                 nuke_session();
161                                                 goaway(self::getApp()->get_baseurl());
162                                         }
163
164                                         // Renew the cookie
165                                         // Expires after 7 days by default,
166                                         // can be set via system.auth_cookie_lifetime
167                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
168                                         new_cookie($authcookiedays * 24 * 60 * 60, $user);
169
170                                         // Do the authentification if not done by now
171                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
172                                                 authenticate_success($user);
173
174                                                 if (Config::get('system', 'paranoia')) {
175                                                         $_SESSION['addr'] = $data->ip;
176                                                 }
177                                         }
178                                 }
179                         }
180                 }
181
182                 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
183                         if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
184                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
185                                         intval($_SESSION['visitor_id'])
186                                 );
187                                 if (DBM::is_result($r)) {
188                                         self::getApp()->contact = $r[0];
189                                 }
190                         }
191
192                         if (x($_SESSION, 'uid')) {
193                                 // already logged in user returning
194                                 $check = Config::get('system', 'paranoia');
195                                 // extra paranoia - if the IP changed, log them out
196                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
197                                         logger('Session address changed. Paranoid setting in effect, blocking session. ' .
198                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
199                                         nuke_session();
200                                         goaway(self::getApp()->get_baseurl());
201                                 }
202
203                                 $user = dba::selectFirst('user', [],
204                                         [
205                                                 'uid'             => $_SESSION['uid'],
206                                                 'blocked'         => false,
207                                                 'account_expired' => false,
208                                                 'account_removed' => false,
209                                                 'verified'        => true,
210                                         ]
211                                 );
212                                 if (!DBM::is_result($user)) {
213                                         nuke_session();
214                                         goaway(self::getApp()->get_baseurl());
215                                 }
216
217                                 // Make sure to refresh the last login time for the user if the user
218                                 // stays logged in for a long time, e.g. with "Remember Me"
219                                 $login_refresh = false;
220                                 if (!x($_SESSION['last_login_date'])) {
221                                         $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
222                                 }
223                                 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
224                                         $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
225                                         $login_refresh = true;
226                                 }
227                                 authenticate_success($user, false, false, $login_refresh);
228                         }
229                 }
230         }
231
232         /**
233          * @brief Wrapper for adding a login box.
234          *
235          * @param string $return_url The url relative to the base the user should be sent
236          *                                                       back to after login completes
237          * @param bool $register If $register == true provide a registration link.
238          *                                               This will most always depend on the value of $a->config['register_policy'].
239          * @param array $hiddens  optional
240          *
241          * @return string Returns the complete html for inserting into the page
242          *
243          * @hooks 'login_hook' string $o
244          */
245         public static function form($return_url = null, $register = false, $hiddens = [])
246         {
247                 $a = self::getApp();
248                 $o = '';
249                 $reg = false;
250                 if ($register) {
251                         $reg = [
252                                 'title' => L10n::t('Create a New Account'),
253                                 'desc' => L10n::t('Register')
254                         ];
255                 }
256
257                 $noid = Config::get('system', 'no_openid');
258
259                 if (is_null($return_url)) {
260                         $return_url = $a->query_string;
261                 }
262
263                 if (local_user()) {
264                         $tpl = get_markup_template('logout.tpl');
265                 } else {
266                         $a->page['htmlhead'] .= replace_macros(
267                                 get_markup_template('login_head.tpl'),
268                                 [
269                                         '$baseurl' => $a->get_baseurl(true)
270                                 ]
271                         );
272
273                         $tpl = get_markup_template('login.tpl');
274                         $_SESSION['return_url'] = $return_url;
275                 }
276
277                 $o .= replace_macros(
278                         $tpl,
279                         [
280                                 '$dest_url'     => self::getApp()->get_baseurl(true) . '/login',
281                                 '$logout'       => L10n::t('Logout'),
282                                 '$login'        => L10n::t('Login'),
283
284                                 '$lname'        => ['username', L10n::t('Nickname or Email: ') , '', ''],
285                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
286                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
287
288                                 '$openid'       => !$noid,
289                                 '$lopenid'      => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
290
291                                 '$hiddens'      => $hiddens,
292
293                                 '$register'     => $reg,
294
295                                 '$lostpass'     => L10n::t('Forgot your password?'),
296                                 '$lostlink'     => L10n::t('Password Reset'),
297
298                                 '$tostitle'     => L10n::t('Website Terms of Service'),
299                                 '$toslink'      => L10n::t('terms of service'),
300
301                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
302                                 '$privacylink'  => L10n::t('privacy policy'),
303                         ]
304                 );
305
306                 Addon::callHooks('login_hook', $o);
307
308                 return $o;
309         }
310 }