[TASK] Replace Space Indent into Tab indent (CGL Cleanup)
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_beuserauth.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains class for TYPO3 backend user authentication
29 *
30 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 * @internal
34 */
35
36
37 /**
38 * TYPO3 user authentication, backend
39 * Could technically have been the same class as t3lib_userauthgroup since these two are always used together and only together.
40 * t3lib_userauthgroup contains most of the functions used for checking permissions, authenticating users, setting up the user etc. This class is most interesting in terms of an API for user from outside.
41 * This class contains the configuration of the database fields used plus some functions for the authentication process of backend users.
42 *
43 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
44 * @package TYPO3
45 * @subpackage t3lib
46 */
47 class t3lib_beUserAuth extends t3lib_userAuthGroup {
48 var $session_table = 'be_sessions'; // Table to use for session data.
49
50 var $user_table = 'be_users'; // Table in database with userdata
51 var $username_column = 'username'; // Column for login-name
52 var $userident_column = 'password'; // Column for password
53 var $userid_column = 'uid'; // Column for user-id
54 var $lastLogin_column = 'lastlogin';
55
56 var $enablecolumns = Array(
57 'rootLevel' => 1,
58 'deleted' => 'deleted',
59 'disabled' => 'disable',
60 'starttime' => 'starttime',
61 'endtime' => 'endtime'
62 );
63
64 var $formfield_uname = 'username'; // formfield with login-name
65 var $formfield_uident = 'userident'; // formfield with password
66 var $formfield_chalvalue = 'challenge'; // formfield with a unique value which is used to encrypt the password and username
67 var $formfield_status = 'login_status'; // formfield with status: *'login', 'logout'
68
69 var $writeStdLog = 1; // Decides if the writelog() function is called at login and logout
70 var $writeAttemptLog = 1; // If the writelog() functions is called if a login-attempt has be tried without success
71
72 var $auth_timeout_field = 6000; // if > 0 : session-timeout in seconds. if FALSE/<0 : no timeout. if string: The string is fieldname from the usertable where the timeout can be found.
73 var $lifetime = 0; // 0 = Session-cookies. If session-cookies, the browser will stop session when the browser is closed. Else it keeps the session for $lifetime seconds.
74 var $challengeStoredInCookie = TRUE;
75
76
77 // User Config:
78 var $uc;
79
80 // User Config Default values:
81 // The array may contain other fields for configuration. For this, see "setup" extension and "TSConfig" document (User TSconfig, "setup.[xxx]....")
82 /*
83 Reserved keys for other storage of session data:
84 moduleData
85 moduleSessionID
86 */
87 var $uc_default = Array(
88 'interfaceSetup' => '', // serialized content that is used to store interface pane and menu positions. Set by the logout.php-script
89 'moduleData' => Array(), // user-data for the modules
90 'thumbnailsByDefault' => 1,
91 'emailMeAtLogin' => 0,
92 'condensedMode' => 0,
93 'noMenuMode' => 0,
94 'startModule' => 'help_aboutmodules',
95 'hideSubmoduleIcons' => 0,
96 'helpText' => 1,
97 'titleLen' => 50,
98 'edit_wideDocument' => '0',
99 'edit_showFieldHelp' => 'icon',
100 'edit_RTE' => '1',
101 'edit_docModuleUpload' => '1',
102 'enableFlashUploader' => '1',
103 'navFrameWidth' => '', // Default is 245 pixels
104 'navFrameResizable' => 0,
105 'resizeTextareas' => 1,
106 'resizeTextareas_MaxHeight' => 500,
107 'resizeTextareas_Flexible' => 0,
108 );
109
110 /**
111 * Constructor
112 */
113 public function __construct() {
114 $this->name = self::getCookieName();
115 $this->loginType = 'BE';
116 }
117
118 /**
119 * @static
120 * @return string
121 *
122 * returns the configured cookie name
123 */
124 public static function getCookieName() {
125 $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
126 if (empty($configuredCookieName)) {
127 $configuredCookieName = 'be_typo_user';
128 }
129 return $configuredCookieName;
130 }
131
132
133 /**
134 * Sets the security level for the Backend login
135 *
136 * @return void
137 */
138 function start() {
139 $securityLevel = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['loginSecurityLevel']);
140 $standardSecurityLevels = array('normal', 'challenged', 'superchallenged');
141
142 // The TYPO3 standard login service relies on $this->security_level being set
143 // to 'superchallenged' because of the password in the database is stored as md5 hash.
144 // @deprecated since 4.7
145 // These lines are here for compatibility purpose only, can be removed in 4.9.
146 // @see tx_sv_auth::processLoginData()
147 if (!empty($securityLevel) && !in_array($securityLevel, $standardSecurityLevels)) {
148 $this->security_level = $securityLevel;
149 } else {
150 $this->security_level = 'superchallenged';
151 }
152
153 parent::start();
154 }
155
156 /**
157 * If TYPO3_CONF_VARS['BE']['enabledBeUserIPLock'] is enabled and an IP-list is found in the User TSconfig objString "options.lockToIP", then make an IP comparison with REMOTE_ADDR and return the outcome (TRUE/FALSE)
158 *
159 * @return boolean TRUE, if IP address validates OK (or no check is done at all)
160 * @access private
161 */
162 function checkLockToIP() {
163 $out = 1;
164 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['enabledBeUserIPLock']) {
165 $IPList = $this->getTSConfigVal('options.lockToIP');
166 if (trim($IPList)) {
167 $baseIP = t3lib_div::getIndpEnv('REMOTE_ADDR');
168 $out = t3lib_div::cmpIP($baseIP, $IPList);
169 }
170 }
171 return $out;
172 }
173
174 /**
175 * Check if user is logged in and if so, call ->fetchGroupData() to load group information and access lists of all kind, further check IP, set the ->uc array and send login-notification email if required.
176 * If no user is logged in the default behaviour is to exit with an error message, but this will happen ONLY if the constant TYPO3_PROCEED_IF_NO_USER is set TRUE.
177 * This function is called right after ->start() in fx. init.php
178 *
179 * @return void
180 */
181 function backendCheckLogin() {
182 if (!$this->user['uid']) {
183 if (!defined('TYPO3_PROCEED_IF_NO_USER') || !TYPO3_PROCEED_IF_NO_USER) {
184 t3lib_utility_Http::redirect($GLOBALS['BACK_PATH']);
185 }
186 } else { // ...and if that's the case, call these functions
187 $this->fetchGroupData(); // The groups are fetched and ready for permission checking in this initialization. Tables.php must be read before this because stuff like the modules has impact in this
188 if ($this->checkLockToIP()) {
189 if ($this->isUserAllowedToLogin()) {
190 $this->backendSetUC(); // Setting the UC array. It's needed with fetchGroupData first, due to default/overriding of values.
191 $this->emailAtLogin(); // email at login - if option set.
192 } else {
193 throw new RuntimeException('Login Error: TYPO3 is in maintenance mode at the moment. Only administrators are allowed access.', 1294585860);
194 }
195 } else {
196 throw new RuntimeException('Login Error: IP locking prevented you from being authorized. Can\'t proceed, sorry.', 1294585861);
197 }
198 }
199 }
200
201 /**
202 * If the backend script is in CLI mode, it will try to load a backend user named by the CLI module name (in lowercase)
203 *
204 * @return boolean Returns TRUE if a CLI user was loaded, otherwise FALSE!
205 */
206 function checkCLIuser() {
207 // First, check if cliMode is enabled:
208 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
209 if (!$this->user['uid']) {
210 if (substr($GLOBALS['MCONF']['name'], 0, 5) == '_CLI_') {
211 $userName = strtolower($GLOBALS['MCONF']['name']);
212 $this->setBeUserByName($userName);
213 if ($this->user['uid']) {
214 if (!$this->isAdmin()) {
215 return TRUE;
216 } else {
217 fwrite(STDERR, 'ERROR: CLI backend user "' . $userName . '" was ADMIN which is not allowed!' . LF . LF);
218 exit(3);
219 }
220 } else {
221 fwrite(STDERR, 'ERROR: No backend user named "' . $userName . '" was found!' . LF . LF);
222 exit(3);
223 }
224 } else {
225 fwrite(STDERR, 'ERROR: Module name, "' . $GLOBALS['MCONF']['name'] . '", was not prefixed with "_CLI_"' . LF . LF);
226 exit(3);
227 }
228 } else {
229 fwrite(STDERR, 'ERROR: Another user was already loaded which is impossible in CLI mode!' . LF . LF);
230 exit(3);
231 }
232 }
233 }
234
235 /**
236 * Initialize the internal ->uc array for the backend user
237 * Will make the overrides if necessary, and write the UC back to the be_users record if changes has happend
238 *
239 * @return void
240 * @internal
241 */
242 function backendSetUC() {
243 // UC - user configuration is a serialized array inside the userobject
244 $temp_theSavedUC = unserialize($this->user['uc']); // if there is a saved uc we implement that instead of the default one.
245 if (is_array($temp_theSavedUC)) {
246 $this->unpack_uc($temp_theSavedUC);
247 }
248 // Setting defaults if uc is empty
249 if (!is_array($this->uc)) {
250 $this->uc = array_merge(
251 $this->uc_default,
252 (array) $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUC'],
253 t3lib_div::removeDotsFromTS((array) $this->getTSConfigProp('setup.default'))
254 );
255 $this->overrideUC();
256 $U = 1;
257 }
258 // If TSconfig is updated, update the defaultUC.
259 if ($this->userTSUpdated) {
260 $this->overrideUC();
261 $U = 1;
262 }
263 // Setting default lang from be_user record.
264 if (!isset($this->uc['lang'])) {
265 $this->uc['lang'] = $this->user['lang'];
266 $U = 1;
267 }
268 // Setting the time of the first login:
269 if (!isset($this->uc['firstLoginTimeStamp'])) {
270 $this->uc['firstLoginTimeStamp'] = $GLOBALS['EXEC_TIME'];
271 $U = TRUE;
272 }
273
274 // Saving if updated.
275 if ($U) {
276 $this->writeUC(); // Method from the t3lib_userauth class.
277 }
278 }
279
280 /**
281 * Override: Call this function every time the uc is updated.
282 * That is 1) by reverting to default values, 2) in the setup-module, 3) userTS changes (userauthgroup)
283 *
284 * @return void
285 * @internal
286 */
287 function overrideUC() {
288 $this->uc = array_merge((array) $this->uc, (array) $this->getTSConfigProp('setup.override')); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
289 }
290
291 /**
292 * Clears the user[uc] and ->uc to blank strings. Then calls ->backendSetUC() to fill it again with reset contents
293 *
294 * @return void
295 * @internal
296 */
297 function resetUC() {
298 $this->user['uc'] = '';
299 $this->uc = '';
300 $this->backendSetUC();
301 }
302
303 /**
304 * Will send an email notification to warning_email_address/the login users email address when a login session is just started.
305 * Depends on various parameters whether mails are send and to whom.
306 *
307 * @return void
308 * @access private
309 */
310 function emailAtLogin() {
311 if ($this->loginSessionStarted) {
312 // Send notify-mail
313 $subject = 'At "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '"' .
314 ' from ' . t3lib_div::getIndpEnv('REMOTE_ADDR') .
315 (t3lib_div::getIndpEnv('REMOTE_HOST') ? ' (' . t3lib_div::getIndpEnv('REMOTE_HOST') . ')' : '');
316 $msg = sprintf('User "%s" logged in from %s (%s) at "%s" (%s)',
317 $this->user['username'],
318 t3lib_div::getIndpEnv('REMOTE_ADDR'),
319 t3lib_div::getIndpEnv('REMOTE_HOST'),
320 $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
321 t3lib_div::getIndpEnv('HTTP_HOST')
322 );
323
324 // Warning email address
325 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr']) {
326 $warn = 0;
327 $prefix = '';
328 if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode']) & 1) { // first bit: All logins
329 $warn = 1;
330 $prefix = $this->isAdmin() ? '[AdminLoginWarning]' : '[LoginWarning]';
331 }
332 if ($this->isAdmin() && (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode']) & 2)) { // second bit: Only admin-logins
333 $warn = 1;
334 $prefix = '[AdminLoginWarning]';
335 }
336 if ($warn) {
337 $from = t3lib_utility_Mail::getSystemFrom();
338 /** @var $mail t3lib_mail_Message */
339 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
340 $mail->setTo($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'])
341 ->setFrom($from)
342 ->setSubject($prefix . ' ' . $subject)
343 ->setBody($msg);
344 $mail->send();
345 }
346 }
347
348 // If An email should be sent to the current user, do that:
349 if ($this->uc['emailMeAtLogin'] && strstr($this->user['email'], '@')) {
350 $from = t3lib_utility_Mail::getSystemFrom();
351 /** @var $mail t3lib_mail_Message */
352 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
353 $mail->setTo($this->user['email'])
354 ->setFrom($from)
355 ->setSubject($subject)
356 ->setBody($msg);
357 $mail->send();
358 }
359 }
360 }
361
362 /**
363 * Determines whether a backend user is allowed to access the backend.
364 *
365 * The conditions are:
366 * + backend user is a regular user and adminOnly is not defined
367 * + backend user is an admin user
368 * + backend user is used in CLI context and adminOnly is explicitely set to "2"
369 * + backend user is being controlled by an admin user
370 *
371 * @return boolean Whether a backend user is allowed to access the backend
372 */
373 protected function isUserAllowedToLogin() {
374 $isUserAllowedToLogin = FALSE;
375 $adminOnlyMode = $GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'];
376
377 // Backend user is allowed if adminOnly is not set or user is an admin:
378 if (!$adminOnlyMode || $this->isAdmin()) {
379 $isUserAllowedToLogin = TRUE;
380 // Backend user is allowed if adminOnly is set to 2 (CLI) and a CLI process is running:
381 } elseif ($adminOnlyMode == 2 && (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
382 $isUserAllowedToLogin = TRUE;
383 // Backend user is allowed if an admin has switched to that user
384 } elseif ($this->user['ses_backuserid']) {
385 $backendUserId = intval($this->user['ses_backuserid']);
386 $whereAdmin = 'uid=' . $backendUserId . ' AND admin=1' . t3lib_BEfunc::BEenableFields('be_users');
387 if ($GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'be_users', $whereAdmin) > 0) {
388 $isUserAllowedToLogin = TRUE;
389 }
390 }
391
392 return $isUserAllowedToLogin;
393 }
394
395 /**
396 * Logs out the current user and clears the form protection tokens.
397 */
398 public function logoff() {
399 if (isset($GLOBALS['BE_USER'])) {
400 t3lib_formProtection_Factory::get()->clean();
401 }
402 parent::logoff();
403 }
404 }
405
406 ?>