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