DAViCal
auth-functions.php
1<?php
28require_once("DataUpdate.php");
29
30if ( !function_exists('auth_functions_deprecated') ) {
34 function auth_functions_deprecated( $method, $message = null ) {
35 $stack = debug_backtrace();
36 array_shift($stack);
37 dbg_error_log("ERROR", " auth-functions: Call to deprecated routine '%s'%s", $method, (isset($message)?': '.$message:'') );
38 foreach( $stack AS $k => $v ) {
39 dbg_error_log( 'ERROR', ' auth-functions: Deprecated call from line %4d of %s', $v['line'], $v['file']);
40 }
41 }
42}
43
47function getUserByName( $username, $use_cache=true ) {
48 auth_functions_deprecated('getUserByName','replaced by Principal class');
49 return new Principal('username', $username, $use_cache);
50}
51
55function getUserByEMail( $email, $use_cache = true ) {
56 auth_functions_deprecated('getUserByEMail','replaced by Principal class');
57 return new Principal('email', $email, $use_cache);
58}
59
63function getUserByID( $user_no, $use_cache = true ) {
64 auth_functions_deprecated('getUserByID','replaced by Principal class');
65 return new Principal('user_no', $user_no, $use_cache);
66}
67
71function getPrincipalByID( $principal_id, $use_cache = true ) {
72 auth_functions_deprecated('getPrincipalByID','replaced by Principal class');
73 return new Principal('principal_id', $principal_id, $use_cache);
74}
75
76
81function CreateHomeCollections( $username, $default_timezone = null ) {
82 global $session, $c;
83
84 if ( !isset($c->default_collections) )
85 {
86 $c->default_collections = array();
87
88 if( !empty($c->home_calendar_name) )
89 $c->default_collections[] = array(
90 'type' => 'calendar',
91 'name' => $c->home_calendar_name
92 );
93 if( !empty($c->home_out_calendar_name) )
94 $c->default_collections[] = array(
95 'type' => 'calendar',
96 'name' => $c->home_out_calendar_name,
97 'displayname_suffix' => ' Outbox'
98 );
99 if( !empty($c->home_in_calendar_name) )
100 $c->default_collections[] = array(
101 'type' => 'calendar',
102 'name' => $c->home_in_calendar_name,
103 'displayname_suffix' => ' Inbox'
104 );
105 if( !empty($c->home_addressbook_name) )
106 $c->default_collections[] = array(
107 'type' => 'addressbook',
108 'name' => $c->home_addressbook_name
109 );
110 }
111
112 if ( !is_array($c->default_collections) || !count($c->default_collections) ) return true;
113
114 $principal = new Principal('username',$username);
115
116 $user_fullname = $principal->fullname; // user fullname
117 $user_rfullname = implode(' ', array_reverse(explode(' ', $principal->fullname))); // user fullname in reverse order
118
119 $sql = 'INSERT INTO collection (user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, is_addressbook, default_privileges, created, modified, resourcetypes) ';
120 $sql .= 'VALUES( :user_no, :parent_container, :collection_path, :dav_etag, :displayname, :is_calendar, :is_addressbook, :privileges::BIT(24), current_timestamp, current_timestamp, :resourcetypes );';
121
122 foreach( $c->default_collections as $v ) {
123 if ( $v['type'] == 'calendar' || $v['type']=='addressbook' ) {
124 if ( !empty($v['name']) ) {
125 $qry = new AwlQuery( 'SELECT 1 FROM collection WHERE dav_name = :dav_name', array( ':dav_name' => $principal->dav_name().$v['name'].'/') );
126 if ( !$qry->Exec() ) {
127 $c->messages[] = i18n('There was an error reading from the database.');
128 return false;
129 }
130 if ( $qry->rows() > 0 ) {
131 $c->messages[] = i18n('Home '.( $v['type']=='calendar' ? 'calendar' : 'addressbook' ).' already exists.');
132 return true;
133 }
134 else {
135 $params[':user_no'] = $principal->user_no();
136 $params[':parent_container'] = $principal->dav_name();
137 $params[':dav_etag'] = '-1';
138 $params[':collection_path'] = $principal->dav_name().$v['name'].'/';
139 if ( isset($v['displayname']) && ! empty($v['displayname']) ) {
140 $params[':displayname'] = str_replace(array('%fn', '%rfn'), array($user_fullname, $user_rfullname), $v['displayname']);
141 } elseif ( isset($v['displayname_suffix']) && ! empty($v['displayname_suffix']) ) {
142 $params[':displayname'] = $user_fullname . $v['displayname_suffix'];
143 } else {
144 $params[':displayname'] = $user_fullname . ($v['type']=='calendar' ? ' calendar' : ' addressbook');
145 }
146 $params[':resourcetypes'] = ( $v['type']=='calendar' ? '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>' : '<DAV::collection/><urn:ietf:params:xml:ns:carddav:addressbook/>' );
147 $params[':is_calendar'] = ( $v['type']=='calendar' ? true : false );
148 $params[':is_addressbook'] = ( $v['type']=='addressbook' ? true : false );
149 $params[':privileges'] = ( !isset($v['privileges']) || $v['privileges']===null ? null : privilege_to_bits($v['privileges']) );
150
151 $qry = new AwlQuery( $sql, $params );
152 if ( $qry->Exec() ) {
153 $c->messages[] = i18n('Home '.( $v['type']=='calendar' ? 'calendar' : 'addressbook' ).' added.') . " " . $v['name'];
154 dbg_error_log("User",":Write: Created user's home ".( $v['type']=='calendar' ? 'calendar' : 'addressbook' )." at '%s'", $params[':collection_path'] );
155
156 // create value for urn:ietf:params:xml:ns:caldav:supported-calendar-component-set property
157 if($v['type'] == 'calendar' && isset($v['calendar_components']) && $v['calendar_components'] != null && is_array($v['calendar_components']) && count($v['calendar_components'])) {
158 // convert the array to uppercase and allow only real calendar compontents
159 $components_clean=array_intersect(array_map("strtoupper", $v['calendar_components']), array('VEVENT', 'VTODO', 'VJOURNAL', 'VTIMEZONE', 'VFREEBUSY', 'VPOLL', 'VAVAILABILITY'));
160
161 // convert the $components_clean array to XML string
162 $result_xml='';
163 foreach($components_clean as $curr)
164 $result_xml.=sprintf('<comp name="%s" xmlns="urn:ietf:params:xml:ns:caldav"/>', $curr);
165
166 // handle the components XML string as user defined property (see below)
167 if($result_xml!='')
168 $v['default_properties']['urn:ietf:params:xml:ns:caldav:supported-calendar-component-set']=$result_xml;
169 }
170
171 // store all user defined properties (note: it also handles 'calendar_components' - see above)
172 if(isset($v['default_properties']) && $v['default_properties'] != null && is_array($v['default_properties']) && count($v['default_properties'])) {
173 $sql2='INSERT INTO property (dav_name, property_name, property_value, changed_on, changed_by) ';
174 $sql2.='VALUES (:collection_path, :property_name, :property_value, current_timestamp, :user_no);';
175 $params2[':user_no'] = $principal->user_no();
176 $params2[':collection_path'] = $principal->dav_name().$v['name'].'/';
177
178 foreach( $v['default_properties'] AS $key => $val ) {
179 $params2[':property_name'] = $key;
180 $params2[':property_value'] = $val;
181
182 $qry2 = new AwlQuery( $sql2, $params2 );
183 if ( $qry2->Exec() ) {
184 dbg_error_log("User",":Write: Created property '%s' for ".( $v['type']=='calendar' ? 'calendar' : 'addressbook' )." at '%s'", $params2[':property_name'], $params2[':collection_path'] );
185 }
186 else {
187 $c->messages[] = i18n("There was an error writing to the database.");
188 return false;
189 }
190 }
191 }
192 }
193 else {
194 $c->messages[] = i18n("There was an error writing to the database.");
195 return false;
196 }
197 }
198 }
199 }
200 }
201 return true;
202}
203
208function CreateHomeCalendar($username) {
209 auth_functions_deprecated('CreateHomeCalendar','renamed to CreateHomeCollections');
210 return CreateHomeCollections($username);
211}
212
217function CreateDefaultRelationships( $username ) {
218 global $c;
219 if(! isset($c->default_relationships) || count($c->default_relationships) == 0) return true;
220
221 $changes = false;
222 $principal = new Principal('username', $username, true);
223 foreach($c->default_relationships as $group => $relationships)
224 {
225 $sql = 'INSERT INTO grants (by_principal, to_principal, privileges) VALUES(:by_principal, :to_principal, :privileges::INT::BIT(24))';
226 $params = array(
227 ':by_principal' => $principal->principal_id,
228 ':to_principal' => $group,
229 ':privileges' => privilege_to_bits($relationships)
230 );
231 $qry = new AwlQuery($sql, $params);
232
233 if ( $qry->Exec() ) {
234 $changes = true;
235 dbg_error_log("User",":Write: Created user's default relationship by:'%s', to:'%s', privileges:'%s'",$params[':by_principal'],$params[':to_principal'],$params[':privileges']);
236 }
237 else {
238 $c->messages[] = i18n("There was an error writing to the database.");
239 return false;
240 }
241 }
242
243 if($changes)
244 $c->messages[] = i18n("Default relationships added.");
245
246 return true;
247}
248
254function UpdateCollectionTimezones( $username, $new_timezone=null ) {
255 if ( empty($new_timezone) ) return;
256 $qry = new AwlQuery('UPDATE collection SET timezone=? WHERE dav_name LIKE ? AND is_calendar', '/'.$username.'/%', $new_timezone);
257 $qry->Exec();
258
259 require_once("instance_range.php");
260 update_instance_ranges($dav_resource->dav_name());
261}
262
267function UpdateUserFromExternal( &$usr ) {
268 global $c;
269
270 auth_functions_deprecated('UpdateUserFromExternal','refactor to use the "Principal" class');
274 if ( !isset($usr->user_no) || intval($usr->user_no) == 0 ) {
275 $qry = new AwlQuery( "SELECT nextval('usr_user_no_seq');" );
276 $qry->Exec('Login',__LINE__,__FILE__);
277 $sequence_value = $qry->Fetch(true); // Fetch as an array
278 $usr->user_no = $sequence_value[0];
279 }
280
281 $qry = new AwlQuery('SELECT * FROM usr WHERE user_no = :user_no', array(':user_no' => $usr->user_no) );
282 if ( $qry->Exec('Login',__LINE__,__FILE__) && $qry->rows() == 1 ) {
283 $type = "UPDATE";
284 if ( $old = $qry->Fetch() ) {
285 $changes = false;
286 foreach( $usr AS $k => $v ) {
287 if ( $old->{$k} != $v ) {
288 $changes = true;
289 dbg_error_log("Login","User '%s' field '%s' changed from '%s' to '%s'", $usr->username, $k, $old->{$k}, $v );
290 break;
291 }
292 }
293 if ( !$changes ) {
294 dbg_error_log("Login","No changes to user record for '%s' - leaving as-is.", $usr->username );
295 if ( isset($usr->active) && $usr->active == 'f' ) return false;
296 return; // Normal case, if there are no changes
297 }
298 else {
299 dbg_error_log("Login","Changes to user record for '%s' - updating.", $usr->username );
300 }
301 }
302 }
303 else
304 $type = "INSERT";
305
306 $params = array();
307 if ( $type != 'INSERT' ) $params[':user_no'] = $usr->user_no;
308 $qry = new AwlQuery( sql_from_object( $usr, $type, 'usr', 'WHERE user_no= :user_no' ), $params );
309 $qry->Exec('Login',__LINE__,__FILE__);
310
314 if ( isset($usr->active) && ($usr->active === 'f' || $usr->active === false) ) return false;
315
316 if ( $type == 'INSERT' ) {
317 $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))',
318 array( ':privs' => privilege_to_bits($c->default_privileges), ':username' => $usr->username) );
319 $qry->Exec('Login',__LINE__,__FILE__);
320 CreateHomeCalendar($usr->username);
321 CreateDefaultRelationships($usr->username);
322 }
323 else if ( $usr->fullname != $old->{'fullname'} ) {
324 // Also update the displayname if the fullname has been updated.
325 $qry->QDo( 'UPDATE principal SET displayname=:new_display WHERE user_no=:user_no',
326 array(':new_display' => $usr->fullname, ':user_no' => $usr->user_no)
327 );
328 }
329}
330
331
352function AuthExternalAWL( $username, $password ) {
353 global $c;
354
355 $persistent = isset($c->authenticate_hook['config']['use_persistent']) && $c->authenticate_hook['config']['use_persistent'];
356
357 if ( isset($c->authenticate_hook['config']['columns']) )
358 $cols = $c->authenticate_hook['config']['columns'];
359 else
360 $cols = '*';
361
362 if ( isset($c->authenticate_hook['config']['where']) )
363 $andwhere = ' AND '.$c->authenticate_hook['config']['where'];
364 else
365 $andwhere = '';
366
367 $qry = new AwlQuery('SELECT '.$cols.' FROM usr WHERE lower(username) = :username '. $andwhere, array( ':username' => strtolower($username) ));
368 $authconn = $qry->SetConnection($c->authenticate_hook['config']['connection'], ($persistent ? array(PDO::ATTR_PERSISTENT => true) : null));
369 if ( ! $authconn ) {
370 echo <<<EOERRMSG
371 <html><head><title>Database Connection Failure</title></head><body>
372 <h1>Database Error</h1>
373 <h3>Could not connect to PostgreSQL database</h3>
374 </body>
375 </html>
376EOERRMSG;
377 @ob_flush(); exit(1);
378 }
379
380 if ( $qry->Exec('Login',__LINE__,__FILE__) && $qry->rows() == 1 ) {
381 $usr = $qry->Fetch();
382 if ( session_validate_password( $password, $usr->password ) ) {
383 $principal = new Principal('username',$username);
384 if ( $principal->Exists() ) {
385 if ( $principal->modified <= $usr->updated )
386 $principal->Update($usr);
387 }
388 else {
389 $principal->Create($usr);
390 CreateHomeCollections($username);
391 CreateDefaultRelationships($username);
392 }
393
397 if ( isset($usr->active) && $usr->active == 'f' ) return false;
398
399 return $principal;
400 }
401 }
402
403 return false;
404
405}