diff options
author | Karl 'vollmerk' Vollmer <vollmer@ampache.org> | 2005-06-09 16:34:40 +0000 |
---|---|---|
committer | Karl 'vollmerk' Vollmer <vollmer@ampache.org> | 2005-06-09 16:34:40 +0000 |
commit | bcad40a05ab2dc2a341a3227e30b96668bce4500 (patch) | |
tree | 6fca27588d53a1b24705bd2834e9e643bb729bd1 /libglue | |
download | ampache-bcad40a05ab2dc2a341a3227e30b96668bce4500.tar.gz ampache-bcad40a05ab2dc2a341a3227e30b96668bce4500.tar.bz2 ampache-bcad40a05ab2dc2a341a3227e30b96668bce4500.zip |
New Import
Diffstat (limited to 'libglue')
-rw-r--r-- | libglue/README | 393 | ||||
-rw-r--r-- | libglue/auth.php | 399 | ||||
-rw-r--r-- | libglue/config.php | 173 | ||||
-rw-r--r-- | libglue/dbh.php | 53 | ||||
-rw-r--r-- | libglue/libdb.php | 95 | ||||
-rw-r--r-- | libglue/session.php | 417 | ||||
-rw-r--r-- | libglue/session2.php | 346 |
7 files changed, 1876 insertions, 0 deletions
diff --git a/libglue/README b/libglue/README new file mode 100644 index 00000000..b847586b --- /dev/null +++ b/libglue/README @@ -0,0 +1,393 @@ +libglue - 8/17/03 + +libglue provides a set of libraries for use with applications +developed here at Oregon State University. + +This set of libraries includes: +- mysql session handling, +- MySQL/LDAP/'shared' authentication methods +- a database handler + +Contents: +1 Authentication Methods + 1.1 LDAP Authentication + 1.2 MySQL Authentication + 1.3 Shared Authentication +2 Database schemas + 2.1 For Session management + 2.2 For LDAP Authentication + 2.3 For MySQL Authentication + 2.4 For Shared Authentication +3 The Config file + 3.1 Formatting + 3.2 Subsections + 3.3 Arrays + 3.3 Retrieving options +4 Session management +5 Libglue in action + +6 Help, FAQs + + +1 Authentication Methods +-------------------------------------------------------------------------------- + Libglue currently supports 3 authentication methods: LDAP, MySQL, and + 'Shared.' It can support any combination of these concurrently, by falling + through in the order you specify (see Section 3.3). + + 1.1 LDAP Authentication + ------------------------------------------------------------------------------ + To use LDAP authentication, you must have LDAP support for PHP. + See http://php.net/manual/en/ref.ldap.php for how to configure php with LDAP. + + You must provide credentials for your LDAP server in the config file. + Anonymous LDAP authentication is possible, but not with libglue today. + + libglue has two functions for ldap authentication, both in 'LIBGLUE/auth.php': + + mixed get_ldap_user($username [,$fields]) + + object auth_ldap($username,$password) + + 'auth_ldap' is intended for internal use, while 'get_ldap_user' is a utility + for app developers to use. Both have similar layouts: + + - connect to ldap service + - bind to ldap with credential from config file + - search for '$username' in the space specified in the config file + - attempt to bind with supplied user credentials (auth_ldap only) + + 'get_ldap_user' returns an array of fields on success (if '$fields' is + not specified, it will return all the information for the specified user), + and an error string on failure. + + 'auth_ldap' returns an 'auth_response' object, with success indicated by + the value of auth_response->success. (This class is defined in 'auth.php'). + + 'auth_ldap' is typically only going to be called from a login script. + 'get_ldap_user' could be used when granting access to a new user. + + Config Options: + ldap_host + ldap_auth_dn + ldap_user_dn + ldap_filter + ldap_pass + ldap_fields + ldap_version + + + 1.2 MySQL Authentication + ------------------------------------------------------------------------------ + MySQL Authentication (like all of libglue) requires MySQL support in PHP. + It defaults to using the MySQL PASSWORD() function to check passwords, but + can also use PHP crypt() for compatability with other applications + (pam_mysql for example). + + MySQL Authentication assumes the local database specified in the config file + is being used. It is possible to support a different database, but that + begins to duplicate functionality from Share Authentication (Section 1.3). + + Config Options: + mysql_host + mysql_db + mysql_username + mysql_passwd + mysql_table + mysql_usercol + mysql_passcol + mysql_other + mysql_fields + + 'mysql_other' is an optional clause appended to the query. + Ex: mysql_other = "access = 'admin'" + + 'mysql_fields' is a comma separated list of the fields to return from + 'mysql_table' + Ex: mysql_fields = 'id,username,email,homedir' + + 1.3 Shared Authentication + ------------------------------------------------------------------------------ + Because libglue uses a mysql database to store session info, it is possible + to share session information between applications, creating a "Single Sign + On" (SSO) framework for web applications. libglue supports this out of + the box, with the following assumptions: + 1) The initial authentication is being handled elsewhere + 2) "SSO" session data is stored in a mysql database. + 3) The SSO database uses the schema described in Section 2.3. + + libglue keeps track of the 'type' of authentication each session uses, so + can still use LDAP or MySQL authentication when also using SSO. + + Config options: + sso_host + sso_db + sso_username + sso_pass + sso_table + sso_sid + sso_usercol + sso_expirecol + sso_length + sso_dbh_name + + +2 Database schemas +-------------------------------------------------------------------------------- + + Below are sample schemas for use with libglue. Mandatory fields are + indicated with a '*'. Unless stated otherwise, field NAMES can be set in + the config file. + + 2.1 For Session Management + ------------------------------------------------------------------------------ + CREATE TABLE session_data ( + * id varchar(32) NOT NULL default '', + * username varchar(16) NOT NULL default '', + * expire int(10) unsigned NOT NULL default '0', + * type enum('sso','mysql','ldap') NOT NULL default 'sso', + * data text, + PRIMARY KEY (id)) + + This session table should work for any type of authentication you do. + 'id' is an md5sum by default (as generated by php) but you can make + something else up if you've got the spare entropy. 'Type' obviously + only applies if you're using more than 1 type of authentication, + but the code assumes that it's present. + + 'data' is the field where serialized php data (from $_SESSION) is stored. + If you overflow this field, weird things may happen. + + + 2.2 For LDAP Authentication + ------------------------------------------------------------------------------ + + Basic LDAP authentication with libglue doesn't require a mysql database, + only session management. However, you will most likely need to store + some user information locally, in which case the table definition in + Section 2.3 is a good starting point. + + 2.3 For MySQL Authentication + ------------------------------------------------------------------------------ + + CREATE TABLE user ( + * id int(11) NOT NULL default '0', + * username varchar(255) NOT NULL default '', + * password varchar(255) default NULL, + fullname varchar(255) NOT NULL default '', + email varchar(255) default NULL, + status enum('disabled','enabled','dev') NOT NULL default 'enabled', + expire date default NULL, + phone varchar(255) NOT NULL default '', + PRIMARY KEY (id), + UNIQUE KEY username (username), + UNIQUE KEY id (id) + } + + Feel free to add columns to this table and then specify them in + 'mysql_fields' to make them part of your session data. + + 2.3 For Shared Authentication + ------------------------------------------------------------------------------ + + If you need to store user data locally, see the definition in Section 2.3. + + +3 The Config file +-------------------------------------------------------------------------------- + + 3.1 Formatting + ------------------------------------------------------------------------------ + The libglue config file is a lot like the smb.cnf file if you've ever used + samba (it's really easy to parse). Options are specified like + + option = value + + 'option' is a letter followed by any number of letters or numbers. + The spaces between 'option' and 'value' are optional. + 'value' may be single quoted, double quoted, or not quoted at all. + semicolons at the end of the line are ignored. + '#' is the single-line comment character. + + 3.2 Subsections + ------------------------------------------------------------------------------ + The config file parser can generate subsections in the config: + + > [libglue] + > option1 = value; + > option2 = 'value'; + > option3 = "value" + > [conf] + > option1 = value; + > otheroption = othervalue; + > [other] + > foo = "bar"; + + The parser then returns: + array( + 'libglue' => ('option1' => 'value', + 'option2' => 'value', + 'option3' => 'value'), + 'conf' => ('option1' => 'value', + 'otheroption' => 'othervalue'), + 'other' => ('foo' => 'bar') + ); + + 3.3 Arrays + ------------------------------------------------------------------------------ + You can create arrays of values in the config file by declaring an option + multiple times: + + [libglue] + ldap_fields = 'cn' + ldap_fields = 'homedirectory' + ldap_fields = 'uidnumber' + ldap_fields = 'uid' + ldap_fields = 'osuuid' + + would return the following: + array( + 'libglue' => ('ldap_fields' => ( + 0 => 'cn', + 1 => 'homedirectory', + 2 => 'uidnumber', + 3 => 'uid', + 4 => 'osuuid') + ) + ) + + + 3.3 Retrieving options + ------------------------------------------------------------------------------ + LIBGLUE/config.php defines two functions, conf() and libglue_param() for + retrieving values from the config file. See "Libglue in action" below. + + +4 Session Data and Management +-------------------------------------------------------------------------------- + + Libglue should relieve some of the burden of session management from your app + once a user is authenticated. The config file has the following parameters, + + user_data_name - Name of the array to store authentication session data in. + Ex: + user_data_name = 'user' + + Libglue then puts all the account information it retrieves + into $_SESSION['user'] + + user_id - fieldname for userid, + stored in $_SESSION[user_data_name][user_id] + user_username - fieldname for username, + stored in $_SESSION[user_data_name][user_username] + + Then for each of your authentication methods: + + ldap_uidfield = 'uidnumber' + ldap_usernamefield = 'uid' + mysql_uidfield = 'id' + mysql_usernamefield = 'username' + + Note that in this case, 'sso' isn't really an authentication method + (the info has to be looked up either in ldap or mysql). + + What this lets you do is ignore account type in your application, since + every session will have the same field names. + + +5 Libglue in action +-------------------------------------------------------------------------------- + + Libglue assumes there are three basic types of files in your application: + 1) Login/Authentication page + 2) Restricted pages + 3) Logout/Cleanup page + + Example login and logout pages are in the LIBGLUE/examples directory. + + For (2), you'll be calling the same code over and over. It is a good idea + to create an init file to take care of these common tasks in your application. + In each file, you'll do a + + > $restricted = 1; + > require_once('/path/to/init.php'); + + right off the bat; libglue needs to run before anything else so it can send + HTTP headers for cookies and redirection if necessary. + + Here is a sample init.php: + + + <?php + //config defines readconfig(), libglue_param(), and conf() + require_once("/data/libglue/config.php"); + // 1st parameter is the path to the config file + // 2nd parameter is DEBUG (1 or 0) + // '$config' will hold the parsed config data + $config = read_config("/data/app/conf/config.conf",0); + + // Register subsection 'libglue' in libglue_param() + libglue_param($config['libglue']); + + //Register subsection 'app' in conf() + conf($config['app']); + //Require the rest of the libglue code: + // Authentication methods: + require_once('/data/libglue/auth.php'); + // Session handling code: + require_once('/data/libglue/session.php'); + // Common database handle: + require_once('/data/libglue/dbh.php'); + + // This is optional, if you have some pages where session data and + // authentication aren't relevant. Otherwise just do check_session(). + if($restricted === 1) check_session(); + ?> + + libglue_param() and conf() make use of static member variables and + tests on paramter types to register/retrieve config data. When passed an + array, these functions assume you're registering config options. If given + a string, as in: + + $database_name = libglue_param('local_db'); + + the function will look for the key 'local_db' in the values that have been + previously registered with it. This is a little bit hokey, but objects + don't yet support static members in php so it's about the best we can do. + + + Session management is just taken care of; anything you put in $_SESSION in + your app is serialized, stored in the db when the page is done redering, + and retrieved on page load. + + + Database handle management is nice with libglue; if you've defined + 'dbh' in the config file, you can call dbh() to use that database handle again: + + $dbh = dbh(); + mysql_query($sql, $dbh); + + or + + mysql_query($sql, dbh()); + + +6 Help, FAQs +-------------------------------------------------------------------------------- + + Libglue is distributed at: + + http://oss.oregonstate.edu/libglue/ + + as it becomes more mature and widely used, this page may include more help + documentation. + + For now, feel free to email + + cws-prog@lists.orst.edu + + with any questions or bug reports. + +-- Central Web Services, + Oregon State University + diff --git a/libglue/auth.php b/libglue/auth.php new file mode 100644 index 00000000..0ef41e8c --- /dev/null +++ b/libglue/auth.php @@ -0,0 +1,399 @@ +<? +/* ------------------- CVS INFO ---------------------- + * + * $Source: /data/cvsroot/ampache/libglue/auth.php,v $ + * last modified by $Author: vollmerk $ at $Date: 2003/11/27 10:19:28 $ + * + * Libglue, a free php library for handling authentication + * and session management. + * + * Written and distributed by Oregon State University. + * http://oss.oregonstate.edu/libglue + * + * --------------------------------------------------- + */ + +// +// Attempt to authenticate using the services in +// auth_methods, and returns an auth_config object +// which describes the results of the authentication +// attempt +function authenticate($username, $password) +{ + // First thing to do is check for the gone fishing file: + $stopfile = libglue_param('stop_auth'); + if ( file_exists($stopfile) ) + { + echo "We should tell the users here that no one can log in.\n"; + exit(); + } + + $methods = libglue_param('auth_methods'); + if(!is_array($methods)) + { + $auth = call_user_func("auth_$methods",$username,$password); + } + else + { + foreach($methods as $method) + { + $auth = call_user_func("auth_$method", $username,$password); + if($auth['success'] == 1) break; + } + } + return $auth; +} + +function get_ldap_user ($username,$fields=0) +{ + $auth = array(); + + $auth_dn = libglue_param('ldap_auth_dn'); + $user_dn = libglue_param('ldap_user_dn'); + $filter = libglue_param('ldap_filter'); + $host = libglue_param('ldap_host'); + $pass = libglue_param('ldap_pass'); + $ldapfields = libglue_param('ldap_fields'); + $protocol = libglue_param('ldap_version'); + + // can we even connect? + if ( $ldap_link = @ldap_connect( $host ) ) + { + + //Snazzy new protocol stuff + if(!empty($protocol)) ldap_set_option($ldap_link, + LDAP_OPT_PROTOCOL_VERSION, + $protocol); + + // now try and bind with system credentials for searching. + if ( @ldap_bind($ldap_link, $filter."".$auth_dn, $pass) ) + { + // now search and retrieve our user data + $ldap_uid = libglue_param('ldap_uidfield'); + $ldap_username = libglue_param('ldap_usernamefield'); + + //force uid and username to be part of the query + if(!in_array($ldap_uid,$ldapfields)) $ldapfields[] = $ldap_uid; + if(!in_array($ldap_username,$ldapfields)) $ldapfields[] = $ldap_username; + + $sr = ldap_search($ldap_link, $user_dn, "(".$filter."".$username.")", $ldapfields, 0, 1); +/* $sr = @ldap_search($ldap_link, $user_dn, "(".$filter."".$username.")");*/ + + //info will contain a 1-element array with our user's info + $info = ldap_get_entries($ldap_link, $sr); + + foreach($ldapfields as $field) + { + $auth[$field] = $info[0][$field][0]; + } + $sess_username = libglue_param('user_username'); + $sess_id = libglue_param('user_id'); + $auth[$sess_username] = $username; + $auth[$sess_id] = $info[0][$ldap_uid][0]; + } + + // + // Here means we couldn't use the service. + // So it's most likely config related. + // Check the username and password? + // + else + { $auth['error'] = libglue_param('bad_auth_cred'); } + } + + // + // This most often will mean we can't reach the server. + // Perhaps it's down, or we mistyped the address. + // + else + { $auth['error'] = libglue_param('connect_error'); } + + // Done with the link, give it back + ldap_close($ldap_link); + + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) $auth['type'] = 'sso'; + else $auth['type'] = 'ldap'; + return $auth; +} + +function get_mysql_user ($username,$fields=null) +{ + $auth = array(); + $dbh = dbh(); + $user_table = libglue_param('mysql_table'); + $mysql_uid = libglue_param('mysql_uidfield'); + $mysql_username = libglue_param('mysql_usernamefield'); + $mysql_fields = libglue_param('mysql_fields'); + $sql = "SELECT "; + if(is_null($fields)) $sql .= " * "; + else + { + if(!is_array($fields)) $fields = array($fields); + foreach($fields as $field) + { + $sql .= "$field,"; + } + $sql = substr($sql, 0, strlen($sql)-1); + } + + $sql .= " FROM $user_table WHERE $mysql_username = '$username'"; + $result = mysql_query($sql, $dbh); + + foreach($ldapfields as $field) + { + $auth[$field] = $info[0][$field][0]; + } + $sess_username = libglue_param('user_username'); + $sess_id = libglue_param('user_id'); + $auth[$sess_username] = $username; + $auth[$sess_id] = $info[0][$ldap_uid][0]; + + $auth['type'] = 'mysql'; + return $auth; +} + + +function auth_ldap ($username, $password) +{ + $auth = array(); + $auth['success'] = 0; // don't want to keep setting this + $auth_dn = libglue_param('ldap_auth_dn'); + $user_dn = libglue_param('ldap_user_dn'); + $filter = libglue_param('ldap_filter'); + $host = libglue_param('ldap_host'); + $pass = libglue_param('ldap_pass'); + $ldapfields = libglue_param('ldap_fields'); + // Did we get fed proper variables? + if(!$username || !$password) + { + $auth['error'] = libglue_param('empty_field'); + // I'm not a huge fan of returning here, + // but why force more logic? + return $auth; + } + + // can we even connect? + if ( $ldap_link = @ldap_connect( $host ) ) + { + // now try and bind with system credentials for searching. + if ( @ldap_bind($ldap_link, $filter."".$auth_dn, $pass) ) + { + // now search and retrieve our user data + $ldap_uid = libglue_param('ldap_uidfield'); + $ldap_username = libglue_param('ldap_usernamefield'); + + //force uid and username to be part of the query + if(!in_array($ldap_uid,$ldapfields)) $ldapfields[] = $ldap_uid; + if(!in_array($ldap_username,$ldapfields)) $ldapfields[] = $ldap_username; + + $sr = ldap_search($ldap_link, $user_dn, "(".$filter."".$username.")", $ldapfields, 0, 1); + //info will contain a 1-element array with our user's info + $info = @ldap_get_entries($ldap_link, $sr); + + // + // The real authentication: + // binding here with the user's credentials + // + //if ( ldap_bind($ldap_link, $user_dn, $password) ) { + if ( ($info["count"] == 1) && (@ldap_bind($ldap_link, + $info[0]['dn'], + $password) ) ) + { + $auth['info'] = array(); + foreach($ldapfields as $field) + { + $auth['info'][$field] = $info[0][$field][0]; + } + $sess_username = libglue_param('user_username'); + $sess_id = libglue_param('user_id'); + $auth['info'][$sess_username] = $username; + $auth['info'][$sess_id] = $info[0][$ldap_uid][0]; + $auth['success'] = 1; + } + else + { + // show the error here, better than anything I can come up with + // most likely bad username or password + // We'll handle two cases, where the username doesn't exist, + // and where more than 1 exists separately in case we + // decide to do some logging or something fancy someday + if($info["count"] == 0) + { + $auth['error'] = libglue_param('login_failed'); + } + else + { + // We could return the error here + // EXCEPT that we want the error message to be the same + // for a bad password as a bad username + // $auth->error = ldap_error($ldap_link); + $auth['error'] = libglue_param('login_failed'); + } + } + } + + // + // Here means we couldn't use the service. + // So it's most likely config related. + // Check the username and password? + // + else + { + $auth['error'] = libglue_param('bad_auth_cred'); + } + } + + // + // This most often will mean we can't reach the server. + // Perhaps it's down, or we mistyped the address. + // + else + { + $auth['error'] = libglue_param('connect_error'); + } + + // Done with the link, give it back + ldap_close($ldap_link); + $auth['type'] = 'ldap'; + return $auth; +} + +/* + * MySQL authentication. + * returns true/false depending on whether the user was authenticated + * successfully + * The crypt settings below assume the php crypt() function created the passwords. + * But hopson updated it to use mysql PASSWORD() instead + */ + +function auth_mysql($username, $password) { + + $auth = array(); + $auth['success'] = 0; + + // Did we get fed proper variables? + if(!$username or !$password) { + $auth['error'] = 'Empty username/password'; + return $auth; + } + + // + // Retrieve config parameters set in config.php + // + $dbhost = libglue_param('mysql_host'); + $dbuser = libglue_param('mysql_user'); + $dbpass = libglue_param('mysql_pass'); + $dbname = libglue_param('mysql_db'); + $passfield = libglue_param('mysql_passcol'); + $table = libglue_param('mysql_table'); + $usercol = libglue_param('mysql_usercol'); + $other = libglue_param('mysql_other'); + $fields = libglue_param('mysql_fields'); + + + $mysql_uidfield = libglue_param('mysql_uidfield'); + $mysql_usernamefield = libglue_param('mysql_usernamefield'); + + if(!preg_match("/$mysql_uidfield/",$fields)) $fields .= ",$mysql_uidfield"; + if(!preg_match("/$mysql_usernamefield/",$fields)) $fields .= ",$mysql_usernamefield"; + + if($other == '') $other = '1=1'; + + if ($mysql_link = @mysql_connect($dbhost,$dbuser,$dbpass)) + { + // + // now retrieve the stored password to use as salt + // for password checking + // + $sql = "SELECT $passfield FROM $table" . + " WHERE $usercol = '$username' " . + " AND $other LIMIT 1"; + @mysql_select_db($dbname, $mysql_link); + $result = @mysql_query($sql, $mysql_link); + $row = @mysql_fetch_array($result); + + $password_check_sql = "PASSWORD('$password')"; + + $sql = "SELECT version()"; + $db_results = @mysql_query($sql, $mysql_link); + $version = @mysql_fetch_array($db_results); + + $mysql_version = substr(preg_replace("/(\d+)\.(\d+)\.(\d+).*/","$1$2$3",$version[0]),0,3); + + if ($mysql_version > "409" AND substr($row[0],0,1) !== "*") { + $password_check_sql = "OLD_PASSWORD('$password')"; + } + + $sql = "SELECT $fields FROM $table" . + " WHERE $usercol = '$username'" . + " AND $passfield = $password_check_sql" . + " AND $other LIMIT 1"; + $rs = @mysql_query($sql, $mysql_link); + //This should only fail on a badly formed query. + if(!$rs) + { + $auth['error'] = @mysql_error(); + } + + // + // Retrieved the right info, set auth->success and info. + // + if (@mysql_num_rows($rs) == 1) + { + // username and password are successful + $row = mysql_fetch_array($rs); + $sess_username = libglue_param('user_username'); + $sess_id = libglue_param('user_id'); + $auth[$info][$sess_username] = $row[$mysql_usernamefield]; + $auth[$info][$sess_id] = $row[$mysql_uidfield]; + $auth[$info] = $row; + $auth['info'] = $row; + $auth['success'] = 1; + } + + // + // We didn't find anything matching. No user, bad password, ? + // + else + { + $auth['error'] = libglue_param('login_failed'); + } + } + + // + // Couldn't connect to database at all. + // + else + { + $auth['error'] = libglue_param('bad_auth_cred'); + } + + $auth['type'] = 'mysql'; + return $auth; + +} // auth_mysql + + +function auth_sso ($username, $password) +{ + $auth = new auth_response(); + $auth->success = 0; + $auth->error = "SSO Authentication failed."; + return $auth; +} + +// This is the auth_response class that will be returned during +// and authentication - this allows us to set some variables +// by the session for later lookup +class auth_response { + var $username; + var $userid; + var $error; + var $success; + var $info; +} + + +?> diff --git a/libglue/config.php b/libglue/config.php new file mode 100644 index 00000000..c1ca07a8 --- /dev/null +++ b/libglue/config.php @@ -0,0 +1,173 @@ +<?php + +function read_config($config_file, $debug = 0) { + $fp = fopen($config_file,'r'); + if(!is_resource($fp)) die("Can't open config file $config_file"); + $file_data = fread($fp,filesize($config_file)); + fclose($fp); + + // explode the var by \n's + $data = explode("\n",$file_data); + if($debug) echo "<pre>"; + + $count = 0; + $config_name = ''; + foreach($data as $value) + { + $count++; + if (preg_match("/^\[([A-Za-z]+)\]$/",$value,$matches)) + { + // If we have previous data put it into $results... + if (!empty($config_name) && count(${$config_name})) $results[$config_name] = ${$config_name}; + $config_name = $matches[1]; + } // if it is a [section] name + + elseif ($config_name) + { + // if it's not a comment + if (preg_match("/^(\w[\w\d]*)\s*=\s*\"{1}(.*?)\"{1};*$/",$value,$matches) + || preg_match("/^(\w[\w\d]*)\s*=\s*\'{1}(.*?)\'{1};*$/", $value, $matches) + || preg_match("/^(\w[\w\d]*)\s*=\s*[\'\"]{0}(.*)[\'\"]{0};*$/",$value,$matches)) + { + if (isset(${$config_name}[$matches[1]]) && is_array(${$config_name}[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> to existing key <strong>$matches[1]</strong>\n"; + array_push(${$config_name}[$matches[1]], $matches[2]); + } + elseif (isset(${$config_name}[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> to existing key $matches[1]</strong>\n"; + ${$config_name}[$matches[1]] = array(${$config_name}[$matches[1]],$matches[2]); + } + elseif ($matches[2] !== "") + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> for key <strong>$matches[1]</strong>\n"; + ${$config_name}[$matches[1]] = $matches[2]; + } + + // if there is something there and it's not a comment + elseif ($value{0} !== "#" AND strlen(trim($value)) > 0) + { + echo "Error Invalid Config Entry --> Line:$count"; die; + } // else if it's not a comment and there is something there + + else + { + if($debug) + echo "Key <strong>$matches[1]</strong> defined, but no value set\n"; + } + } // end if it's not a comment + + } // else if no config_name + + + elseif (preg_match("/^([\w\d]+)\s+=\s+[\"]{1}(.*?)[\"]{1}$/",$value,$matches) + || preg_match("/^([\w\d]+)\s+=\s+[\']{1}(.*?)[\']{1}$/", $value, $matches) + || preg_match("/^([\w\d]+)\s+=\s+[\'\"]{0}(.*)[\'\"]{0}$/",$value,$matches)) + { + if (is_array($results[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> to existing key <strong>$matches[1]</strong>\n"; + array_push($results[$matches[1]], $matches[2]); + } + elseif (isset($results[$matches[1]]) && isset($matches[2]) ) + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> to existing key $matches[1]</strong>\n"; + $results[$matches[1]] = array($results[$matches[1]],$matches[2]); + } + elseif ($matches[2] !== "") + { + if($debug) + echo "Adding value <strong>$matches[2]</strong> for key <strong>$matches[1]</strong>\n"; + $results[$matches[1]] = $matches[2]; + } + + // if there is something there and it's not a comment + elseif ($value{0} !== "#" AND strlen(trim($value)) > 0) + { + echo "Error Invalid Config Entry --> Line:$count"; die; + } // else if it's not a comment and there is something there + + else + { + if($debug) + echo "Key <strong>$matches[1]</strong> defined, but no value set\n"; + } + + } // end else + + } // foreach + + if (count(${$config_name})) + { + $results[$config_name] = ${$config_name}; + } + + if($debug) echo "</pre>"; + + return $results; + +} // end read_config + +function libglue_param($param,$clobber=0) +{ + static $params = array(); + if(is_array($param)) + //meaning we are setting values + { + foreach ($param as $key=>$val) + { + if(!$clobber && isset($params[$key])) + { + echo "Error: attempting to clobber $key = $val\n"; + exit(); + } + $params[$key] = $val; + } + return true; + } + else + //meaning we are trying to retrieve a parameter + { + if(isset($params[$param])) return $params[$param]; + else return false; + } +} + +function conf($param,$clobber=0) +{ + static $params = array(); + if(is_array($param)) + //meaning we are setting values + { + foreach ($param as $key=>$val) + { + if(!$clobber && isset($params[$key])) + { + echo "Error: attempting to clobber $key = $val\n"; + exit(); + } + $params[$key] = $val; + } + return true; + } + else + //meaning we are trying to retrieve a parameter + { + if(isset($params[$param])) return $params[$param]; + else return false; + } +} + +function dbh($str='') +{ + if($str !== '') $dbh = libglue_param(libglue_param($str)); + else $dbh = libglue_param(libglue_param('dbh')); + if(!is_resource($dbh)) die("Bad database handle: $dbh"); + else return $dbh; +} diff --git a/libglue/dbh.php b/libglue/dbh.php new file mode 100644 index 00000000..71d04b9c --- /dev/null +++ b/libglue/dbh.php @@ -0,0 +1,53 @@ +<? +/* + * ---------------------------- CVS INFO -------------------------------- + * + * $Source: /data/cvsroot/ampache/libglue/dbh.php,v $ + * last modified by $Author: vollmerk $ at $Date: 2003/11/24 05:53:13 $ + * + * Libglue, a free php library for handling authentication + * and session management. + * + * Written and distributed by Oregon State University. + * http://oss.oregonstate.edu/libglue + * + * ----------------------------------------------------------------------- + */ + +/*---------------------------------------------------------------------- + + For complete information on this toolkit see the README located in this + directory. + + This is the database handler class. This will setup and return a + database handle for use in your application. Simply pass it a + username and password. If an error occurs you'll be presented with + a verbose reason for the error. +----------------------------------------------------------------------*/ + +function setup_sess_db($name, $host, $db, $username, $password) +{ + $dbh = @mysql_connect($host, $username, $password) or header("Location:" . conf('web_path') . "/test.php"); + if ( !is_resource($dbh) ) + { + echo "Unable to connect to \"". $host ."\" in order to \n" . + "use the \"". $db ."\" database with account \"".$username." : ".$password. + "\"\n . Perhaps the database is not " . + "running, \nor perhaps the admin needs to change a few variables in\n ". + "the config files in order to point to the correct database.\n"; + echo "Details: " . + mysql_errno() . ": " . + mysql_error() . "\n"; + die(); + } + + else + { + @mysql_select_db($db, $dbh) or header("Location:" . conf('web_path') . "/test.php"); + libglue_param(array($name=>$dbh)); + } + + return $dbh; +} + +?> diff --git a/libglue/libdb.php b/libglue/libdb.php new file mode 100644 index 00000000..00e8a9b2 --- /dev/null +++ b/libglue/libdb.php @@ -0,0 +1,95 @@ +<?php +// +// PHP itself sort of supports the behavior defined here, +// but I don't trust it, and I think it's better to do +// application-level database abstraction. +// + +function db_connect($host='localhost',$user=null,$password=null) +{ + static $dbh = null; + // If we haven't already connected, do so + // The first call must include this info + // Subsequent calls that provide this info may bork db_query() below if you're not careful, + // but until I can have static class variables, I'm not going to make an object + // out of this mojo. + if(!empty($host) && isset($user) && isset($password)) $dbh = @mysql_connect($host,$user,$password); + + // If we've already connected successfully, we're good + if(is_resource($dbh)){ return $dbh; } + // On a failed connection, let's just die? + else die("Unable to create database connection in db_connect()"); +} + +function db_makeinsert($vars, $table) +{ + static $tables = array(); + $dbh = db_connect(); + if(!isset($tables[$table])) $tables[$table] = db_describe($table); + $fields = $tables[$table]; + + foreach($fields as $field) + { + //only addslashes if magic quotes is off + if(get_magic_quotes_gpc) $vars[$field['Field']] = stripslashes($vars[$field['Field']]); + addslashes($vars[$field['Field']]); + + if(isset($vars[$field['Field']])) + { + + $q1 = isset($q1)? $q1.','.$field['Field']:'INSERT INTO '.$table.'('.$field['Field']; + $q2 = isset($q2)? $q2.",\"".$field[$var['Field']]."\"":" VALUES(\"".$vars[$field['Field']]."\""; + } + } + $q1.=')'; + $q2.=')'; + $query = $q1.$q2; + return $query; +} + + +function db_select($database, $dbh=null) +{ + if(is_resource($dbh)) @mysql_select_db($database); + else @mysql_select_db($database, db_connect()); +} + +function db_describe($thingy) +{ + $descriptions = array(); + foreach( (explode(',',$thingy)) as $field) + { + db_query("DESCRIBE $field"); + while($row = db_fetch()){ $descriptions[] = $row; } + } + return $descriptions; +} + +function db_query($qry=null, $dbh=null) +{ + static $result = null; + if(!is_resource($dbh)) $dbh = db_connect(); + if(is_null($qry)) + { + if(is_resource($result)) return $result; + else return false; + } + else + { + $result = @mysql_query($qry, $dbh); + return $result; + } +} + +function db_fetch($result=null) +{ + if(!is_resource($result)) return @mysql_fetch_array(db_query()); + else return @mysql_fetch_array($result); +} + +function db_scrub($var,$htmlok=false) +{ + if(!get_magic_quotes_gpc()) $var = addslashes($var); + return $var; +} + diff --git a/libglue/session.php b/libglue/session.php new file mode 100644 index 00000000..aef10c60 --- /dev/null +++ b/libglue/session.php @@ -0,0 +1,417 @@ +<? +/* ------------------- CVS INFO ---------------------- + * + * $Source: /data/cvsroot/ampache/libglue/session.php,v $ + * last modified by $Author: vollmerk $ at $Date: 2003/11/24 05:53:13 $ + * + * Libglue, a free php library for handling authentication + * and session management. + * + * Written and distributed by Oregon State University. + * http://oss.oregonstate.edu/libglue + * + * --------------------------------------------------- + */ + + +function check_sess_db($dbtype = 'local') +{ + if($dbtype === 'sso') + { + $dbh = libglue_param(libglue_param('sso_dbh_name')); + if(is_resource($dbh)) return $dbh; + $dbh_name = libglue_param('sso_dbh_name'); + $host = libglue_param('sso_host'); + $db = libglue_param('sso_db'); + $user = libglue_param('sso_username'); + $pass = libglue_param('sso_pass'); + $name = libglue_param('sso_dbh_name'); + } + elseif($dbtype === 'local') + { + $dbh = libglue_param(libglue_param('local_dbh_name')); + if(is_resource($dbh)) return $dbh; + $dbh_name = libglue_param('local_dbh_name'); + $host = libglue_param('local_host'); + $db = libglue_param('local_db'); + $user = libglue_param('local_username'); + $pass = libglue_param('local_pass'); + $name = libglue_param('local_dhb_name'); + } + $dbh = setup_sess_db($dbh_name,$host,$db,$user,$pass); + + if(is_resource($dbh)) return $dbh; + else die("Could not connect to $dbtype database for session management"); +} + +// +// Really we are just checking the session here -- we want to see if + +// if the user has a valid session, if they do then we'll let them do +// what they need to do. +// + +function check_session($id=0) +{ + //If an id isn't passed in, retrieve one from the cookie + if($id===0) { + + /* + We don't need to set cookie params here php + is smart enough to know which cookie it wants + via the session_name. Setting cookie params + here sometimes made php create a new cookie + which is very bad :) -- Vollmer + */ + $name = libglue_param('sess_name'); + if($name) session_name($name); + + // Start the session, then get the cookie id + session_start(); + $id = strip_tags($_COOKIE[$name]); + } + + // Determine if we need to check the SSO database: + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + $sso_mode = in_array('sso',$auth_methods,TRUE); + + $local = get_local_session($id); + if($sso_mode) $sso = get_sso_session($id); + + if($sso_mode && !$sso) + { + return FALSE; + } + else if ($sso_mode && is_array($sso)) + { + if(is_array($local)) return TRUE; + else + { + // + // Should we do gc here, just in case + // local is only expired? + // (The insert in make_local_session + // will fail if we don't) + // + $newlocal = make_local_session_sso($sso); + return $newlocal; + } + } + //If we get here, we're not using SSO mode + else if (!is_array($local)) + { + return FALSE; + } + else return TRUE; +} + +function make_local_session_only($data,$id=0) +{ + if($id===0) + { + $name = libglue_param('sess_name'); + $domain = libglue_param('sess_domain'); + if($name) session_name($name); + //Lifetime of the cookie: + $cookielife = libglue_param('sess_cookielife'); + if(empty($cookielife)) $cookielife = 0; + //Secure cookie? + $cookiesecure = libglue_param('sess_cookiesecure'); + if(empty($cookiesecure)) $cookiesecure = 0; + //Cookie path: + $cookiepath = libglue_param('sess_cookiepath'); + if(empty($cookiepath)) $cookiepath = '/'; + + if(!empty($domain)) session_set_cookie_params($cookielife,$cookiepath,$domain,$cookiesecure); + + // Start the session + session_start(); + + + /* + Before a refresh we do not have a cookie value + here so let's use session_id() --Vollmer + */ + $id = session_id(); + } + + $userfield = libglue_param('user_username'); + $username = $data['info'][$userfield]; + $type = $data['type']; + + $local_dbh = check_sess_db('local'); + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_expirecol = libglue_param('local_expirecol'); + $local_typecol = libglue_param('local_typecol'); + $sql= "INSERT INTO $local_table ". + " ($local_sid,$local_usercol,$local_typecol)". + " VALUES ('$id','$username','$type')"; + $db_result = mysql_query($sql, $local_dbh); + + if($db_result) return TRUE; + else return FALSE; +} + +function make_local_session_sso($sso_session) +{ + $sso_usercol = $sso_session[libglue_param('sso_usercol')]; + $sso_sid = $sso_session[libglue_param('sso_sid')]; + $sso_expire = $sso_session[libglue_param('sso_expirecol')]; + + $user = get_ldap_user($sso_usercol); + + $data = array('user'=>$user); + + //Somewhat stupidly, we have to initialize $_SESSION here, + // or sess_write will blast it for us + $_SESSION = $data; + + $db_data = serialize($data); + $local_dbh = check_sess_db('local'); + + //Local stuff we need: + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_expirecol = libglue_param('local_expirecol'); + $local_typecol = libglue_param('local_typecol'); + $sql= "INSERT INTO $local_table ". + " ($local_sid,$local_usercol,$local_datacol,$local_expirecol,$local_typecol)". + " VALUES ('$sso_sid','$sso_usercol','$db_data','$sso_expire','sso')"; + $db_result = mysql_query($sql, $local_dbh); + + if($db_result) return TRUE; + else return FALSE; +} + +function get_local_session($sid) +{ + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_typecol = libglue_param('local_typecol'); + + $local_dbh = check_sess_db('local'); + $time = time(); + $sql = "SELECT * FROM $local_table WHERE $local_sid='$sid' AND $local_expirecol > $time"; + $db_result = mysql_query($sql, $local_dbh); + $session = mysql_fetch_array($db_result); + + if(is_array($session)) $retval = $session; + else $retval = FALSE; + + if($retval === FALSE) + { + //Find out what's going on + } + + return $retval; +} + +function get_sso_session($sid) +{ + $sso_table = libglue_param('sso_table'); + $sso_sid = libglue_param('sso_sid'); + $sso_expirecol = libglue_param('sso_expirecol'); + $sso_length = libglue_param('sso_length'); + $sso_usercol = libglue_param('sso_usercol'); + + $sso_dbh = check_sess_db('sso'); + $time = time(); + $sql = "SELECT * FROM $sso_table WHERE $sso_sid='$sid' AND $sso_expirecol > $time"; + $db_result = mysql_query($sql, $sso_dbh); + $sso_session = mysql_fetch_array($db_result); + + $retval = (is_array($sso_session))?$sso_session:FALSE; + return $retval; +} + + + +// This will start the session tools, then destroy anything in the database then +// clear all of the session information +function logout ($id=0) +{ + sess_destroy($id); + $login_page = libglue_param('login_page'); + // should clear both the database information as well as the + // current session info + header("Location: $login_page"); + die(); + return true; +} + +// Double checks that we have a database handle +// Args are completely ignored - we're using a database here +function sess_open($save_path, $session_name) +{ + $local_dbh = check_sess_db(); + if ( !is_resource($local_dbh) ) + { + echo "<!-- Unable to connect to local server in order to " . + "use the session database. Perhaps the database is not ". + "running, or perhaps the admin needs to change a few variables in ". + "the config file in order to point to the correct ". + "database.-->\n"; + return FALSE; + } + + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + $sso_dbh = check_sess_db('sso'); + if ( !is_resource($sso_dbh) ) + { + echo "<!-- Unable to connect to the SSO server in order to " . + "use the session database. Perhaps the database is not ". + "running, or perhaps the admin needs to change a few variables in ". + "modules/include/global_settings in order to point to the correct ". + "database.-->\n"; + return FALSE; + } + } + return TRUE; +} + +// Placeholder function, does nothing +function sess_close() +{ + return true; +} + +// Retrieve session identified by 'key' from the database +// and return the data field +function sess_read($key) +{ + $retval = 0; + $session = get_local_session($key); + $datacol = libglue_param('local_datacol'); + if(is_array($session)) $retval = $session[$datacol]; + else $retval = ""; + return $retval; +} + + +// +// Save the session data $val to the database +// +function sess_write($key, $val) +{ + $local_dbh = check_sess_db('local'); + $local_datacol = libglue_param('local_datacol'); + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + + $auth_methods = libglue_param('auth_methods'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + + // If they've got the long session + if ($_COOKIE['amp_longsess'] == '1') { + $time = time() + 86400*364; + } + + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(!in_array('sso',$auth_methods,TRUE)) + { + // If not using sso, we now need to update the expire time + $sql = "UPDATE $local_table SET $local_datacol='" . sql_escape($val) . "',$local_expirecol='$time'". + " WHERE $local_sid = '$key'"; + } + else $sql = "UPDATE $local_table SET $local_datacol='" . sql_escape($val) . "',$local_expirecol='$time'". + " WHERE $local_sid = '$key'"; + + return mysql_query($sql, $local_dbh); +} + +// +// Remove the current session from the database. +// +function sess_destroy($id=0) +{ + if($id == 0) { + session_start(); + $id = session_id(); + } + + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + $sso_sid = libglue_param('sso_sid'); + $sso_table = libglue_param('sso_table'); + $sso_dbh = check_sess_db('sso'); + $sql = "DELETE FROM $sso_table WHERE $sso_sid = '$id' LIMIT 1"; + $result = mysql_query($sql, $sso_dbh); + } + $local_sid = libglue_param('local_sid'); + $local_table = libglue_param('local_table'); + + $local_dbh = check_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_sid = '$id' LIMIT 1"; + $result = mysql_query($sql, $local_dbh); + $_SESSION = array(); + + /* Delete the long ampache session cookie */ + setcookie ("amp_longsess", "", time() - 3600); + + /* Delete the ampache cookie as well... */ + setcookie (libglue_param('sess_name'),"", time() - 3600); + + return TRUE; +} + +// +// This function is called with random frequency +// to remove expired session data +// +function sess_gc($maxlifetime) +{ + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + if(in_array('sso',$auth_methods,TRUE)) + { + //Delete old sessions from SSO + // We do 'where length' so we don't accidentally blast + // another app's sessions + $sso_expirecol = libglue_param('sso_expirecol'); + $sso_table = libglue_param('sso_table'); + $sso_length = libglue_param('sso_length'); + $local_length = libglue_param('local_length'); + + $sso_dbh = check_sess_db('sso'); + $time = time(); + $sql = "DELETE FROM $sso_table WHERE $sso_expirecol < $time". + " AND $sso_length = '$local_length'"; + $result = mysql_query($sql, $sso_dbh); + } + $local_expirecol = libglue_param('local_expirecol'); + $local_table = libglue_param('local_table'); + $time = time(); + $local_dbh = check_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_expirecol < $time"; + $result = mysql_query($sql, $local_dbh); + return true; +} + +// +// Register all our cool session handling functions +// +session_set_save_handler( + "sess_open", + "sess_close", + "sess_read", + "sess_write", + "sess_destroy", + "sess_gc"); +?> diff --git a/libglue/session2.php b/libglue/session2.php new file mode 100644 index 00000000..171dc1ca --- /dev/null +++ b/libglue/session2.php @@ -0,0 +1,346 @@ +<?php + require_once('libdb.php'); + +function libglue_sess_db($dbtype = 'local') +{ + if($dbtype === 'sso') + { + $dbh = libglue_param(libglue_param('sso_dbh_name')); + if(is_resource($dbh)) return $dbh; + $dbh_name = libglue_param('sso_dbh_name'); + $host = libglue_param('sso_host'); + $db = libglue_param('sso_db'); + $user = libglue_param('sso_username'); + $pass = libglue_param('sso_pass'); + $name = libglue_param('sso_dbh_name'); + } + elseif($dbtype === 'local') + { + $dbh = libglue_param(libglue_param('local_dbh_name')); + if(is_resource($dbh)) return $dbh; + $dbh_name = libglue_param('local_dbh_name'); + $host = libglue_param('local_host'); + $db = libglue_param('local_db'); + $user = libglue_param('local_username'); + $pass = libglue_param('local_pass'); + $name = libglue_param('local_dhb_name'); + } + $dbh = db_connect($host,$user,$pass); + db_select($db); + libglue_param(array($dbh_name=>$dbh)); + + if(is_resource($dbh)) return $dbh; + else die("Could not connect to $dbtype database for session management"); +} + +/* This function is public */ +function check_session($id=null) +{ + if(is_null($id)) + { + //From Karl Vollmer, vollmerk@net.orst.edu: + // naming the session and starting it is sufficient + // to retrieve the cookie + $name = libglue_param('sess_name'); + if(!empty($name)) session_name($name); + session_start(); + $id = strip_tags($_COOKIE[$name]); + } + + // Now what we have a session id, let's verify it: + if(libglue_sso_mode()) + { + // if sso mode, we must have a valid sso session already + $sso_sess = libglue_sso_check($id); + if(!is_null($sso_sess)) + { + // if sso is valid, it's okay to create a new local session + if($local_sess = libglue_local_check($id)) + { + return true; + } + else + { + libglue_local_create($id, + $sso_sess[libglue_param('sso_username_col')], + 'sso', + $sso_sess[libglue_param('sso_expire_col')]); + return true; + } + } + else + // libglue_sso_check failed + { + libglue_sess_destroy($id); + return false; + } + } + else + { + //if not in sso mode, there must be a local session + if($local_sess = libglue_local_check($id)) + { + return true; + } + else + { + //you're gone buddy + libglue_sess_destroy($id); + return false; + } + } +} + +// private function, don't ever use this: +function libglue_sso_mode() +{ + $auth_methods = libglue_param('auth_methods'); + if(!is_array($auth_methods)) $auth_methods = array($auth_methods); + return (in_array('sso',$auth_methods))?true:false; +} + +function libglue_sso_check($sess_id) +{ + // Read the sso info from the config file: + $sso_table = libglue_param('sso_table'); + $sso_sid = libglue_param('sso_sessid_col'); + $sso_expire_col = libglue_param('sso_expire_col'); + $sso_length = libglue_param('sso_length'); + $sso_username_col = libglue_param('sso_username_col'); + + $sso_dbh = libglue_sess_db('sso'); + $sql = "SELECT * FROM $sso_table WHERE $sso_sid='$sess_id' AND $sso_expire_col > UNIX_TIMESTAMP()"; + $db_result = db_query($sql, $sso_dbh); + if(is_resource($db_result)) $sso_session = db_fetch($db_result); + else $sso_session = null; + + $retval = (is_array($sso_session))?$sso_session:null; + return $retval; +} + +function libglue_local_check($sess_id) +{ + static $retval = -1; + if($retval != -1) return $retval; + + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_expirecol = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_typecol = libglue_param('local_typecol'); + + $local_dbh = libglue_sess_db('local'); + $sql = "SELECT $local_datacol FROM $local_table WHERE $local_sid='$sess_id' AND $local_expirecol > UNIX_TIMESTAMP()"; + $db_result = db_query($sql, $local_dbh); + if(is_resource($db_result)) $session = db_fetch($db_result); + else $session = null; + + if(is_array($session)) + { + $retval = $session[$local_datacol]; + } + else $retval = null; + return $retval; +} + +function libglue_local_create($sess_id, $username, $type, $expire) +{ + if($type === "sso" || $type === "ldap") + $userdata = get_ldap_user($username); + else if($type === "mysql") + $userdata = get_mysql_user($username); + + $data = array(libglue_param('user_data_name')=>$userdata); + + // It seems we have to set $_SESSION manually, or it gets blasted + // by php's session write handler + $_SESSION = $data; + $db_data = serialize($data); + $local_dbh = libglue_sess_db('local'); + + // Local parameters we need: + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + $local_usercol = libglue_param('local_usercol'); + $local_datacol = libglue_param('local_datacol'); + $local_expirecol = libglue_param('local_expirecol'); + $local_typecol = libglue_param('local_typecol'); + + // session data will be saved when the script terminates, + // but not the rest of this fancy info + $sql= "INSERT INTO $local_table ". + " ($local_sid,$local_usercol,$local_datacol,$local_expirecol,$local_typecol)". + " VALUES ('$sess_id','$username','$db_data','$expire','$type')"; + $db_result = db_query($sql, $local_dbh); + if(!$db_result) die("Died trying to create local session: <pre><br>$sql</pre>"); +} + +function sess_open() +{ + if(libglue_sso_mode()) + { + if(!is_resource(libglue_sess_db('sso'))) + { + die("<!-- Unable to connect to the SSO server in order to " . + "use the session database. Perhaps the database is not ". + "running, or perhaps the admin needs to change a few variables in ". + "modules/include/global_settings in order to point to the correct ". + "database.-->\n"); + return false; + } + } + + if(!is_resource(libglue_sess_db('local'))) + { + die("<!-- Unable to connect to local server in order to " . + "use the session database. Perhaps the database is not ". + "running, or perhaps the admin needs to change a few variables in ". + "the config file in order to point to the correct ". + "database.-->\n"); + return false; + } + return true; +} + +function sess_close(){ return true; } + +function sess_write($sess_id, $sess_data) +{ + $local_dbh = libglue_sess_db('local'); + $local_datacol = libglue_param('local_datacol'); + $local_table = libglue_param('local_table'); + $local_sid = libglue_param('local_sid'); + + $auth_methods = libglue_param('auth_methods'); + $local_expire = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + + // If not using sso, we now need to update the expire time + $local_expire = libglue_param('local_expirecol'); + $local_length = libglue_param('local_length'); + $time = $local_length+time(); + $sql = "UPDATE $local_table SET $local_datacol='$sess_data',$local_expire='$time'". + " WHERE $local_sid = '$sess_id'"; + db_query($sql, $local_dbh); + + if(libglue_sso_mode()) + { + $sso_table = libglue_param('sso_table'); + $sso_expire_col = libglue_param('sso_expire_col'); + $sso_sess_length = libglue_param('sso_length_col'); + $sso_sess_id = libglue_param('sso_sessid_col'); + $time = time(); + $sql = "UPDATE $sso_table SET $sso_expire_col = $sso_sess_length + UNIX_TIMESTAMP() WHERE $sso_sess_id = '$sess_id'"; + $sso_dbh = libglue_sess_db('sso'); + db_query($sql, $sso_dbh); + } + return true; +} + +// +// This function is called with random frequency +// to remove expired session data +// +function sess_gc($maxlifetime) +{ + if(libglue_sso_mode()) + { + //Delete old sessions from SSO + // We do 'where length' so we don't accidentally blast + // another app's sessions + $sso_expirecol = libglue_param('sso_expire_col'); + $sso_table = libglue_param('sso_table'); + $sso_length = libglue_param('sso_length_col'); + $local_length = libglue_param('local_length'); + + $sso_dbh = libglue_sess_db('sso'); + $time = time(); + $sql = "DELETE FROM $sso_table WHERE $sso_expirecol < $time". + " AND $sso_length = '$local_length'"; + $result = db_query($sql, $sso_dbh); + } + $local_expire = libglue_param('local_expire'); + $local_table = libglue_param('local_table'); + $time = time(); + $local_dbh = libglue_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_expire < $time"; + $result = db_query($sql, $local_dbh); + return true; +} + +function libglue_sess_destroy($id=null) +{ + if(is_null($id)) + { + //From Karl Vollmer, vollmerk@net.orst.edu: + // naming the session and starting it is sufficient + // to retrieve the cookie + $name = libglue_param('sess_name'); + if(!empty($name)) session_name($name); + session_start(); + $id = strip_tags($_COOKIE[$name]); + } + if(libglue_sso_mode()) + { + $sso_sid = libglue_param('sso_sessid_col'); + $sso_table = libglue_param('sso_table'); + $sso_dbh = libglue_sess_db('sso'); + $sql = "DELETE FROM $sso_table WHERE $sso_sid = '$id' LIMIT 1"; + $result = db_query($sql, $sso_dbh); + } + $local_sid = libglue_param('local_sid'); + $local_table = libglue_param('local_table'); + + $local_dbh = libglue_sess_db('local'); + $sql = "DELETE FROM $local_table WHERE $local_sid = '$id' LIMIT 1"; + $result = db_query($sql, $local_dbh); + + // It is very important we destroy our current session cookie, + // because if we don't, a person won't be able to log in again + // without closing their browser - SSO doesn't respect + // + // Code from http://php.oregonstate.edu/manual/en/function.session-destroy.php, + // Written by powerlord@spamless.vgmusic.com, 18-Nov-2002 08:41 + // + $cookie = session_get_cookie_params(); + if ((empty($cookie['domain'])) && (empty($cookie['secure'])) ) + { + setcookie(session_name(), '', time()-3600, $cookie['path']); + } elseif (empty($CookieInfo['secure'])) { + setcookie(session_name(), '', time()-3600, $cookie['path'], $cookie['domain']); + } else { + setcookie(session_name(), '', time()-3600, $cookie['path'], $cookie['domain'], $cookie['secure']); + } + // end powerloard + + unset($_SESSION); + unset($_COOKIE[session_name()]); + + return TRUE; +} + +function logout($id=null) +{ + libglue_sess_destroy($id); + $login_page = libglue_param('login_page'); + header("Location: $login_page"); + die(); + return true; //because why not? +} + + +// +// Register all our cool session handling functions +// +session_set_save_handler( + "sess_open", + "sess_close", + "libglue_local_check", + "sess_write", + "libglue_sess_destroy", + "sess_gc"); + +?> |