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