Merge branch 'master' of github.com:DAViCal/davical into github
[davical.git] / inc / auth-functions.php
blob870bd26c63a1bf0dfc0d079e03ecdba1e383f64a
1 <?php
2 /**
3 * The authentication handling plugins can be used by the Session class to
4 * provide authentication.
6 * Each authenticate hook needs to:
7 * - Accept a username / password
8 * - Confirm the username / password are correct
9 * - Create (or update) a 'usr' record in our database
10 * - Return the 'usr' record as an object
11 * - Return === false when authentication fails
13 * It can expect that:
14 * - Configuration data will be in $c->authenticate_hook['config'], which might be an array, or whatever is needed.
16 * In order to be called:
17 * - This file should be included
18 * - $c->authenticate_hook['call'] should be set to the name of the plugin
19 * - $c->authenticate_hook['config'] should be set up with any configuration data for the plugin
21 * @package davical
22 * @subpackage authentication
23 * @author Andrew McMillan <andrew@mcmillan.net.nz>
24 * @copyright Catalyst IT Ltd, Morphoss Ltd
25 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
28 require_once("DataUpdate.php");
30 if ( !function_exists('auth_functions_deprecated') ) {
31 function auth_functions_deprecated( $method, $message = null ) {
32 global $c;
33 if ( isset($c->dbg['ALL']) || isset($c->dbg['deprecated']) ) {
34 $stack = debug_backtrace();
35 array_shift($stack);
36 if ( preg_match( '{/inc/auth-functions.php$}', $stack[0]['file'] ) && $stack[0]['line'] > __LINE__ ) return;
37 dbg_error_log("LOG", " auth-functions: Call to deprecated routine '%s'%s", $method, (isset($message)?': '.$message:'') );
38 foreach( $stack AS $k => $v ) {
39 dbg_error_log( 'LOG', ' auth-functions: Deprecated call from line %4d of %s', $v['line'], $v['file']);
46 function getUserByName( $username, $use_cache=true ) {
47 auth_functions_deprecated('getUserByName','replaced by Principal class');
48 return new Principal('username', $username, $use_cache);
51 function getUserByEMail( $email, $use_cache = true ) {
52 auth_functions_deprecated('getUserByEMail','replaced by Principal class');
53 return new Principal('email', $email, $use_cache);
56 function getUserByID( $user_no, $use_cache = true ) {
57 auth_functions_deprecated('getUserByID','replaced by Principal class');
58 return new Principal('user_no', $user_no, $use_cache);
61 function getPrincipalByID( $principal_id, $use_cache = true ) {
62 auth_functions_deprecated('getPrincipalByID','replaced by Principal class');
63 return new Principal('principal_id', $principal_id, $use_cache);
67 /**
68 * Creates some default home collections for the user.
69 * @param string $username The username of the user we are creating relationships for.
71 function CreateHomeCollections( $username, $defult_timezone = null ) {
72 global $session, $c;
74 if ( !isset($c->default_collections) )
76 $c->default_collections = array();
78 if( !empty($c->home_calendar_name) )
79 $c->default_collections[] = array( 'type' => 'calendar', 'name' => $c->home_calendar_name );
80 if( !empty($c->home_addressbook_name) )
81 $c->default_collections[] = array( 'type' => 'addressbook', 'name' => $c->home_addressbook_name );
84 if ( !is_array($c->default_collections) || !count($c->default_collections) ) return true;
86 $principal = new Principal('username',$username);
88 $user_fullname = $principal->fullname; // user fullname
89 $user_rfullname = implode(' ', array_reverse(explode(' ', $principal->fullname))); // user fullname in reverse order
91 $sql = 'INSERT INTO collection (user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, is_addressbook, default_privileges, created, modified, resourcetypes) ';
92 $sql .= 'VALUES( :user_no, :parent_container, :collection_path, :dav_etag, :displayname, :is_calendar, :is_addressbook, :privileges::BIT(24), current_timestamp, current_timestamp, :resourcetypes );';
94 foreach( $c->default_collections as $v ) {
95 if ( $v['type'] == 'calendar' || $v['type']=='addressbook' ) {
96 if ( !empty($v['name']) ) {
97 $qry = new AwlQuery( 'SELECT 1 FROM collection WHERE dav_name = :dav_name', array( ':dav_name' => $principal->dav_name().$v['name'].'/') );
98 if ( !$qry->Exec() ) {
99 $c->messages[] = i18n('There was an error reading from the database.');
100 return false;
102 if ( $qry->rows() > 0 ) {
103 $c->messages[] = i18n('Home '.( $v['type']=='calendar' ? 'calendar' : 'addressbook' ).' already exists.');
104 return true;
106 else {
107 $params[':user_no'] = $principal->user_no();
108 $params[':parent_container'] = $principal->dav_name();
109 $params[':dav_etag'] = '-1';
110 $params[':collection_path'] = $principal->dav_name().$v['name'].'/';
111 $params[':displayname'] = ( !isset($v['displayname']) || empty($v['displayname']) ? $user_fullname.( $v['type']=='calendar' ? ' calendar' : ' addressbook' ) : str_replace(array('%fn', '%rfn'), array($user_fullname, $user_rfullname), $v['displayname']) );
112 $params[':resourcetypes'] = ( $v['type']=='calendar' ? '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>' : '<DAV::collection/><urn:ietf:params:xml:ns:carddav:addressbook/>' );
113 $params[':is_calendar'] = ( $v['type']=='calendar' ? true : false );
114 $params[':is_addressbook'] = ( $v['type']=='addressbook' ? true : false );
115 $params[':privileges'] = ( !isset($v['privileges']) || $v['privileges']===null ? null : privilege_to_bits($v['privileges']) );
117 $qry = new AwlQuery( $sql, $params );
118 if ( $qry->Exec() ) {
119 $c->messages[] = i18n('Home '.( $v['type']=='calendar' ? 'calendar' : 'addressbook' ).' added.');
120 dbg_error_log("User",":Write: Created user's home ".( $v['type']=='calendar' ? 'calendar' : 'addressbook' )." at '%s'", $params[':collection_path'] );
122 // create value for urn:ietf:params:xml:ns:caldav:supported-calendar-component-set property
123 if($v['type'] == 'calendar' && isset($v['calendar_components']) && $v['calendar_components'] != null && is_array($v['calendar_components']) && count($v['calendar_components'])) {
124 // convert the array to uppercase and allow only real calendar compontents
125 $components_clean=array_intersect(array_map("strtoupper", $v['calendar_components']), array('VEVENT', 'VTODO', 'VJOURNAL', 'VTIMEZONE', 'VFREEBUSY', 'VPOLL', 'VAVAILABILITY'));
127 // convert the $components_clean array to XML string
128 $result_xml='';
129 foreach($components_clean as $curr)
130 $result_xml.=sprintf('<comp name="%s" xmlns="urn:ietf:params:xml:ns:caldav"/>', $curr);
132 // handle the components XML string as user defined property (see below)
133 if($result_xml!='')
134 $v['default_properties']['urn:ietf:params:xml:ns:caldav:supported-calendar-component-set']=$result_xml;
137 // store all user defined properties (note: it also handles 'calendar_components' - see above)
138 if(isset($v['default_properties']) && $v['default_properties'] != null && is_array($v['default_properties']) && count($v['default_properties'])) {
139 $sql2='INSERT INTO property (dav_name, property_name, property_value, changed_on, changed_by) ';
140 $sql2.='VALUES (:collection_path, :property_name, :property_value, current_timestamp, :user_no);';
141 $params2[':user_no'] = $principal->user_no();
142 $params2[':collection_path'] = $principal->dav_name().$v['name'].'/';
144 foreach( $v['default_properties'] AS $key => $val ) {
145 $params2[':property_name'] = $key;
146 $params2[':property_value'] = $val;
148 $qry2 = new AwlQuery( $sql2, $params2 );
149 if ( $qry2->Exec() ) {
150 dbg_error_log("User",":Write: Created property '%s' for ".( $v['type']=='calendar' ? 'calendar' : 'addressbook' )." at '%s'", $params2[':property_name'], $params2[':collection_path'] );
152 else {
153 $c->messages[] = i18n("There was an error writing to the database.");
154 return false;
159 else {
160 $c->messages[] = i18n("There was an error writing to the database.");
161 return false;
167 return true;
171 * Backward compatibility
172 * @param unknown_type $username
174 function CreateHomeCalendar($username) {
175 auth_functions_deprecated('CreateHomeCalendar','renamed to CreateHomeCollections');
176 return CreateHomeCollections($username);
180 * Defunct function for creating default relationships.
181 * @param string $username The username of the user we are creating relationships for.
183 function CreateDefaultRelationships( $username ) {
184 global $c;
185 if(! isset($c->default_relationships) || count($c->default_relationships) == 0) return true;
187 $changes = false;
188 foreach($c->default_relationships as $group => $relationships)
190 $sql = 'INSERT INTO grants (by_principal, to_principal, privileges) VALUES(:by_principal, :to_principal, :privileges::INT::BIT(24))';
191 $params = array(
192 ':by_principal' => getUserByName($username)->principal_id,
193 ':to_principal' => $group,
194 ':privileges' => privilege_to_bits($relationships)
196 $qry = new AwlQuery($sql, $params);
198 if ( $qry->Exec() ) {
199 $changes = true;
200 dbg_error_log("User",":Write: Created user's default relationship by:'%s', to:'%s', privileges:'%s'",$params[':by_principal'],$params[':to_principal'],$params[':privileges']);
202 else {
203 $c->messages[] = i18n("There was an error writing to the database.");
204 return false;
208 if($changes)
209 $c->messages[] = i18n("Default relationships added.");
211 return true;
215 function UpdateCollectionTimezones( $username, $new_timezone=null ) {
216 if ( empty($new_timezone) ) return;
217 $qry = new AwlQuery('UPDATE collection SET timezone=? WHERE dav_name LIKE ? AND is_calendar', '/'.$username.'/%', $new_timezone);
218 $qry->Exec();
222 * Update the local cache of the remote user details
223 * @param object $usr The user details we read from the remote.
225 function UpdateUserFromExternal( &$usr ) {
226 global $c;
228 auth_functions_deprecated('UpdateUserFromExternal','refactor to use the "Principal" class');
230 * When we're doing the create we will usually need to generate a user number
232 if ( !isset($usr->user_no) || intval($usr->user_no) == 0 ) {
233 $qry = new AwlQuery( "SELECT nextval('usr_user_no_seq');" );
234 $qry->Exec('Login',__LINE__,__FILE__);
235 $sequence_value = $qry->Fetch(true); // Fetch as an array
236 $usr->user_no = $sequence_value[0];
239 $qry = new AwlQuery('SELECT * FROM usr WHERE user_no = :user_no', array(':user_no' => $usr->user_no) );
240 if ( $qry->Exec('Login',__LINE__,__FILE__) && $qry->rows() == 1 ) {
241 $type = "UPDATE";
242 if ( $old = $qry->Fetch() ) {
243 $changes = false;
244 foreach( $usr AS $k => $v ) {
245 if ( $old->{$k} != $v ) {
246 $changes = true;
247 dbg_error_log("Login","User '%s' field '%s' changed from '%s' to '%s'", $usr->username, $k, $old->{$k}, $v );
248 break;
251 if ( !$changes ) {
252 dbg_error_log("Login","No changes to user record for '%s' - leaving as-is.", $usr->username );
253 if ( isset($usr->active) && $usr->active == 'f' ) return false;
254 return; // Normal case, if there are no changes
256 else {
257 dbg_error_log("Login","Changes to user record for '%s' - updating.", $usr->username );
261 else
262 $type = "INSERT";
264 $params = array();
265 if ( $type != 'INSERT' ) $params[':user_no'] = $usr->user_no;
266 $qry = new AwlQuery( sql_from_object( $usr, $type, 'usr', 'WHERE user_no= :user_no' ), $params );
267 $qry->Exec('Login',__LINE__,__FILE__);
270 * We disallow login by inactive users _after_ we have updated the local copy
272 if ( isset($usr->active) && ($usr->active === 'f' || $usr->active === false) ) return false;
274 if ( $type == 'INSERT' ) {
275 $qry = new AwlQuery( 'INSERT INTO principal( type_id, user_no, displayname, default_privileges) SELECT 1, user_no, fullname, :privs::INT::BIT(24) FROM usr WHERE username=(text(:username))',
276 array( ':privs' => privilege_to_bits($c->default_privileges), ':username' => $usr->username) );
277 $qry->Exec('Login',__LINE__,__FILE__);
278 CreateHomeCalendar($usr->username);
279 CreateDefaultRelationships($usr->username);
281 else if ( $usr->fullname != $old->{'fullname'} ) {
282 // Also update the displayname if the fullname has been updated.
283 $qry->QDo( 'UPDATE principal SET displayname=:new_display WHERE user_no=:user_no',
284 array(':new_display' => $usr->fullname, ':user_no' => $usr->user_no)
291 * Authenticate against a different PostgreSQL database which contains a usr table in
292 * the AWL format.
294 * Use this as in the following example config snippet:
296 * require_once('auth-functions.php');
297 * $c->authenticate_hook = array(
298 * 'call' => 'AuthExternalAwl',
299 * 'config' => array(
300 * // A PgSQL database connection string for the database containing user records
301 * 'connection[]' => 'dbname=wrms host=otherhost port=5433 user=general',
302 * // Which columns should be fetched from the database
303 * 'columns' => "user_no, active, email_ok, joined, last_update AS updated, last_used, username, password, fullname, email",
304 * // a WHERE clause to limit the records returned.
305 * 'where' => "active AND org_code=7"
307 * );
310 function AuthExternalAWL( $username, $password ) {
311 global $c;
313 $persistent = isset($c->authenticate_hook['config']['use_persistent']) && $c->authenticate_hook['config']['use_persistent'];
315 if ( isset($c->authenticate_hook['config']['columns']) )
316 $cols = $c->authenticate_hook['config']['columns'];
317 else
318 $cols = '*';
320 if ( isset($c->authenticate_hook['config']['where']) )
321 $andwhere = ' AND '.$c->authenticate_hook['config']['where'];
322 else
323 $andwhere = '';
325 $qry = new AwlQuery('SELECT '.$cols.' FROM usr WHERE lower(username) = :username '. $andwhere, array( ':username' => strtolower($username) ));
326 $authconn = $qry->SetConnection($c->authenticate_hook['config']['connection'], ($persistent ? array(PDO::ATTR_PERSISTENT => true) : null));
327 if ( ! $authconn ) {
328 echo <<<EOERRMSG
329 <html><head><title>Database Connection Failure</title></head><body>
330 <h1>Database Error</h1>
331 <h3>Could not connect to PostgreSQL database</h3>
332 </body>
333 </html>
334 EOERRMSG;
335 @ob_flush(); exit(1);
338 if ( $qry->Exec('Login',__LINE__,__FILE__) && $qry->rows() == 1 ) {
339 $usr = $qry->Fetch();
340 if ( session_validate_password( $password, $usr->password ) ) {
341 $principal = new Principal('username',$username);
342 if ( $principal->Exists() ) {
343 if ( $principal->modified <= $usr->updated )
344 $principal->Update($usr);
346 else {
347 $principal->Create($usr);
348 CreateHomeCollections($username);
352 * We disallow login by inactive users _after_ we have updated the local copy
354 if ( isset($usr->active) && $usr->active == 'f' ) return false;
356 return $principal;
360 return false;