We need the DAVPrincipal module here in some situations.
[davical.git] / inc / DAVPrincipal.php
blobf8dae8b7a6292892edfd0aed3f8be19a3c28c634
1 <?php
2 /**
3 * An object representing a DAV 'Principal'
5 * @package davical
6 * @subpackage Principal
7 * @author Andrew McMillan <andrew@mcmillan.net.nz>
8 * @copyright Catalyst .Net Ltd, Morphoss Ltd <http://www.morhposs.com/>
9 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
13 /**
14 * A class for things to do with a DAV Principal
16 * @package davical
18 class DAVPrincipal extends Principal
21 /**
22 * @var RFC4791: Identifies the URL(s) of any WebDAV collections that contain
23 * calendar collections owned by the associated principal resource.
25 private $calendar_home_set;
27 /**
28 * @var CardDAV: Identifies the URL(s) of any WebDAV collections that contain
29 * addressbook collections owned by the associated principal resource.
31 private $addressbook_home_set;
33 /**
34 * @var Obsolete: Identifies the URL(s) of any calendars participating in free/busy
36 private $calendar_free_busy_set;
38 /**
39 * @var RFC3744: The principals that are direct members of this group.
41 protected $_is_group;
43 /**
44 * @var RFC3744: The principals that are direct members of this group.
46 private $group_member_set;
48 /**
49 * @var RFC3744: The groups in which the principal is directly a member.
51 private $group_membership;
53 /**
54 * @var caldav-cu-proxy-02: The principals which this one has read permissions on.
56 private $read_proxy_for;
58 /**
59 * @var caldav-cu-proxy-02: The principals which this one has read-write prmissions for.
61 private $write_proxy_for;
63 /**
64 * @var caldav-cu-proxy-02: The principals which have read permissions on this one.
66 private $read_proxy_group;
68 /**
69 * @var caldav-cu-proxy-02: The principals which have write permissions on this one.
71 private $write_proxy_group;
73 /**
74 * @var CardDAV: The URL to an addressbook entry for this principal
76 private $principal_address;
78 /**
79 * A unique tag which will change if this principal changes
80 * @var string
82 private $unique_tag;
84 /**
85 * Constructor
86 * @param mixed $parameters If null, an empty Principal is created. If it
87 * is an integer then that ID is read (if possible). If it is
88 * an array then the Principal matching the supplied elements
89 * is read. If it is an object then it is expected to be a 'usr'
90 * record that was read elsewhere.
92 * @return boolean Whether we actually read data from the DB to initialise the record.
94 function __construct( $parameters = null ) {
95 global $session, $c;
97 $this->exists = null;
99 if ( $parameters == null ) return;
101 if ( is_object($parameters) ) {
102 dbg_error_log( 'principal', 'Principal: record for %s', $parameters->username );
103 parent::__construct('username',$parameters->username);
105 else if ( is_int($parameters) ) {
106 dbg_error_log( 'principal', 'Principal: %d', $parameters );
107 parent::__construct('principal_id',$parameters);
109 else if ( is_array($parameters) ) {
110 if ( ! isset($parameters['options']['allow_by_email']) ) $parameters['options']['allow_by_email'] = false;
111 if ( isset($parameters['username']) ) {
112 parent::__construct('username',$parameters['username']);
114 else if ( isset($parameters['user_no']) ) {
115 parent::__construct('user_no',$parameters['user_no']);
117 else if ( isset($parameters['principal_id']) ) {
118 parent::__construct('principal_id',$parameters['principal_id']);
120 else if ( isset($parameters['email']) ) {
121 parent::__construct('email',$parameters['email']);
123 else if ( isset($parameters['path']) ) {
124 parent::__construct('path',$parameters['path']);
126 else if ( isset($parameters['principal-property-search']) ) {
127 $username = $this->PropertySearch($parameters['principal-property-search']);
128 parent::__construct('username',$username);
132 if ( ! $this->exists ) return;
134 $this->InitialiseRecord();
140 * Initialise the Principal object from a $usr record from the DB.
141 * @param object $usr The usr record from the DB.
143 function InitialiseRecord() {
144 global $c;
146 $this->unique_tag = '"'.md5($this->username . $this->modified).'"';
147 $this->_is_group = (isset($this->type_id) && $this->type_id == 3);
149 $this->principal_address = $this->url . 'principal.vcf';
151 $this->user_address_set = array(
152 'mailto:'.$this->email,
153 $this->url,
154 // ConstructURL( '/~'.$this->username.'/', true ),
155 // ConstructURL( '/__uuids__/'.$this->username.'/', true ),
158 if ( isset ( $c->notifications_server ) ) {
159 $this->xmpp_uri = 'xmpp:pubsub.'.$c->notifications_server['host'].'?pubsub;node=/davical-'.$this->principal_id;
160 $this->xmpp_server = $c->notifications_server['host'];
163 if ( $this->_is_group ) {
164 $this->group_member_set = array();
165 $qry = new AwlQuery('SELECT usr.username FROM group_member JOIN principal ON (principal_id=member_id) JOIN usr USING(user_no) WHERE group_id = :group_id ORDER BY principal.principal_id ', array( ':group_id' => $this->principal_id) );
166 if ( $qry->Exec('DAVPrincipal') && $qry->rows() > 0 ) {
167 while( $member = $qry->Fetch() ) {
168 $this->group_member_set[] = ConstructURL( '/'. $member->username . '/', true);
173 $this->group_membership = array();
174 $qry = new AwlQuery('SELECT usr.username FROM group_member JOIN principal ON (principal_id=group_id) JOIN usr USING(user_no) WHERE member_id = :member_id UNION SELECT usr.username FROM group_member LEFT JOIN grants ON (to_principal=group_id) JOIN principal ON (principal_id=by_principal) JOIN usr USING(user_no) WHERE member_id = :member_id and by_principal != member_id ORDER BY 1', array( ':member_id' => $this->principal_id ) );
175 if ( $qry->Exec('DAVPrincipal') && $qry->rows() > 0 ) {
176 while( $group = $qry->Fetch() ) {
177 $this->group_membership[] = ConstructURL( '/'. $group->username . '/', true);
181 $this->read_proxy_group = null;
182 $this->write_proxy_group = null;
183 $this->write_proxy_for = null;
184 $this->read_proxy_for = null;
186 dbg_error_log( 'principal', ' User: %s (%d) URL: %s, By Email: %d', $this->username, $this->user_no, $this->url, $this->by_email );
191 * Split this out so we do it as infrequently as possible, given the cost.
193 function FetchProxyGroups() {
194 global $c;
196 $this->read_proxy_group = array();
197 $this->write_proxy_group = array();
198 $this->write_proxy_for = array();
199 $this->read_proxy_for = array();
201 if ( !isset($c->disable_caldav_proxy) || $c->disable_caldav_proxy === false ) {
203 $write_priv = privilege_to_bits(array('write'));
204 // whom are we a proxy for? who is a proxy for us?
205 // (as per Caldav Proxy section 5.1 Paragraph 7 and 5)
206 $sql = 'SELECT principal_id, username, pprivs(:request_principal::int8,principal_id,:scan_depth::int) FROM principal JOIN usr USING(user_no) WHERE principal_id IN (SELECT * from p_has_proxy_access_to(:request_principal,:scan_depth))';
207 $params = array( ':request_principal' => $this->principal_id, ':scan_depth' => $c->permission_scan_depth );
208 $qry = new AwlQuery($sql, $params);
209 if ( $qry->Exec('DAVPrincipal') && $qry->rows() > 0 ) {
210 while( $relationship = $qry->Fetch() ) {
211 if ( (bindec($relationship->pprivs) & $write_priv) != 0 ) {
212 $this->write_proxy_for[] = ConstructURL( '/'. $relationship->username . '/', true);
213 $this->group_membership[] = ConstructURL( '/'. $relationship->username . '/calendar-proxy-write/', true);
215 else {
216 $this->read_proxy_for[] = ConstructURL( '/'. $relationship->username . '/', true);
217 $this->group_membership[] = ConstructURL( '/'. $relationship->username . '/calendar-proxy-read/', true);
222 $sql = 'SELECT principal_id, username, pprivs(:request_principal::int8,principal_id,:scan_depth::int) FROM principal JOIN usr USING(user_no) WHERE principal_id IN (SELECT * from grants_proxy_access_from_p(:request_principal,:scan_depth))';
223 $qry = new AwlQuery($sql, $params ); // reuse $params assigned for earlier query
224 if ( $qry->Exec('DAVPrincipal') && $qry->rows() > 0 ) {
225 while( $relationship = $qry->Fetch() ) {
226 if ( bindec($relationship->pprivs) & $write_priv ) {
227 $this->write_proxy_group[] = ConstructURL( '/'. $relationship->username . '/', true);
229 else {
230 $this->read_proxy_group[] = ConstructURL( '/'. $relationship->username . '/', true);
234 // @dbg_error_log( 'principal', 'Read-proxy-for: %s', implode(',',$this->read_proxy_for) );
235 // @dbg_error_log( 'principal', 'Write-proxy-for: %s', implode(',',$this->write_proxy_for) );
236 // @dbg_error_log( 'principal', 'Read-proxy-group: %s', implode(',',$this->read_proxy_group) );
237 // @dbg_error_log( 'principal', 'Write-proxy-group: %s', implode(',',$this->write_proxy_group) );
243 * Accessor for the read proxy group
245 function ReadProxyGroup() {
246 if ( !isset($this->read_proxy_group) ) $this->FetchProxyGroups();
247 return $this->read_proxy_group;
252 * Accessor for the write proxy group
254 function WriteProxyGroup() {
255 if ( !isset($this->write_proxy_group) ) $this->FetchProxyGroups();
256 return $this->write_proxy_group;
261 * Accessor for read or write proxy
262 * @param string read/write - which sort of proxy list is requested.
264 function ProxyFor( $type ) {
265 if ( !isset($this->read_proxy_for) ) $this->FetchProxyGroups();
266 if ( $type == 'write' ) return $this->write_proxy_for;
267 return $this->read_proxy_for;
272 * Accessor for the group membership - the groups this principal is a member of
274 function GroupMembership() {
275 if ( !isset($this->read_proxy_group) ) $this->FetchProxyGroups();
276 return $this->group_membership;
281 * Accessor for the group member set - the members of this group
283 function GroupMemberSet() {
284 if ( ! $this->_is_group ) return null;
285 return $this->group_member_set;
290 * Is this a group principal?
291 * @return boolean Whether this is a group principal
293 function IsGroup() {
294 return $this->_is_group;
299 * Return an arbitrary property
300 * @return string The name of the arbitrary property
302 function GetProperty( $property_id ) {
304 switch( $property_id ) {
305 case 'DAV::resource-id':
306 if ( $this->exists && $this->principal_id > 0 )
307 ConstructURL('/.resources/'.$this->principal_id);
308 else
309 return null;
310 break;
313 if ( isset($this->{$property_id}) ) {
314 if ( ! is_object($this->{$property_id}) ) return $this->{$property_id};
315 return clone($this->{$property_id});
317 return null;
321 * Returns the unique_tag (ETag or getctag) for this resource
323 public function unique_tag() {
324 if ( isset($this->unique_tag) ) return $this->unique_tag;
326 if ( $this->exists !== true ) $this->unique_tag = '"-1"';
328 return $this->unique_tag;
333 * Get the calendar_home_set, as lazily as possible
335 function calendar_home_set() {
336 if ( !isset($this->calendar_home_set) ) {
337 $this->calendar_home_set = array();
338 $qry = new AwlQuery('SELECT DISTINCT parent_container FROM collection WHERE is_calendar AND dav_name ~ :dav_name_start',
339 array( ':dav_name_start' => '^'.$this->dav_name));
340 if ( $qry->Exec('principal',__LINE__,__FILE__) ) {
341 if ( $qry->rows() > 0 ) {
342 while( $calendar = $qry->Fetch() ) {
343 $this->calendar_home_set[] = ConstructURL($calendar->parent_container, true);
346 else {
347 $this->calendar_home_set[] = $this->url;
351 return $this->calendar_home_set;
356 * Get the addressbook_home_set, as lazily as possible
358 function addressbook_home_set() {
359 if ( !isset($this->addressbook_home_set) ) {
360 $this->addressbook_home_set = array();
361 $qry = new AwlQuery('SELECT DISTINCT parent_container FROM collection WHERE is_addressbook AND dav_name ~ :dav_name_start',
362 array( ':dav_name_start' => '^'.$this->dav_name));
363 if ( $qry->Exec('principal',__LINE__,__FILE__) ) {
364 if ( $qry->rows() > 0 ) {
365 while( $addressbook = $qry->Fetch() ) {
366 $this->addressbook_home_set[] = ConstructURL($addressbook->parent_container, true);
369 else {
370 $this->addressbook_home_set[] = $this->url;
374 return $this->addressbook_home_set;
379 * Get the calendar_free_busy_set, as lazily as possible
381 function calendar_free_busy_set() {
382 if ( !isset($this->calendar_free_busy_set) ) {
384 * calendar-free-busy-set has been dropped from draft 5 of the scheduling extensions for CalDAV
385 * in favour of ???
387 $this->calendar_free_busy_set = array();
388 $qry = new AwlQuery('SELECT dav_name FROM collection WHERE is_calendar AND (schedule_transp = \'opaque\' OR schedule_transp IS NULL) AND dav_name ~ :dav_name_start ORDER BY user_no, collection_id',
389 array( ':dav_name_start' => '^'.$this->dav_name));
390 if ( $qry->Exec('principal',__LINE__,__FILE__) ) {
391 while( $calendar = $qry->Fetch() ) {
392 $this->calendar_free_busy_set[] = ConstructURL($calendar->dav_name, true);
396 return $this->calendar_free_busy_set;
401 * Return the privileges bits for the current session user to this resource
403 function Privileges() {
404 global $session;
405 if ( !isset($this->privileges) ) $this->privileges = 0;
406 if ( is_string($this->privileges) ) $this->privileges = bindec( $this->privileges );
407 if ( $this->_is_group ) {
408 if ( in_array($session->principal->url(), $this->GroupMemberSet()) ) {
409 $this->privileges |= privilege_to_bits( array('DAV::read', 'DAV::read-current-user-privilege-set') );
412 return $this->privileges;
417 * Returns a representation of the principal as a collection
419 function AsCollection() {
420 $dav_name = (isset($this->original_request_url) ? DeconstructURL($this->original_request_url) : $this->dav_name());
421 $collection = (object) array(
422 'collection_id' => ($this->principal_id() ? $this->principal_id() : 0),
423 'is_calendar' => false,
424 'is_addressbook' => false,
425 'is_principal' => true,
426 'type' => 'principal' . (isset($this->original_request_url) ? '_link' : ''),
427 'user_no' => ($this->user_no() ? $this->user_no() : 0),
428 'username' => $this->username(),
429 'dav_name' => $dav_name,
430 'parent_container' => '/',
431 'email' => ($this->email()? $this->email() : ''),
432 'created' => $this->created,
433 'updated' => $this->modified,
434 'dav_etag' => substr($this->unique_tag(),1,-1),
435 'resourcetypes' => $this->resourcetypes
437 $collection->dav_displayname = (isset($this->dav_displayname) ? $this->dav_displayname : (isset($this->fullname) ? $this->fullname : $collection->username));
439 return $collection;
443 function PropertySearch( $parameters ) {
444 throw new Exception("Unimplemented!");
448 * Returns properties which are specific to this principal
450 function PrincipalProperty( $tag, $prop, &$reply, &$denied ) {
452 dbg_error_log('principal',': RenderAsXML: Principal Property "%s"', $tag );
453 switch( $tag ) {
454 case 'DAV::getcontenttype':
455 $prop->NewElement('getcontenttype', 'httpd/unix-directory' );
456 break;
458 case 'DAV::resourcetype':
459 $prop->NewElement('resourcetype', array( new XMLElement('principal'), new XMLElement('collection')) );
460 break;
462 case 'DAV::displayname':
463 $prop->NewElement('displayname', $this->fullname );
464 break;
466 case 'DAV::principal-URL':
467 $prop->NewElement('principal-URL', $reply->href($this->url()) );
468 break;
470 case 'DAV::getlastmodified':
471 $prop->NewElement('getlastmodified', ISODateToHTTPDate($this->modified) );
472 break;
474 case 'DAV::creationdate':
475 $prop->NewElement('creationdate', DateToISODate($this->created) );
476 break;
478 case 'DAV::getcontentlanguage':
479 /** Use the principal's locale by preference, otherwise system default */
480 $locale = (isset($c->current_locale) ? $c->current_locale : '');
481 if ( isset($this->locale) && $this->locale != '' ) $locale = $this->locale;
482 $prop->NewElement('getcontentlanguage', $locale );
483 break;
485 case 'DAV::group-member-set':
486 if ( ! $this->_is_group ) return false;
487 $prop->NewElement('group-member-set', $reply->href($this->group_member_set) );
488 break;
490 case 'DAV::group-membership':
491 $prop->NewElement('group-membership', $reply->href($this->GroupMembership()) );
492 break;
494 case 'urn:ietf:params:xml:ns:caldav:schedule-inbox-URL':
495 $reply->CalDAVElement($prop, 'schedule-inbox-URL', $reply->href($this->url('schedule-inbox')) );
496 break;
498 case 'urn:ietf:params:xml:ns:caldav:schedule-outbox-URL':
499 $reply->CalDAVElement($prop, 'schedule-outbox-URL', $reply->href($this->url('schedule-outbox')) );
500 break;
502 case 'urn:ietf:params:xml:ns:caldav:schedule-default-calendar-URL':
503 $reply->CalDAVElement($prop, 'schedule-default-calendar-URL', $reply->href($this->url('schedule-default-calendar')) );
504 break;
506 case 'http://calendarserver.org/ns/:dropbox-home-URL':
507 $reply->CalendarserverElement($prop, 'dropbox-home-URL', $reply->href($this->url('dropbox')) );
508 break;
510 case 'http://calendarserver.org/ns/:xmpp-server':
511 if ( ! isset( $this->xmpp_uri ) ) return false;
512 $reply->CalendarserverElement($prop, 'xmpp-server', $this->xmpp_server );
513 break;
515 case 'http://calendarserver.org/ns/:xmpp-uri':
516 if ( ! isset( $this->xmpp_uri ) ) return false;
517 $reply->CalendarserverElement($prop, 'xmpp-uri', $this->xmpp_uri );
518 break;
520 case 'urn:ietf:params:xml:ns:carddav:addressbook-home-set':
521 $reply->NSElement($prop, $tag, $reply->href( $this->addressbook_home_set() ) );
522 break;
524 case 'urn:ietf:params:xml:ns:caldav:calendar-home-set':
525 $reply->NSElement($prop, $tag, $reply->href( $this->calendar_home_set() ) );
526 break;
528 case 'urn:ietf:params:xml:ns:caldav:calendar-free-busy-set':
529 $reply->CalDAVElement( $prop, 'calendar-free-busy-set', $reply->href( $this->calendar_free_busy_set() ) );
530 break;
532 case 'urn:ietf:params:xml:ns:caldav:calendar-user-address-set':
533 $reply->CalDAVElement($prop, 'calendar-user-address-set', $reply->href($this->user_address_set) );
534 break;
536 case 'DAV::owner':
537 // After a careful reading of RFC3744 we see that this must be the principal-URL of the owner
538 $reply->DAVElement( $prop, 'owner', $reply->href( $this->url ) );
539 break;
541 // Empty tag responses.
542 case 'DAV::alternate-URI-set':
543 $prop->NewElement( $reply->Tag($tag));
544 break;
546 case 'SOME-DENIED-PROPERTY': /** @todo indicating the style for future expansion */
547 $denied[] = $reply->Tag($tag);
548 break;
550 default:
551 return false;
552 break;
555 return true;
560 * Render XML for a single Principal (user) from the DB
562 * @param array $properties The requested properties for this principal
563 * @param reference $reply A reference to the XMLDocument being used for the reply
564 * @param boolean $props_only Default false. If true will only return the fragment with the properties, not a full response fragment.
566 * @return string An XML fragment with the requested properties for this principal
568 function RenderAsXML( $properties, &$reply, $props_only = false ) {
569 global $request;
571 dbg_error_log('principal',': RenderAsXML: Principal "%s"', $this->username );
573 $prop = new XMLElement('prop');
574 $denied = array();
575 $not_found = array();
576 foreach( $properties AS $k => $tag ) {
577 if ( ! $this->PrincipalProperty( $tag, $prop, $reply, $denied ) ) {
578 dbg_error_log( 'principal', 'Request for unsupported property "%s" of principal "%s".', $tag, $this->username );
579 $not_found[] = $reply->Tag($tag);
583 if ( $props_only ) return $prop;
585 $status = new XMLElement('status', 'HTTP/1.1 200 OK' );
587 $propstat = new XMLElement( 'propstat', array( $prop, $status) );
588 $href = $reply->href($this->url );
590 $elements = array($href,$propstat);
592 if ( count($denied) > 0 ) {
593 $status = new XMLElement('status', 'HTTP/1.1 403 Forbidden' );
594 $noprop = new XMLElement('prop');
595 foreach( $denied AS $k => $v ) {
596 $noprop->NewElement( $v );
598 $elements[] = new XMLElement( 'propstat', array( $noprop, $status) );
601 if ( count($not_found) > 0 ) {
602 $status = new XMLElement('status', 'HTTP/1.1 404 Not Found' );
603 $noprop = new XMLElement('prop');
604 foreach( $not_found AS $k => $v ) {
605 $noprop->NewElement( $v );
607 $elements[] = new XMLElement( 'propstat', array( $noprop, $status) );
610 $response = new XMLElement( 'response', $elements );
612 return $response;