[Session] _CheckLogin needs to access $c for external authentication.
[awl.git] / inc / Session.php
bloba5841818c7b92c276aca502bf7b03b8481de95a4
1 <?php
2 /**
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.
19 * @package awl
20 * @subpackage 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');
30 /**
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__);
47 return true;
50 return false;
53 /**
54 * A class for creating and holding session information.
56 * @package awl
58 class Session
60 /**#@+
61 * @access private
63 var $roles;
64 var $cause = '';
65 /**#@-*/
67 /**#@+
68 * @access public
71 /**
72 * The user_no of the logged in user.
73 * @var int
75 var $user_no;
77 /**
78 * A unique id for this user's logged-in session.
79 * @var int
81 var $session_id = 0;
83 /**
84 * The user's username used to log in.
85 * @var int
87 var $username = 'guest';
89 /**
90 * The user's full name from their usr record.
91 * @var int
93 var $fullname = 'Guest';
95 /**
96 * The user's email address from their usr record.
97 * @var int
99 var $email = '';
102 * Whether this user has actually logged in.
103 * @var int
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.
111 * @var boolean
113 var $just_logged_in = false;
116 * The date and time that the user logged on during their last session.
117 * @var string
119 var $last_session_start;
122 * The date and time that the user requested their last page during their last
123 * session.
124 * @var string
126 var $last_session_end;
127 /**#@-*/
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
141 * that read.
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;
154 if ( $sid == "" ) {
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:
166 * <code>
167 * SELECT session.*, usr.* FROM session JOIN usr ON ( user_no )
168 * </code>
170 if ( function_exists('local_session_sql') ) {
171 $sql = local_session_sql();
173 else {
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');
184 else {
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 )
204 global $c;
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" );
211 else {
212 $args = array();
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" );
243 else {
244 $args = array();
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 ) {
286 $this->{$k} = $v;
289 $qry = new PgQuery( "SET DATESTYLE TO ?;", ($this->date_format_type == 'E' ? 'European,ISO' : ($this->date_format_type == 'U' ? 'US,ISO' : 'ISO')) );
290 $qry->Exec();
292 $this->GetRoles();
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 ) {
312 global $c;
313 $rc = 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();
384 else {
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() );
394 $rc = true;
395 return $rc;
397 // else ...
398 $this->cause = 'ERR: Could not create new session.';
400 else {
401 $this->cause = 'ERR: Could not increment session sequence.';
404 else {
405 $c->messages[] = i18n('Invalid username or password.');
406 if ( isset($c->dbg['Login']) || isset($c->dbg['ALL']) )
407 $this->cause = 'WARN: Invalid password.';
408 else
409 $this->cause = 'WARN: Invalid username or password.';
412 else {
413 $c->messages[] = i18n('Invalid username or password.');
414 if ( isset($c->dbg['Login']) || isset($c->dbg['ALL']) )
415 $this->cause = 'WARN: Invalid username.';
416 else
417 $this->cause = 'WARN: Invalid username or password.';
420 $this->Log( "Login failure: $this->cause" );
421 $this->login_failed = true;
422 $rc = false;
423 return $rc;
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 ) {
437 global $c;
438 dbg_error_log( "Login", " LSIDLogin: Attempting login for $lsid" );
440 list($md5_user_no,$validation_string) = explode( ';', $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) = explode('*', $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();
480 else {
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() );
490 $rc = true;
491 return $rc;
493 // else ...
494 $this->cause = 'ERR: Could not create new session.';
496 else {
497 $this->cause = 'ERR: Could not increment session sequence.';
500 else {
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.';
505 else
506 $this->cause = 'WARN: Invalid username or password.';
509 else {
510 $client_messages[] = i18n('Invalid username or password.');
511 if ( isset($c->dbg['Login']) || isset($c->dbg['ALL']) )
512 $this->cause = 'WARN: Invalid username.';
513 else
514 $this->cause = 'WARN: Invalid username or password.';
517 dbg_error_log( "Login", " LSIDLogin: $this->cause" );
518 return false;
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( ' ', '&nbsp;', 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."));
538 $html = <<<EOTEXT
539 <div id="logon">
540 <form action="$action_target" method="post">
541 <table>
542 <tr>
543 <th class="prompt">$userprompt:</th>
544 <td class="entry">
545 <input class="text" type="text" name="username" size="12" /></td>
546 </tr>
547 <tr>
548 <th class="prompt">$pwprompt:</th>
549 <td class="entry">
550 <input class="password" type="password" name="password" size="12" />
551 &nbsp;<label>$rememberprompt: <input class="checkbox" type="checkbox" name="remember" value="1" /></label>
552 </td>
553 </tr>
554 <tr>
555 <th class="prompt">&nbsp;</th>
556 <td class="entry">
557 <input type="submit" value="$gobutton" title="$gotitle" name="submit" class="submit" />
558 </td>
559 </tr>
560 </table>
562 $temppwprompt: <input type="submit" value="$temppwbutton" title="$temppwtitle" name="lostpass" class="submit" />
563 </p>
564 </form>
565 </div>
567 EOTEXT;
568 return $html;
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 = "" ) {
582 global $c, $session;
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();
590 else {
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");
597 exit(0);
599 @include("page-header.php");
600 echo $page_content;
601 @include("page-footer.php");
604 else {
605 $valid_groups = explode(",", $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");
612 exit(0);
614 @include("page-header.php");
615 @include("page-footer.php");
618 exit;
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="" ) {
632 global $c;
634 $password_sent = false;
635 $where = "";
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 != "" ) {
644 $tmp_passwd = "";
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 ) {
652 $sql = "BEGIN;";
654 $mail = new EMail( "Access to $c->system_name" );
655 $mail->SetFrom($c->admin_email );
656 $usernames = "";
657 $debug_to = "";
658 if ( isset($c->debug_email) ) {
659 $debug_to = "This e-mail would normally be sent to:\n ";
660 $mail->AddTo( "Tester <$c->debug_email>" );
662 while ( $row = $qry->Fetch() ) {
663 $sql .= "INSERT INTO tmp_password ( user_no, password) VALUES( $row->user_no, '$tmp_passwd');";
664 if ( isset($c->debug_email) ) {
665 $debug_to .= "$row->fullname <$row->email> ";
667 else {
668 $mail->AddTo( "$row->fullname <$row->email>" );
670 $usernames .= " $row->username\n";
672 if ( $mail->To != "" ) {
673 if ( isset($c->debug_email) ) {
674 $debug_to .= "\n============================================================\n";
676 $sql .= "COMMIT;";
677 $qry = new PgQuery( $sql );
678 $qry->Exec("Session::SendTemporaryPassword");
679 if ( !isset($body_template) || $body_template == "" ) {
680 $body_template = <<<EOTEXT
681 $debug_to
682 @@debugging@@A temporary password has been requested for @@system_name@@.
684 Temporary Password: @@password@@
686 This has been applied to the following usernames:
688 @@usernames@@
689 and will be valid for 24 hours.
691 If you have any problems, please contact the system administrator.
693 EOTEXT;
695 $body = str_replace( '@@system_name@@', $c->system_name, $body_template);
696 $body = str_replace( '@@password@@', $tmp_passwd, $body);
697 $body = str_replace( '@@usernames@@', $usernames, $body);
698 $body = str_replace( '@@debugging@@', $debug_to, $body);
699 $mail->SetBody($body);
700 $mail->Send();
701 $password_sent = true;
705 return $password_sent;
710 * Sends a temporary password in response to a request from a user.
712 * This is probably only going to be called from somewhere internal. An external
713 * caller will probably just want the e-mail, without the HTML that this displays.
716 function SendTemporaryPassword( ) {
717 global $c, $page_elements;
719 $password_sent = $this->EmailTemporaryPassword( (isset($_POST['username'])?$_POST['username']:null), (isset($_POST['email_address'])?$_POST['email_address']:null) );
721 if ( ! $password_sent && ((isset($_POST['username']) && $_POST['username'] != "" )
722 || (isset($_POST['email_address']) && $_POST['email_address'] != "" )) ) {
723 // Username or EMail were non-null, but we didn't find that user.
725 $page_content = <<<EOTEXT
726 <div id="logon">
727 <h1>Unable to Reset Password</h1>
728 <p>We were unable to reset your password at this time. Please contact
729 <a href="mailto:$c->admin_email">$c->admin_email</a>
730 to arrange for an administrator to reset your password.</p>
731 <p>Thank you.</p>
732 </div>
733 EOTEXT;
736 if ( $password_sent ) {
737 $page_content = <<<EOTEXT
738 <div id="logon">
739 <h1>Temporary Password Sent</h1>
740 <p>A temporary password has been e-mailed to you. This password
741 will be valid for 24 hours and you will be required to change
742 your password after logging in.</p>
743 <p><a href="/">Click here to return to the login page.</a></p>
744 </div>
745 EOTEXT;
747 else {
748 $page_content = <<<EOTEXT
749 <div id="logon">
750 <h1>Temporary Password</h1>
751 <form action="$action_target" method="post">
752 <table>
753 <tr>
754 <th class="prompt" style="white-space: nowrap;">Enter your User Name:</th>
755 <td class="entry"><input class="text" type="text" name="username" size="12" /></td>
756 </tr>
757 <tr>
758 <th class="prompt" style="white-space: nowrap;">Or your EMail Address:</th>
759 <td class="entry"><input class="text" type="text" name="email_address" size="50" /></td>
760 </tr>
761 <tr>
762 <th class="prompt" style="white-space: nowrap;">and click on -></th>
763 <td class="entry">
764 <input class="submit" type="submit" value="Send me a temporary password" alt="Enter a username, or e-mail address, and click here." name="lostpass" />
765 </td>
766 </tr>
767 </table>
768 <p>Note: If you have multiple accounts with the same e-mail address, they will <em>all</em>
769 be assigned a new temporary password, but only the one(s) that you use that temporary password
770 on will have the existing password invalidated.</p>
771 <p>Any temporary password will only be valid for 24 hours.</p>
772 </form>
773 </div>
774 EOTEXT;
776 if ( isset($page_elements) && gettype($page_elements) == 'array' ) {
777 $page_elements[] = $page_content;
778 @include("page-renderer.php");
779 exit(0);
781 @include("page-header.php");
782 echo $page_content;
783 @include("page-footer.php");
784 exit(0);
787 function _CheckLogout() {
788 if ( isset($_GET['logout']) ) {
789 dbg_error_log( "Login", ":_CheckLogout: Logging out");
790 setcookie( 'sid', '', 0,'/');
791 unset($_COOKIE['sid']);
792 unset($GLOBALS['sid']);
793 unset($_COOKIE['lsid']); // Allow a cookied person to be un-logged-in for one page view.
794 unset($GLOBALS['lsid']);
796 if ( isset($_GET['forget']) ) setcookie( 'lsid', '', 0,'/');
800 function _CheckLogin() {
801 global $c;
802 if ( isset($_POST['lostpass']) ) {
803 dbg_error_log( "Login", ":_CheckLogin: User '$_POST[username]' has lost the password." );
804 $this->SendTemporaryPassword();
806 else if ( isset($_POST['username']) && isset($_POST['password']) ) {
807 // Try and log in if we have a username and password
808 $this->Login( $_POST['username'], $_POST['password'] );
809 @dbg_error_log( "Login", ":_CheckLogin: User %s(%s) - %s (%d) login status is %d", $_POST['username'], $this->fullname, $this->user_no, $this->logged_in );
811 else if ( !isset($_COOKIE['sid']) && isset($_COOKIE['lsid']) && $_COOKIE['lsid'] != "" ) {
812 // Validate long-term session details
813 $this->LSIDLogin( $_COOKIE['lsid'] );
814 dbg_error_log( "Login", ":_CheckLogin: User $this->username - $this->fullname ($this->user_no) login status is $this->logged_in" );
816 else if ( !isset($_COOKIE['sid']) && isset($c->authenticate_hook['server_auth_type']) && $c->authenticate_hook['server_auth_type'] == $_SERVER['AUTH_TYPE']) {
818 * The authentication has happened in the server, and we should accept it.
819 * Perhaps this 'split' is not a good idea though. People may want to use the
820 * full ID as the username. A further option may be desirable.
822 list($username) = explode('@', $_SERVER['REMOTE_USER']);
823 $this->Login($username, "", true); // Password will not be checked.
829 * Function to reformat an ISO date to something nicer and possibly more localised
830 * @param string $indate The ISO date to be formatted.
831 * @param string $type If 'timestamp' then the time will also be shown.
832 * @return string The nicely formatted date.
834 function FormattedDate( $indate, $type='date' ) {
835 $out = "";
836 if ( preg_match( '#^\s*$#', $indate ) ) {
837 // Looks like it's empty - just return empty
838 return $indate;
840 if ( preg_match( '#^\d{1,2}[/-]\d{1,2}[/-]\d{2,4}#', $indate ) ) {
841 // Looks like it's nice already - don't screw with it!
842 return $indate;
844 $yr = substr($indate,0,4);
845 $mo = substr($indate,5,2);
846 $dy = substr($indate,8,2);
847 switch ( $this->date_format_type ) {
848 case 'U':
849 $out = sprintf( "%d/%d/%d", $mo, $dy, $yr );
850 break;
851 case 'E':
852 $out = sprintf( "%d/%d/%d", $dy, $mo, $yr );
853 break;
854 default:
855 $out = sprintf( "%d-%02d-%02d", $yr, $mo, $dy );
856 break;
858 if ( $type == 'timestamp' ) {
859 $out .= substr($indate,10,6);
861 return $out;
866 * Build a hash which we can use for confirmation that we didn't get e-mailed
867 * a bogus link by someone, and that we actually got here by traversing the
868 * website.
870 * @param string $method Either 'GET' or 'POST' depending on the way we will use this.
871 * @param string $varname The name of the variable which we will confirm
872 * @return string A string we can use as either a GET or POST value (i.e. a hidden field, or a varname=hash pair.
874 function BuildConfirmationHash( $method, $varname ) {
876 * We include session_start in this because it is never passed to the client
877 * and since it includes microseconds would be very hard to predict.
879 $confirmation_hash = session_salted_md5( $this->session_start.$varname.$this->session_key, "" );
880 if ( $method == 'GET' ) {
881 $confirm = $varname .'='. urlencode($confirmation_hash);
883 else {
884 $confirm = sprintf( '<input type="hidden" name="%s" value="%s">', $varname, htmlspecialchars($confirmation_hash) );
886 return $confirm;
891 * Check a hash which we created through BuildConfirmationHash
893 * @param string $method Either 'GET' or 'POST' depending on the way we will use this.
894 * @param string $varname The name of the variable which we will confirm
895 * @return string A string we can use as either a GET or POST value (i.e. a hidden field, or a varname=hash pair.
897 function CheckConfirmationHash( $method, $varname ) {
898 if ( $method == 'GET' && isset($_GET[$varname])) {
899 $hashwegot = $_GET[$varname];
901 else if ( isset($_POST[$varname]) ) {
902 $hashwegot = $_POST[$varname];
904 else {
905 return false;
908 if ( ereg('^\*(.+)\*.+$', $hashwegot, $regs ) ) {
909 // A nicely salted md5sum like "*<salt>*<salted_md5>"
910 $salt = $regs[1];
911 $test_against = session_salted_md5( $this->session_start.$varname.$this->session_key, $salt ) ;
913 if ( $hashwegot == $test_against ) return true;
915 return false;
922 * @global resource $session
923 * @name $session
924 * The session object is global.
927 if ( !isset($session) ) {
928 Session::_CheckLogout();
929 $session = new Session();
930 $session->_CheckLogin();