3 * Session handling class and associated functions
5 * This subpackage provides some functions that are useful around web
6 * application session management.
8 * The class is intended to be as lightweight as possible while holding
9 * all session data in the database:
10 * - Session hash is not predictable.
11 * - No clear text information is held in cookies.
12 * - Passwords are generally salted MD5 hashes, but individual users may
13 * have plain text passwords set by an administrator.
14 * - Temporary passwords are supported.
15 * - Logout is supported
16 * - "Remember me" cookies are supported, and will result in a new
17 * Session for each browser session.
21 * @author Andrew McMillan <andrew@mcmillan.net.nz>
22 * @copyright Catalyst IT Ltd, Morphoss Ltd <http://www.morphoss.com/>
23 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
25 require_once('AWLUtilities.php');
26 require_once('PgQuery.php');
27 require_once('EMail.php');
31 * Checks what a user entered against any currently valid temporary passwords on their account.
32 * @param string $they_sent What the user entered.
33 * @param int $user_no Which user is attempting to log on.
34 * @return boolean Whether or not the user correctly guessed a temporary password within the necessary window of opportunity.
36 function check_temporary_passwords( $they_sent, $user_no ) {
37 $sql = 'SELECT 1 AS ok FROM tmp_password WHERE user_no = ? AND password = ? AND valid_until > current_timestamp';
38 $qry = new PgQuery( $sql, $user_no, $they_sent );
39 if ( $qry->Exec('Session::check_temporary_passwords') ) {
40 dbg_error_log( "Login", " check_temporary_passwords: Rows = $qry->rows");
41 if ( $row = $qry->Fetch() ) {
42 dbg_error_log( "Login", " check_temporary_passwords: OK = $row->ok");
43 // Remove all the temporary passwords for that user...
44 $sql = 'DELETE FROM tmp_password WHERE user_no = ? ';
45 $qry = new PgQuery( $sql, $user_no );
46 $qry->Exec('Login',__LINE__
,__FILE__
);
54 * A class for creating and holding session information.
72 * The user_no of the logged in user.
78 * A unique id for this user's logged-in session.
84 * The user's username used to log in.
87 var $username = 'guest';
90 * The user's full name from their usr record.
93 var $fullname = 'Guest';
96 * The user's email address from their usr record.
102 * Whether this user has actually logged in.
105 var $logged_in = false;
108 * Whether the user logged in to view the current page. Perhaps some details on the
109 * login form might pollute an editable form and result in an unplanned submit. This
110 * can be used to program around such a problem.
113 var $just_logged_in = false;
116 * The date and time that the user logged on during their last session.
119 var $last_session_start;
122 * The date and time that the user requested their last page during their last
126 var $last_session_end;
130 * Create a new Session object.
132 * If a session identifier is supplied, or we can find one in a cookie, we validate it
133 * and consider the person logged in. We read some useful session and user data in
134 * passing as we do this.
136 * The session identifier contains a random value, hashed, to provide validation. This
137 * could be hijacked if the traffic was sniffable so sites who are paranoid about security
138 * should only do this across SSL.
140 * A worthwhile enhancement would be to add some degree of external configurability to
143 * @param string $sid A session identifier.
145 function Session( $sid="" )
147 global $sid, $sysname;
149 $this->roles
= array();
150 $this->logged_in
= false;
151 $this->just_logged_in
= false;
152 $this->login_failed
= false;
155 if ( ! isset($_COOKIE['sid']) ) return;
156 $sid = $_COOKIE['sid'];
159 list( $session_id, $session_key ) = explode( ';', $sid, 2 );
162 * We regularly want to override the SQL for joining against the session record.
163 * so the calling application can define a function local_session_sql() which
164 * will return the SQL to join (up to and excluding the WHERE clause. The standard
165 * SQL used if this function is not defined is:
167 * SELECT session.*, usr.* FROM session JOIN usr ON ( user_no )
170 if ( function_exists('local_session_sql') ) {
171 $sql = local_session_sql();
174 $sql = "SELECT session.*, usr.* FROM session JOIN usr USING ( user_no )";
176 $sql .= " WHERE session.session_id = ? AND (md5(session.session_start::text) = ? OR session.session_key = ?) ORDER BY session.session_start DESC LIMIT 2";
178 $qry = new PgQuery($sql, $session_id, $session_key, $session_key);
179 if ( $qry->Exec('Session') && 1 == $qry->rows
) {
180 $this->AssignSessionDetails( $qry->Fetch() );
181 $qry = new PgQuery('UPDATE session SET session_end = current_timestamp WHERE session_id=?', $session_id);
182 $qry->Exec('Session');
185 // Kill the existing cookie, which appears to be bogus
186 setcookie('sid', '', 0,'/');
187 $this->cause
= 'ERR: Other than one session record matches. ' . $qry->rows
;
188 $this->Log( "WARN: Login $this->cause" );
194 * DEPRECATED Utility function to log stuff with printf expansion.
196 * This function could be expanded to log something identifying the session, but
197 * somewhat strangely this has not yet been done.
199 * @param string $whatever A log string
200 * @param mixed $whatever... Further parameters to be replaced into the log string a la printf
202 function Log( $whatever )
206 $argc = func_num_args();
207 $format = func_get_arg(0);
208 if ( $argc == 1 ||
($argc == 2 && func_get_arg(1) == "0" ) ) {
209 error_log( "$c->sysabbr: $format" );
213 for( $i=1; $i < $argc; $i++
) {
214 $args[] = func_get_arg($i);
216 error_log( "$c->sysabbr: " . vsprintf($format,$args) );
221 * DEPRECATED Utility function to log debug stuff with printf expansion, and the ability to
222 * enable it selectively.
224 * The enabling is done by setting a variable "$debuggroups[$group] = 1"
226 * @param string $group The name of an arbitrary debug group.
227 * @param string $whatever A log string
228 * @param mixed $whatever... Further parameters to be replaced into the log string a la printf
230 function Dbg( $whatever )
232 global $debuggroups, $c;
234 $argc = func_num_args();
235 $dgroup = func_get_arg(0);
237 if ( ! (isset($debuggroups[$dgroup]) && $debuggroups[$dgroup]) ) return;
239 $format = func_get_arg(1);
240 if ( $argc == 2 ||
($argc == 3 && func_get_arg(2) == "0" ) ) {
241 error_log( "$c->sysabbr: DBG: $dgroup: $format" );
245 for( $i=2; $i < $argc; $i++
) {
246 $args[] = func_get_arg($i);
248 error_log( "$c->sysabbr: DBG: $dgroup: " . vsprintf($format,$args) );
253 * Checks whether a user is allowed to do something.
255 * The check is performed to see if the user has that role.
257 * @param string $whatever The role we want to know if the user has.
258 * @return boolean Whether or not the user has the specified role.
260 function AllowedTo ( $whatever ) {
261 return ( $this->logged_in
&& isset($this->roles
[$whatever]) && $this->roles
[$whatever] );
266 * Internal function used to get the user's roles from the database.
268 function GetRoles () {
269 $this->roles
= array();
270 $qry = new PgQuery( 'SELECT role_name FROM role_member m join roles r ON r.role_no = m.role_no WHERE user_no = ? ', $this->user_no
);
271 if ( $qry->Exec('Session::GetRoles') && $qry->rows
> 0 ) {
272 while( $role = $qry->Fetch() ) {
273 $this->roles
[$role->role_name
] = true;
280 * Internal function used to assign the session details to a user's new session.
281 * @param object $u The user+session object we (probably) read from the database.
283 function AssignSessionDetails( $u ) {
284 // Assign each field in the selected record to the object
285 foreach( $u AS $k => $v ) {
289 $qry = new PgQuery( "SET DATESTYLE TO ?;", ($this->date_format_type
== 'E' ?
'European,ISO' : ($this->date_format_type
== 'U' ?
'US,ISO' : 'ISO')) );
293 $this->logged_in
= true;
298 * Attempt to perform a login action.
300 * This will validate the user's username and password. If they are OK then a new
301 * session id will be created and the user will be cookied with it for subsequent
302 * pages. A logged in session will be created, and the $_POST array will be cleared
303 * of the username, password and submit values. submit will also be cleared from
304 * $_GET and $GLOBALS, just in case.
306 * @param string $username The user's login name, or at least what they entered it as.
307 * @param string $password The user's password, or at least what they entered it as.
308 * @param string $authenticated If true, then authentication has already happened and the password is not checked, though the user must still exist.
309 * @return boolean Whether or not the user correctly guessed a temporary password within the necessary window of opportunity.
311 function Login( $username, $password, $authenticated = false ) {
314 dbg_error_log( "Login", " Login: Attempting login for $username" );
315 if ( isset($usr) ) unset($usr); /** In case someone is running with register_globals on */
318 * @todo In here we will need to put code to call the auth plugin, in order to
319 * ensure the 'usr' table has current valid data. At this stage we are just
320 * thinking it through... like ...
323 if ( !$authenticated && isset($c->authenticate_hook
) && isset($c->authenticate_hook
['call']) && function_exists($c->authenticate_hook
['call']) ) {
325 * The authenticate hook needs to:
326 * - Accept a username / password
327 * - Confirm the username / password are correct
328 * - Create (or update) a 'usr' record in our database
329 * - Return the 'usr' record as an object
330 * - Return === false when authentication fails
331 * It can expect that:
332 * - Configuration data will be in $c->authenticate_hook['config'], which might be an array, or whatever is needed.
334 $usr = call_user_func( $c->authenticate_hook
['call'], $username, $password );
335 if ( $usr === false ) unset($usr); else $authenticated = true;
338 $sql = "SELECT * FROM usr WHERE lower(username) = ? AND active";
339 $qry = new PgQuery( $sql, strtolower($username) );
340 if ( isset($usr) ||
($qry->Exec('Login',__LINE__
,__FILE__
) && $qry->rows
== 1 && $usr = $qry->Fetch() ) ) {
341 if ( $authenticated ||
session_validate_password( $password, $usr->password
) ||
check_temporary_passwords( $password, $usr->user_no
) ) {
342 // Now get the next session ID to create one from...
343 $qry = new PgQuery( "SELECT nextval('session_session_id_seq')" );
344 if ( $qry->Exec('Login') && $qry->rows
== 1 ) {
345 $seq = $qry->Fetch();
346 $session_id = $seq->nextval
;
347 $session_key = md5( rand(1010101,1999999999) . microtime() ); // just some random shite
348 dbg_error_log( "Login", " Login: Valid username/password for $username ($usr->user_no)" );
350 // Set the last_used timestamp to match the previous login.
351 $qry = new PgQuery('UPDATE usr SET last_used = (SELECT session_start FROM session WHERE session.user_no = ? ORDER BY session_id DESC LIMIT 1) WHERE user_no = ?;', $usr->user_no
, $usr->user_no
);
352 $qry->Exec('Session');
354 // And create a session
355 $sql = "INSERT INTO session (session_id, user_no, session_key) VALUES( ?, ?, ? )";
356 $qry = new PgQuery( $sql, $session_id, $usr->user_no
, $session_key );
357 if ( $qry->Exec('Login') ) {
358 // Assign our session ID variable
359 $sid = "$session_id;$session_key";
361 // Create a cookie for the sesssion
362 setcookie('sid',$sid, 0,'/');
363 // Recognise that we have started a session now too...
364 $this->Session($sid);
365 dbg_error_log( "Login", " Login: New session $session_id started for $username ($usr->user_no)" );
366 if ( isset($_POST['remember']) && intval($_POST['remember']) > 0 ) {
367 $cookie = md5( $usr->user_no
) . ";";
368 $cookie .= session_salted_md5($usr->user_no
. $usr->username
. $usr->password
);
369 $GLOBALS['lsid'] = $cookie;
370 setcookie( "lsid", $cookie, time() +
(86400 * 3600), "/" ); // will expire in ten or so years
372 $this->just_logged_in
= true;
374 // Unset all of the submitted values, so we don't accidentally submit an unexpected form.
375 unset($_POST['username']);
376 unset($_POST['password']);
377 unset($_POST['submit']);
378 unset($_GET['submit']);
379 unset($GLOBALS['submit']);
381 if ( function_exists('local_session_sql') ) {
382 $sql = local_session_sql();
385 $sql = "SELECT session.*, usr.* FROM session JOIN usr USING ( user_no )";
387 $sql .= " WHERE session.session_id = ? AND (md5(session.session_start::text) = ? OR session.session_key = ?) ORDER BY session.session_start DESC LIMIT 2";
389 $qry = new PgQuery($sql, $session_id, $session_key, $session_key);
390 if ( $qry->Exec('Session') && 1 == $qry->rows
) {
391 $this->AssignSessionDetails( $qry->Fetch() );
398 $this->cause
= 'ERR: Could not create new session.';
401 $this->cause
= 'ERR: Could not increment session sequence.';
405 $c->messages
[] = i18n('Invalid username or password.');
406 if ( isset($c->dbg
['Login']) ||
isset($c->dbg
['ALL']) )
407 $this->cause
= 'WARN: Invalid password.';
409 $this->cause
= 'WARN: Invalid username or password.';
413 $c->messages
[] = i18n('Invalid username or password.');
414 if ( isset($c->dbg
['Login']) ||
isset($c->dbg
['ALL']) )
415 $this->cause
= 'WARN: Invalid username.';
417 $this->cause
= 'WARN: Invalid username or password.';
420 $this->Log( "Login failure: $this->cause" );
421 $this->login_failed
= true;
429 * Attempts to logs in using a long-term session ID
431 * This is all horribly insecure, but its hard not to be.
433 * @param string $lsid The user's value of the lsid cookie.
434 * @return boolean Whether or not the user's lsid cookie got them in the door.
436 function LSIDLogin( $lsid ) {
438 dbg_error_log( "Login", " LSIDLogin: Attempting login for $lsid" );
440 list($md5_user_no,$validation_string) = split( ';', $lsid );
441 $qry = new PgQuery( "SELECT * FROM usr WHERE md5(user_no::text)=?;", $md5_user_no );
442 if ( $qry->Exec('Login') && $qry->rows
== 1 ) {
443 $usr = $qry->Fetch();
444 list( $x, $salt, $y) = split('\*', $validation_string);
445 $my_validation = session_salted_md5($usr->user_no
. $usr->username
. $usr->password
, $salt);
446 if ( $validation_string == $my_validation ) {
447 // Now get the next session ID to create one from...
448 $qry = new PgQuery( "SELECT nextval('session_session_id_seq')" );
449 if ( $qry->Exec('Login') && $qry->rows
== 1 ) {
450 $seq = $qry->Fetch();
451 $session_id = $seq->nextval
;
452 $session_key = md5( rand(1010101,1999999999) . microtime() ); // just some random shite
453 dbg_error_log( "Login", " LSIDLogin: Valid username/password for $username ($usr->user_no)" );
455 // And create a session
456 $sql = "INSERT INTO session (session_id, user_no, session_key) VALUES( ?, ?, ? )";
457 $qry = new PgQuery( $sql, $session_id, $usr->user_no
, $session_key );
458 if ( $qry->Exec('Login') ) {
459 // Assign our session ID variable
460 $sid = "$session_id;$session_key";
462 // Create a cookie for the sesssion
463 setcookie('sid',$sid, 0,'/');
464 // Recognise that we have started a session now too...
465 $this->Session($sid);
466 dbg_error_log( "Login", " LSIDLogin: New session $session_id started for $this->username ($usr->user_no)" );
468 $this->just_logged_in
= true;
470 // Unset all of the submitted values, so we don't accidentally submit an unexpected form.
471 unset($_POST['username']);
472 unset($_POST['password']);
473 unset($_POST['submit']);
474 unset($_GET['submit']);
475 unset($GLOBALS['submit']);
477 if ( function_exists('local_session_sql') ) {
478 $sql = local_session_sql();
481 $sql = "SELECT session.*, usr.* FROM session JOIN usr USING ( user_no )";
483 $sql .= " WHERE session.session_id = ? AND (md5(session.session_start::text) = ? OR session.session_key = ?) ORDER BY session.session_start DESC LIMIT 2";
485 $qry = new PgQuery($sql, $session_id, $session_key, $session_key);
486 if ( $qry->Exec('Session') && 1 == $qry->rows
) {
487 $this->AssignSessionDetails( $qry->Fetch() );
494 $this->cause
= 'ERR: Could not create new session.';
497 $this->cause
= 'ERR: Could not increment session sequence.';
501 dbg_error_log( "Login", " LSIDLogin: $validation_string != $my_validation ($salt - $usr->user_no, $usr->username, $usr->password)");
502 $client_messages[] = i18n('Invalid username or password.');
503 if ( isset($c->dbg
['Login']) ||
isset($c->dbg
['ALL']) )
504 $this->cause
= 'WARN: Invalid password.';
506 $this->cause
= 'WARN: Invalid username or password.';
510 $client_messages[] = i18n('Invalid username or password.');
511 if ( isset($c->dbg
['Login']) ||
isset($c->dbg
['ALL']) )
512 $this->cause
= 'WARN: Invalid username.';
514 $this->cause
= 'WARN: Invalid username or password.';
517 dbg_error_log( "Login", " LSIDLogin: $this->cause" );
523 * Renders some HTML for a basic login panel
525 * @return string The HTML to display a login panel.
527 function RenderLoginPanel() {
528 $action_target = htmlspecialchars(preg_replace('/\?logout.*$/','',$_SERVER['REQUEST_URI']));
529 dbg_error_log( "Login", " RenderLoginPanel: action_target='%s'", $action_target );
530 $userprompt = translate("User Name");
531 $pwprompt = translate("Password");
532 $rememberprompt = str_replace( ' ', ' ', translate("forget me not"));
533 $gobutton = htmlspecialchars(translate("GO!"));
534 $gotitle = htmlspecialchars(translate("Enter your username and password then click here to log in."));
535 $temppwprompt = translate("If you have forgotten your password then");
536 $temppwbutton = htmlspecialchars(translate("Help! I've forgotten my password!"));
537 $temppwtitle = htmlspecialchars(translate("Enter a username, if you know it, and click here, to be e-mailed a temporary password."));
540 <form action="$action_target" method="post">
543 <th class="prompt">$userprompt:</th>
545 <input class="text" type="text" name="username" size="12" /></td>
548 <th class="prompt">$pwprompt:</th>
550 <input class="password" type="password" name="password" size="12" />
551 <label>$rememberprompt: <input class="checkbox" type="checkbox" name="remember" value="1" /></label>
555 <th class="prompt"> </th>
557 <input type="submit" value="$gobutton" title="$gotitle" name="submit" class="submit" />
562 $temppwprompt: <input type="submit" value="$temppwbutton" title="$temppwtitle" name="lostpass" class="submit" />
573 * Checks that this user is logged in, and presents a login screen if they aren't.
575 * The function can optionally confirm whether they are a member of one of a list
576 * of groups, and deny access if they are not a member of any of them.
578 * @param string $groups The list of groups that the user must be a member of one of to be allowed to proceed.
579 * @return boolean Whether or not the user is logged in and is a member of one of the required groups.
581 function LoginRequired( $groups = "" ) {
584 if ( $this->logged_in
&& $groups == "" ) return;
585 if ( ! $this->logged_in
) {
586 $c->messages
[] = i18n("You must log in to use this system.");
587 if ( function_exists("local_index_not_logged_in") ) {
588 local_index_not_logged_in();
591 $login_html = translate( "<h1>Log On Please</h1><p>For access to the %s you should log on withthe username and password that have been issued to you.</p><p>If you would like to request access, please e-mail %s.</p>");
592 $page_content = sprintf( $login_html, $c->system_name
, $c->admin_email
);
593 $page_content .= $this->RenderLoginPanel();
594 if ( isset($page_elements) && gettype($page_elements) == 'array' ) {
595 $page_elements[] = $page_content;
596 @include
("page-renderer.php");
599 @include
("page-header.php");
601 @include
("page-footer.php");
605 $valid_groups = split(",", $groups);
606 foreach( $valid_groups AS $k => $v ) {
607 if ( $this->AllowedTo($v) ) return;
609 $c->messages
[] = i18n("You are not authorised to use this function.");
610 if ( isset($page_elements) && gettype($page_elements) == 'array' ) {
611 @include
("page-renderer.php");
614 @include
("page-header.php");
615 @include
("page-footer.php");
624 * E-mails a temporary password in response to a request from a user.
626 * This could be called from somewhere within the application that allows
627 * someone to set up a user and invite them.
629 * This function includes EMail.php to actually send the password.
631 function EmailTemporaryPassword( $username, $email_address, $body_template="" ) {
634 $password_sent = false;
636 if ( isset($username) && $username != "" ) {
637 $where = "WHERE active AND lower(usr.username) = ". qpg(strtolower($username));
639 else if ( isset($email_address) && $email_address != "" ) {
640 $where = "WHERE active AND lower(usr.email) = ". qpg(strtolower($email_address));
643 if ( $where != "" ) {
645 for ( $i=0; $i < 8; $i++
) {
646 $tmp_passwd .= substr( "ABCDEFGHIJKLMNOPQRSTUVWXYZ+#.-=*%@0123456789abcdefghijklmnopqrstuvwxyz", rand(0,69), 1);
648 $sql = "SELECT * FROM usr $where";
649 $qry = new PgQuery( $sql );
650 $qry->Exec("Session::EmailTemporaryPassword");
651 if ( $qry->rows
> 0 ) {
654 $mail = new EMail( "Access to $c->system_name" );
655 $mail->SetFrom($c->admin_email
);
657 if ( isset($c->debug_email
) ) {
658 $debug_to = "This e-mail would normally be sent to:\n ";
659 $mail->AddTo( "Tester <$c->debug_email>" );
661 while ( $row = $qry->Fetch() ) {
662 $sql .= "INSERT INTO tmp_password ( user_no, password) VALUES( $row->user_no, '$tmp_passwd');";
663 if ( isset($c->debug_email
) ) {
664 $debug_to .= "$row->fullname <$row->email> ";
667 $mail->AddTo( "$row->fullname <$row->email>" );
669 $usernames .= " $row->username\n";
671 if ( $mail->To
!= "" ) {
672 if ( isset($c->debug_email
) ) {
673 $debug_to .= "\n============================================================\n";
676 $qry = new PgQuery( $sql );
677 $qry->Exec("Session::SendTemporaryPassword");
678 if ( !isset($body_template) ||
$body_template == "" ) {
679 $body_template = <<<EOTEXT
681 @@debugging@@A temporary password has been requested for @@system_name@@.
683 Temporary Password: @@password@@
685 This has been applied to the following usernames:
688 and will be valid for 24 hours.
690 If you have any problems, please contact the system administrator.
694 $body = str_replace( '@@system_name@@', $c->system_name
, $body_template);
695 $body = str_replace( '@@password@@', $tmp_passwd, $body);
696 $body = str_replace( '@@usernames@@', $usernames, $body);
697 $body = str_replace( '@@debugging@@', $debug_to, $body);
698 $mail->SetBody($body);
700 $password_sent = true;
704 return $password_sent;
709 * Sends a temporary password in response to a request from a user.
711 * This is probably only going to be called from somewhere internal. An external
712 * caller will probably just want the e-mail, without the HTML that this displays.
715 function SendTemporaryPassword( ) {
716 global $c, $page_elements;
718 $password_sent = $this->EmailTemporaryPassword( (isset($_POST['username'])?
$_POST['username']:null), (isset($_POST['email_address'])?
$_POST['email_address']:null) );
720 if ( ! $password_sent && ((isset($_POST['username']) && $_POST['username'] != "" )
721 ||
(isset($_POST['email_address']) && $_POST['email_address'] != "" )) ) {
722 // Username or EMail were non-null, but we didn't find that user.
724 $page_content = <<<EOTEXT
726 <h1>Unable to Reset Password</h1>
727 <p>We were unable to reset your password at this time. Please contact
728 <a href="mailto:$c->admin_email">$c->admin_email</a>
729 to arrange for an administrator to reset your password.</p>
735 if ( $password_sent ) {
736 $page_content = <<<EOTEXT
738 <h1>Temporary Password Sent</h1>
739 <p>A temporary password has been e-mailed to you. This password
740 will be valid for 24 hours and you will be required to change
741 your password after logging in.</p>
742 <p><a href="/">Click here to return to the login page.</a></p>
747 $page_content = <<<EOTEXT
749 <h1>Temporary Password</h1>
750 <form action="$action_target" method="post">
753 <th class="prompt" style="white-space: nowrap;">Enter your User Name:</th>
754 <td class="entry"><input class="text" type="text" name="username" size="12" /></td>
757 <th class="prompt" style="white-space: nowrap;">Or your EMail Address:</th>
758 <td class="entry"><input class="text" type="text" name="email_address" size="50" /></td>
761 <th class="prompt" style="white-space: nowrap;">and click on -></th>
763 <input class="submit" type="submit" value="Send me a temporary password" alt="Enter a username, or e-mail address, and click here." name="lostpass" />
767 <p>Note: If you have multiple accounts with the same e-mail address, they will <em>all</em>
768 be assigned a new temporary password, but only the one(s) that you use that temporary password
769 on will have the existing password invalidated.</p>
770 <p>Any temporary password will only be valid for 24 hours.</p>
775 if ( isset($page_elements) && gettype($page_elements) == 'array' ) {
776 $page_elements[] = $page_content;
777 @include
("page-renderer.php");
780 @include
("page-header.php");
782 @include
("page-footer.php");
786 function _CheckLogout() {
787 if ( isset($_GET['logout']) ) {
788 dbg_error_log( "Login", ":_CheckLogout: Logging out");
789 setcookie( 'sid', '', 0,'/');
790 unset($_COOKIE['sid']);
791 unset($GLOBALS['sid']);
792 unset($_COOKIE['lsid']); // Allow a cookied person to be un-logged-in for one page view.
793 unset($GLOBALS['lsid']);
795 if ( isset($_GET['forget']) ) setcookie( 'lsid', '', 0,'/');
799 function _CheckLogin() {
800 if ( isset($_POST['lostpass']) ) {
801 dbg_error_log( "Login", ":_CheckLogin: User '$_POST[username]' has lost the password." );
802 $this->SendTemporaryPassword();
804 else if ( isset($_POST['username']) && isset($_POST['password']) ) {
805 // Try and log in if we have a username and password
806 $this->Login( $_POST['username'], $_POST['password'] );
807 @dbg_error_log
( "Login", ":_CheckLogin: User %s(%s) - %s (%d) login status is %d", $_POST['username'], $this->fullname
, $this->user_no
, $this->logged_in
);
809 else if ( !isset($_COOKIE['sid']) && isset($_COOKIE['lsid']) && $_COOKIE['lsid'] != "" ) {
810 // Validate long-term session details
811 $this->LSIDLogin( $_COOKIE['lsid'] );
812 dbg_error_log( "Login", ":_CheckLogin: User $this->username - $this->fullname ($this->user_no) login status is $this->logged_in" );
814 else if ( !isset($_COOKIE['sid']) && isset($c->authenticate_hook
['server_auth_type']) && $c->authenticate_hook
['server_auth_type'] == $_SERVER['AUTH_TYPE']) {
816 * The authentication has happened in the server, and we should accept it.
817 * Perhaps this 'split' is not a good idea though. People may want to use the
818 * full ID as the username. A further option may be desirable.
820 list($username) = split('@', $_SERVER['REMOTE_USER']);
821 $this->Login($username, "", true); // Password will not be checked.
827 * Function to reformat an ISO date to something nicer and possibly more localised
828 * @param string $indate The ISO date to be formatted.
829 * @param string $type If 'timestamp' then the time will also be shown.
830 * @return string The nicely formatted date.
832 function FormattedDate( $indate, $type='date' ) {
834 if ( preg_match( '#^\s*$#', $indate ) ) {
835 // Looks like it's empty - just return empty
838 if ( preg_match( '#^\d{1,2}[/-]\d{1,2}[/-]\d{2,4}#', $indate ) ) {
839 // Looks like it's nice already - don't screw with it!
842 $yr = substr($indate,0,4);
843 $mo = substr($indate,5,2);
844 $dy = substr($indate,8,2);
845 switch ( $this->date_format_type
) {
847 $out = sprintf( "%d/%d/%d", $mo, $dy, $yr );
850 $out = sprintf( "%d/%d/%d", $dy, $mo, $yr );
853 $out = sprintf( "%d-%02d-%02d", $yr, $mo, $dy );
856 if ( $type == 'timestamp' ) {
857 $out .= substr($indate,10,6);
864 * Build a hash which we can use for confirmation that we didn't get e-mailed
865 * a bogus link by someone, and that we actually got here by traversing the
868 * @param string $method Either 'GET' or 'POST' depending on the way we will use this.
869 * @param string $varname The name of the variable which we will confirm
870 * @return string A string we can use as either a GET or POST value (i.e. a hidden field, or a varname=hash pair.
872 function BuildConfirmationHash( $method, $varname ) {
874 * We include session_start in this because it is never passed to the client
875 * and since it includes microseconds would be very hard to predict.
877 $confirmation_hash = session_salted_md5( $this->session_start
.$varname.$this->session_key
, "" );
878 if ( $method == 'GET' ) {
879 $confirm = $varname .'='. urlencode($confirmation_hash);
882 $confirm = sprintf( '<input type="hidden" name="%s" value="%s">', $varname, htmlspecialchars($confirmation_hash) );
889 * Check a hash which we created through BuildConfirmationHash
891 * @param string $method Either 'GET' or 'POST' depending on the way we will use this.
892 * @param string $varname The name of the variable which we will confirm
893 * @return string A string we can use as either a GET or POST value (i.e. a hidden field, or a varname=hash pair.
895 function CheckConfirmationHash( $method, $varname ) {
896 if ( $method == 'GET' && isset($_GET[$varname])) {
897 $hashwegot = $_GET[$varname];
899 else if ( isset($_POST[$varname]) ) {
900 $hashwegot = $_POST[$varname];
906 if ( ereg('^\*(.+)\*.+$', $hashwegot, $regs ) ) {
907 // A nicely salted md5sum like "*<salt>*<salted_md5>"
909 $test_against = session_salted_md5( $this->session_start
.$varname.$this->session_key
, $salt ) ;
911 if ( $hashwegot == $test_against ) return true;
920 * @global resource $session
922 * The session object is global.
925 if ( !isset($session) ) {
926 Session
::_CheckLogout();
927 $session = new Session();
928 $session->_CheckLogin();