Rewriting some TODO comments as @todo
[davical.git] / inc / CalDAVRequest.php
blob07e2029b0d0605cf5d3a26506a5437bb99b1057f
1 <?php
2 /**
3 * Functions that are needed for all CalDAV Requests
5 * - Ascertaining the paths
6 * - Ascertaining the current user's permission to those paths.
7 * - Utility functions which we can use to decide whether this
8 * is a permitted activity for this user.
10 * @package davical
11 * @subpackage Request
12 * @author Andrew McMillan <andrew@mcmillan.net.nz>
13 * @copyright Catalyst .Net Ltd, Morphoss Ltd
14 * @license http://gnu.org/copyleft/gpl.html GNU GPL v3 or later
17 require_once("AwlCache.php");
18 require_once("XMLDocument.php");
19 require_once("DAVPrincipal.php");
20 include("DAVTicket.php");
22 define('DEPTH_INFINITY', 9999);
24 /**
25 * A class for collecting things to do with this request.
27 * @package davical
29 class CalDAVRequest
31 var $options;
33 /**
34 * The raw data sent along with the request
36 var $raw_post;
38 /**
39 * The HTTP request method: PROPFIND, LOCK, REPORT, OPTIONS, etc...
41 var $method;
43 /**
44 * The depth parameter from the request headers, coerced into a valid integer: 0, 1
45 * or DEPTH_INFINITY which is defined above. The default is set per various RFCs.
47 var $depth;
49 /**
50 * The 'principal' (user/resource/...) which this request seeks to access
51 * @var DAVPrincipal
53 var $principal;
55 /**
56 * The 'current_user_principal_xml' the DAV:current-user-principal answer. An
57 * XMLElement object with an <href> or <unauthenticated> fragment.
59 var $current_user_principal_xml;
61 /**
62 * The user agent making the request.
64 var $user_agent;
66 /**
67 * The ID of the collection containing this path, or of this path if it is a collection
69 var $collection_id;
71 /**
72 * The path corresponding to the collection_id
74 var $collection_path;
76 /**
77 * The type of collection being requested:
78 * calendar, schedule-inbox, schedule-outbox
80 var $collection_type;
82 /**
83 * The type of collection being requested:
84 * calendar, schedule-inbox, schedule-outbox
86 protected $exists;
88 /**
89 * The decimal privileges allowed by this user to the identified resource.
91 protected $privileges;
93 /**
94 * A static structure of supported privileges.
96 var $supported_privileges;
98 /**
99 * A DAVTicket object, if there is a ?ticket=id or Ticket: id with this request
101 public $ticket;
104 * Create a new CalDAVRequest object.
106 function __construct( $options = array() ) {
107 global $session, $c, $debugging;
109 $this->options = $options;
110 if ( !isset($this->options['allow_by_email']) ) $this->options['allow_by_email'] = false;
112 if ( !isset($c->raw_post) ) $c->raw_post = file_get_contents( 'php://input');
113 $this->raw_post = $c->raw_post;
115 if ( isset($debugging) && isset($_GET['method']) ) {
116 $_SERVER['REQUEST_METHOD'] = $_GET['method'];
118 else if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) ){
119 $_SERVER['REQUEST_METHOD'] = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
121 $this->method = $_SERVER['REQUEST_METHOD'];
122 if ( isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 7 ) {
123 $this->content_type = (isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : null);
124 if ( preg_match( '{^(\S+/\S+)\s*(;.*)?$}', $this->content_type, $matches ) ) {
125 $this->content_type = $matches[1];
127 if ( $this->method == 'PROPFIND' || $this->method == 'REPORT' ) {
128 if ( !preg_match( '{^(text|application)/xml$}', $this->content_type ) ) {
129 dbg_error_log( "LOG request", 'Request is "%s" but client set content-type to "%s". Assuming they meant XML!',
130 $request->method, $this->content_type );
131 $this->content_type = 'text/xml';
135 $this->user_agent = ((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "Probably Mulberry"));
138 * A variety of requests may set the "Depth" header to control recursion
140 if ( isset($_SERVER['HTTP_DEPTH']) ) {
141 $this->depth = $_SERVER['HTTP_DEPTH'];
143 else {
145 * Per rfc2518, section 9.2, 'Depth' might not always be present, and if it
146 * is not present then a reasonable request-type-dependent default should be
147 * chosen.
149 switch( $this->method ) {
150 case 'PROPFIND':
151 case 'DELETE':
152 case 'MOVE':
153 case 'COPY':
154 case 'LOCK':
155 $this->depth = 'infinity';
156 break;
158 case 'REPORT':
159 default:
160 $this->depth = 0;
163 if ( $this->depth == 'infinity' ) $this->depth = DEPTH_INFINITY;
164 $this->depth = intval($this->depth);
167 * MOVE/COPY use a "Destination" header and (optionally) an "Overwrite" one.
169 if ( isset($_SERVER['HTTP_DESTINATION']) ) $this->destination = $_SERVER['HTTP_DESTINATION'];
170 $this->overwrite = ( isset($_SERVER['HTTP_OVERWRITE']) && ($_SERVER['HTTP_OVERWRITE'] == 'F') ? false : true ); // RFC4918, 9.8.4 says default True.
173 * LOCK things use an "If" header to hold the lock in some cases, and "Lock-token" in others
175 if ( isset($_SERVER['HTTP_IF']) ) $this->if_clause = $_SERVER['HTTP_IF'];
176 if ( isset($_SERVER['HTTP_LOCK_TOKEN']) && preg_match( '#[<]opaquelocktoken:(.*)[>]#', $_SERVER['HTTP_LOCK_TOKEN'], $matches ) ) {
177 $this->lock_token = $matches[1];
181 * Check for an access ticket.
183 if ( isset($_GET['ticket']) ) {
184 $this->ticket = new DAVTicket($_GET['ticket']);
186 else if ( isset($_SERVER['HTTP_TICKET']) ) {
187 $this->ticket = new DAVTicket($_SERVER['HTTP_TICKET']);
191 * LOCK things use a "Timeout" header to set a series of reducing alternative values
193 if ( isset($_SERVER['HTTP_TIMEOUT']) ) {
194 $timeouts = explode( ',', $_SERVER['HTTP_TIMEOUT'] );
195 foreach( $timeouts AS $k => $v ) {
196 if ( strtolower($v) == 'infinite' ) {
197 $this->timeout = (isset($c->maximum_lock_timeout) ? $c->maximum_lock_timeout : 86400 * 100);
198 break;
200 elseif ( strtolower(substr($v,0,7)) == 'second-' ) {
201 $this->timeout = min( intval(substr($v,7)), (isset($c->maximum_lock_timeout) ? $c->maximum_lock_timeout : 86400 * 100) );
202 break;
205 if ( ! isset($this->timeout) || $this->timeout == 0 ) $this->timeout = (isset($c->default_lock_timeout) ? $c->default_lock_timeout : 900);
209 * Our path is /<script name>/<user name>/<user controlled> if it ends in
210 * a trailing '/' then it is referring to a DAV 'collection' but otherwise
211 * it is referring to a DAV data item.
213 * Permissions are controlled as follows:
214 * 1. if there is no <user name> component, the request has read privileges
215 * 2. if the requester is an admin, the request has read/write priviliges
216 * 3. if there is a <user name> component which matches the logged on user
217 * then the request has read/write privileges
218 * 4. otherwise we query the defined relationships between users and use
219 * the minimum privileges returned from that analysis.
221 $this->path = (isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : "/");
222 $this->path = rawurldecode($this->path);
224 /** Allow a request for .../calendar.ics to translate into the calendar URL */
225 if ( preg_match( '#^(/[^/]+/[^/]+).ics$#', $this->path, $matches ) ) {
226 $this->path = $matches[1]. '/';
229 // dbg_error_log( "caldav", "Sanitising path '%s'", $this->path );
230 $bad_chars_regex = '/[\\^\\[\\(\\\\]/';
231 if ( preg_match( $bad_chars_regex, $this->path ) ) {
232 $this->DoResponse( 400, translate("The calendar path contains illegal characters.") );
234 if ( strstr($this->path,'//') ) $this->path = preg_replace( '#//+#', '/', $this->path);
236 $this->principal = new Principal('path',$this->path);
239 * RFC2518, 5.2: URL pointing to a collection SHOULD end in '/', and if it does not then
240 * we SHOULD return a Content-location header with the correction...
242 * We therefore look for a collection which matches one of the following URLs:
243 * - The exact request.
244 * - If the exact request, doesn't end in '/', then the request URL with a '/' appended
245 * - The request URL truncated to the last '/'
246 * The collection URL for this request is therefore the longest row in the result, so we
247 * can "... ORDER BY LENGTH(dav_name) DESC LIMIT 1"
249 $sql = "SELECT * FROM collection WHERE dav_name = :exact_name";
250 $params = array( ':exact_name' => $this->path );
251 if ( !preg_match( '#/$#', $this->path ) ) {
252 $sql .= " OR dav_name = :truncated_name OR dav_name = :trailing_slash_name";
253 $params[':truncated_name'] = preg_replace( '#[^/]*$#', '', $this->path);
254 $params[':trailing_slash_name'] = $this->path."/";
256 $sql .= " ORDER BY LENGTH(dav_name) DESC LIMIT 1";
257 $qry = new AwlQuery( $sql, $params );
258 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $qry->rows() == 1 && ($row = $qry->Fetch()) ) {
259 if ( $row->dav_name == $this->path."/" ) {
260 $this->path = $row->dav_name;
261 dbg_error_log( "caldav", "Path is actually a collection - sending Content-Location header." );
262 header( "Content-Location: ".ConstructURL($this->path) );
265 $this->collection_id = $row->collection_id;
266 $this->collection_path = $row->dav_name;
267 $this->collection_type = ($row->is_calendar == 't' ? 'calendar' : 'collection');
268 $this->collection = $row;
269 if ( preg_match( '#^((/[^/]+/)\.(in|out)/)[^/]*$#', $this->path, $matches ) ) {
270 $this->collection_type = 'schedule-'. $matches[3]. 'box';
272 $this->collection->type = $this->collection_type;
274 else if ( preg_match( '{^( ( / ([^/]+) / ) \.(in|out)/ ) [^/]*$}x', $this->path, $matches ) ) {
275 // The request is for a scheduling inbox or outbox (or something inside one) and we should auto-create it
276 $params = array( ':username' => $matches[3], ':parent_container' => $matches[2], ':dav_name' => $matches[1] );
277 $params[':boxname'] = ($matches[4] == 'in' ? ' Inbox' : ' Outbox');
278 $this->collection_type = 'schedule-'. $matches[4]. 'box';
279 $params[':resourcetypes'] = sprintf('<DAV::collection/><urn:ietf:params:xml:ns:caldav:%s/>', $this->collection_type );
280 $sql = <<<EOSQL
281 INSERT INTO collection ( user_no, parent_container, dav_name, dav_displayname, is_calendar, created, modified, dav_etag, resourcetypes )
282 VALUES( (SELECT user_no FROM usr WHERE username = :username),
283 :parent_container, :dav_name,
284 (SELECT fullname FROM usr WHERE username = :username) || :boxname,
285 FALSE, current_timestamp, current_timestamp, '1', :resourcetypes )
286 EOSQL;
288 $qry = new AwlQuery( $sql, $params );
289 $qry->Exec('caldav',__LINE__,__FILE__);
290 dbg_error_log( 'caldav', 'Created new collection as "%s".', trim($params[':boxname']) );
292 // Uncache anything to do with the collection
293 $cache = getCacheInstance();
294 $cache->delete( 'collection-'.$params[':dav_name'], null );
295 $cache->delete( 'principal-'.$params[':parent_container'], null );
297 $qry = new AwlQuery( "SELECT * FROM collection WHERE dav_name = :dav_name", array( ':dav_name' => $matches[1] ) );
298 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $qry->rows() == 1 && ($row = $qry->Fetch()) ) {
299 $this->collection_id = $row->collection_id;
300 $this->collection_path = $matches[1];
301 $this->collection = $row;
302 $this->collection->type = $this->collection_type;
305 else if ( preg_match( '#^((/[^/]+/)calendar-proxy-(read|write))/?[^/]*$#', $this->path, $matches ) ) {
306 $this->collection_type = 'proxy';
307 $this->_is_proxy_request = true;
308 $this->proxy_type = $matches[3];
309 $this->collection_path = $matches[1].'/'; // Enforce trailling '/'
310 if ( $this->collection_path == $this->path."/" ) {
311 $this->path .= '/';
312 dbg_error_log( "caldav", "Path is actually a (proxy) collection - sending Content-Location header." );
313 header( "Content-Location: ".ConstructURL($this->path) );
316 else if ( $this->options['allow_by_email'] && preg_match( '#^/(\S+@\S+[.]\S+)/?$#', $this->path) ) {
317 /** @todo we should deprecate this now that Evolution 2.27 can do scheduling extensions */
318 $this->collection_id = -1;
319 $this->collection_type = 'email';
320 $this->collection_path = $this->path;
321 $this->_is_principal = true;
323 else if ( preg_match( '#^(/[^/]+)/?$#', $this->path, $matches) || preg_match( '#^(/principals/[^/]+/[^/]+)/?$#', $this->path, $matches) ) {
324 $this->collection_id = -1;
325 $this->collection_path = $matches[1].'/'; // Enforce trailling '/'
326 $this->collection_type = 'principal';
327 $this->_is_principal = true;
328 if ( $this->collection_path == $this->path."/" ) {
329 $this->path .= '/';
330 dbg_error_log( "caldav", "Path is actually a collection - sending Content-Location header." );
331 header( "Content-Location: ".ConstructURL($this->path) );
333 if ( preg_match( '#^(/principals/[^/]+/[^/]+)/?$#', $this->path, $matches) ) {
334 // Force a depth of 0 on these, which are at the wrong URL.
335 $this->depth = 0;
338 else if ( $this->path == '/' ) {
339 $this->collection_id = -1;
340 $this->collection_path = '/';
341 $this->collection_type = 'root';
344 if ( $this->collection_path == $this->path ) $this->_is_collection = true;
345 dbg_error_log( "caldav", " Collection '%s' is %d, type %s", $this->collection_path, $this->collection_id, $this->collection_type );
348 * Extract the user whom we are accessing
350 $this->principal = new DAVPrincipal( array( "path" => $this->path, "options" => $this->options ) );
351 $this->user_no = $this->principal->user_no();
352 $this->username = $this->principal->username();
353 $this->by_email = $this->principal->byEmail();
354 $this->principal_id = $this->principal->principal_id();
356 if ( $this->collection_type == 'principal' || $this->collection_type == 'email' || $this->collection_type == 'proxy' ) {
357 $this->collection = $this->principal->AsCollection();
358 if( $this->collection_type == 'proxy' ) {
359 $this->collection = $this->principal->AsCollection();
360 $this->collection->is_proxy = 't';
361 $this->collection->type = 'proxy';
362 $this->collection->proxy_type = $this->proxy_type;
363 $this->collection->dav_displayname = sprintf('Proxy %s for %s', $this->proxy_type, $this->principal->username() );
366 elseif( $this->collection_type == 'root' ) {
367 $this->collection = (object) array(
368 'collection_id' => 0,
369 'dav_name' => '/',
370 'dav_etag' => md5($c->system_name),
371 'is_calendar' => 'f',
372 'is_addressbook' => 'f',
373 'is_principal' => 'f',
374 'user_no' => 0,
375 'dav_displayname' => $c->system_name,
376 'type' => 'root',
377 'created' => date('Ymd\THis')
382 * Evaluate our permissions for accessing the target
384 $this->setPermissions();
386 $this->supported_methods = array(
387 'OPTIONS' => '',
388 'PROPFIND' => '',
389 'REPORT' => '',
390 'DELETE' => '',
391 'LOCK' => '',
392 'UNLOCK' => '',
393 'MOVE' => '',
394 'ACL' => ''
396 if ( $this->IsCollection() ) {
397 switch ( $this->collection_type ) {
398 case 'root':
399 case 'email':
400 // We just override the list completely here.
401 $this->supported_methods = array(
402 'OPTIONS' => '',
403 'PROPFIND' => '',
404 'REPORT' => ''
406 break;
407 case 'schedule-inbox':
408 case 'schedule-outbox':
409 $this->supported_methods = array_merge(
410 $this->supported_methods,
411 array(
412 'POST' => '', 'GET' => '', 'PUT' => '', 'HEAD' => '', 'PROPPATCH' => ''
415 break;
416 case 'calendar':
417 $this->supported_methods['GET'] = '';
418 $this->supported_methods['PUT'] = '';
419 $this->supported_methods['HEAD'] = '';
420 break;
421 case 'collection':
422 case 'principal':
423 $this->supported_methods['GET'] = '';
424 $this->supported_methods['PUT'] = '';
425 $this->supported_methods['HEAD'] = '';
426 $this->supported_methods['MKCOL'] = '';
427 $this->supported_methods['MKCALENDAR'] = '';
428 $this->supported_methods['PROPPATCH'] = '';
429 $this->supported_methods['BIND'] = '';
430 break;
433 else {
434 $this->supported_methods = array_merge(
435 $this->supported_methods,
436 array(
437 'GET' => '',
438 'HEAD' => '',
439 'PUT' => ''
444 $this->supported_reports = array(
445 'DAV::principal-property-search' => '',
446 'DAV::expand-property' => '',
447 'DAV::sync-collection' => ''
449 if ( isset($this->collection) && $this->collection->is_calendar ) {
450 $this->supported_reports = array_merge(
451 $this->supported_reports,
452 array(
453 'urn:ietf:params:xml:ns:caldav:calendar-query' => '',
454 'urn:ietf:params:xml:ns:caldav:calendar-multiget' => '',
455 'urn:ietf:params:xml:ns:caldav:free-busy-query' => ''
459 if ( isset($this->collection) && $this->collection->is_addressbook ) {
460 $this->supported_reports = array_merge(
461 $this->supported_reports,
462 array(
463 'urn:ietf:params:xml:ns:carddav:addressbook-query' => '',
464 'urn:ietf:params:xml:ns:carddav:addressbook-multiget' => ''
471 * If the content we are receiving is XML then we parse it here. RFC2518 says we
472 * should reasonably expect to see either text/xml or application/xml
474 if ( isset($this->content_type) && preg_match( '#(application|text)/xml#', $this->content_type ) ) {
475 $xml_parser = xml_parser_create_ns('UTF-8');
476 $this->xml_tags = array();
477 xml_parser_set_option ( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
478 xml_parser_set_option ( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
479 $rc = xml_parse_into_struct( $xml_parser, $this->raw_post, $this->xml_tags );
480 if ( $rc == false ) {
481 dbg_error_log( 'ERROR', 'XML parsing error: %s at line %d, column %d',
482 xml_error_string(xml_get_error_code($xml_parser)),
483 xml_get_current_line_number($xml_parser), xml_get_current_column_number($xml_parser) );
484 $this->XMLResponse( 400, new XMLElement( 'error', new XMLElement('invalid-xml'), array( 'xmlns' => 'DAV:') ) );
486 xml_parser_free($xml_parser);
487 if ( count($this->xml_tags) ) {
488 dbg_error_log( "caldav", " Parsed incoming XML request body." );
490 else {
491 $this->xml_tags = null;
492 dbg_error_log( "ERROR", "Incoming request sent content-type XML with no XML request body." );
497 * Look out for If-None-Match or If-Match headers
499 if ( isset($_SERVER["HTTP_IF_NONE_MATCH"]) ) {
500 $this->etag_none_match = $_SERVER["HTTP_IF_NONE_MATCH"];
501 if ( $this->etag_none_match == '' ) unset($this->etag_none_match);
503 if ( isset($_SERVER["HTTP_IF_MATCH"]) ) {
504 $this->etag_if_match = $_SERVER["HTTP_IF_MATCH"];
505 if ( $this->etag_if_match == '' ) unset($this->etag_if_match);
511 * Permissions are controlled as follows:
512 * 1. if the path is '/', the request has read privileges
513 * 2. if the requester is an admin, the request has read/write priviliges
514 * 3. if there is a <user name> component which matches the logged on user
515 * then the request has read/write privileges
516 * 4. otherwise we query the defined relationships between users and use
517 * the minimum privileges returned from that analysis.
519 * @param int $user_no The current user number
522 function setPermissions() {
523 global $c, $session;
525 if ( $this->path == '/' || $this->path == '' ) {
526 $this->privileges = privilege_to_bits( array('read','read-free-busy','read-acl'));
527 dbg_error_log( "caldav", "Full read permissions for user accessing /" );
529 else if ( $session->AllowedTo("Admin") || $session->principal->user_no() == $this->user_no ) {
530 $this->privileges = privilege_to_bits('all');
531 dbg_error_log( "caldav", "Full permissions for %s", ( $session->principal->user_no() == $this->user_no ? "user accessing their own hierarchy" : "a systems administrator") );
533 else {
534 $this->privileges = 0;
535 if ( $this->IsPublic() ) {
536 $this->privileges = privilege_to_bits(array('read','read-free-busy'));
537 dbg_error_log( "caldav", "Basic read permissions for user accessing a public collection" );
539 else if ( isset($c->public_freebusy_url) && $c->public_freebusy_url ) {
540 $this->privileges = privilege_to_bits('read-free-busy');
541 dbg_error_log( "caldav", "Basic free/busy permissions for user accessing a public free/busy URL" );
545 * In other cases we need to query the database for permissions
547 $params = array( ':session_principal_id' => $session->principal->principal_id(), ':scan_depth' => $c->permission_scan_depth );
548 if ( isset($this->by_email) && $this->by_email ) {
549 $sql ='SELECT pprivs( :session_principal_id::int8, :request_principal_id::int8, :scan_depth::int ) AS perm';
550 $params[':request_principal_id'] = $this->principal_id;
552 else {
553 $sql = 'SELECT path_privs( :session_principal_id::int8, :request_path::text, :scan_depth::int ) AS perm';
554 $params[':request_path'] = $this->path;
556 $qry = new AwlQuery( $sql, $params );
557 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $permission_result = $qry->Fetch() )
558 $this->privileges |= bindec($permission_result->perm);
560 dbg_error_log( 'caldav', 'Restricted permissions for user accessing someone elses hierarchy: %s', decbin($this->privileges) );
561 if ( isset($this->ticket) && $this->ticket->MatchesPath($this->path) ) {
562 $this->privileges |= $this->ticket->privileges();
563 dbg_error_log( 'caldav', 'Applying permissions for ticket "%s" now: %s', $this->ticket->id(), decbin($this->privileges) );
567 /** convert privileges into older style permissions */
568 $this->permissions = array();
569 $privs = bits_to_privilege($this->privileges);
570 foreach( $privs AS $k => $v ) {
571 switch( $v ) {
572 case 'DAV::all': $type = 'abstract'; break;
573 case 'DAV::write': $type = 'aggregate'; break;
574 default: $type = 'real';
576 $v = str_replace('DAV::', '', $v);
577 $this->permissions[$v] = $type;
584 * Checks whether the resource is locked, returning any lock token, or false
586 * @todo This logic does not catch all locking scenarios. For example an infinite
587 * depth request should check the permissions for all collections and resources within
588 * that. At present we only maintain permissions on a per-collection basis though.
590 function IsLocked() {
591 if ( !isset($this->_locks_found) ) {
592 $this->_locks_found = array();
594 $sql = 'DELETE FROM locks WHERE (start + timeout) < current_timestamp';
595 $qry = new AwlQuery($sql);
596 $qry->Exec('caldav',__LINE__,__FILE__);
599 * Find the locks that might apply and load them into an array
601 $sql = 'SELECT * FROM locks WHERE :dav_name::text ~ (\'^\'||dav_name||:pattern_end_match)::text';
602 $qry = new AwlQuery($sql, array( ':dav_name' => $this->path, ':pattern_end_match' => ($this->IsInfiniteDepth() ? '' : '$') ) );
603 if ( $qry->Exec('caldav',__LINE__,__FILE__) ) {
604 while( $lock_row = $qry->Fetch() ) {
605 $this->_locks_found[$lock_row->opaquelocktoken] = $lock_row;
608 else {
609 $this->DoResponse(500,translate("Database Error"));
610 // Does not return.
614 foreach( $this->_locks_found AS $lock_token => $lock_row ) {
615 if ( $lock_row->depth == DEPTH_INFINITY || $lock_row->dav_name == $this->path ) {
616 return $lock_token;
620 return false; // Nothing matched
625 * Checks whether the collection is public
627 function IsPublic() {
628 if ( isset($this->collection) && isset($this->collection->publicly_readable) && $this->collection->publicly_readable == 't' ) {
629 return true;
631 return false;
635 private static function supportedPrivileges() {
636 return array(
637 'all' => array(
638 'read' => translate('Read the content of a resource or collection'),
639 'write' => array(
640 'bind' => translate('Create a resource or collection'),
641 'unbind' => translate('Delete a resource or collection'),
642 'write-content' => translate('Write content'),
643 'write-properties' => translate('Write properties')
645 'urn:ietf:params:xml:ns:caldav:read-free-busy' => translate('Read the free/busy information for a calendar collection'),
646 'read-acl' => translate('Read ACLs for a resource or collection'),
647 'read-current-user-privilege-set' => translate('Read the details of the current user\'s access control to this resource.'),
648 'write-acl' => translate('Write ACLs for a resource or collection'),
649 'unlock' => translate('Remove a lock'),
651 'urn:ietf:params:xml:ns:caldav:schedule-deliver' => array(
652 'urn:ietf:params:xml:ns:caldav:schedule-deliver-invite'=> translate('Deliver scheduling invitations from an organiser to this scheduling inbox'),
653 'urn:ietf:params:xml:ns:caldav:schedule-deliver-reply' => translate('Deliver scheduling replies from an attendee to this scheduling inbox'),
654 'urn:ietf:params:xml:ns:caldav:schedule-query-freebusy' => translate('Allow free/busy enquiries targeted at the owner of this scheduling inbox')
657 'urn:ietf:params:xml:ns:caldav:schedule-send' => array(
658 'urn:ietf:params:xml:ns:caldav:schedule-send-invite' => translate('Send scheduling invitations as an organiser from the owner of this scheduling outbox.'),
659 'urn:ietf:params:xml:ns:caldav:schedule-send-reply' => translate('Send scheduling replies as an attendee from the owner of this scheduling outbox.'),
660 'urn:ietf:params:xml:ns:caldav:schedule-send-freebusy' => translate('Send free/busy enquiries')
667 * Returns the dav_name of the resource in our internal namespace
669 function dav_name() {
670 if ( isset($this->path) ) return $this->path;
671 return null;
676 * Returns the name for this depth: 0, 1, infinity
678 function GetDepthName( ) {
679 if ( $this->IsInfiniteDepth() ) return 'infinity';
680 return $this->depth;
684 * Returns the tail of a Regex appropriate for this Depth, when appended to
687 function DepthRegexTail() {
688 if ( $this->IsInfiniteDepth() ) return '';
689 if ( $this->depth == 0 ) return '$';
690 return '[^/]*/?$';
694 * Returns the locked row, either from the cache or from the database
696 * @param string $dav_name The resource which we want to know the lock status for
698 function GetLockRow( $lock_token ) {
699 if ( isset($this->_locks_found) && isset($this->_locks_found[$lock_token]) ) {
700 return $this->_locks_found[$lock_token];
703 $qry = new AwlQuery('SELECT * FROM locks WHERE opaquelocktoken = :lock_token', array( ':lock_token' => $lock_token ) );
704 if ( $qry->Exec('caldav',__LINE__,__FILE__) ) {
705 $lock_row = $qry->Fetch();
706 $this->_locks_found = array( $lock_token => $lock_row );
707 return $this->_locks_found[$lock_token];
709 else {
710 $this->DoResponse( 500, translate("Database Error") );
713 return false; // Nothing matched
718 * Checks to see whether the lock token given matches one of the ones handed in
719 * with the request.
721 * @param string $lock_token The opaquelocktoken which we are looking for
723 function ValidateLockToken( $lock_token ) {
724 if ( isset($this->lock_token) && $this->lock_token == $lock_token ) {
725 dbg_error_log( "caldav", "They supplied a valid lock token. Great!" );
726 return true;
728 if ( isset($this->if_clause) ) {
729 dbg_error_log( "caldav", "Checking lock token '%s' against '%s'", $lock_token, $this->if_clause );
730 $tokens = preg_split( '/[<>]/', $this->if_clause );
731 foreach( $tokens AS $k => $v ) {
732 dbg_error_log( "caldav", "Checking lock token '%s' against '%s'", $lock_token, $v );
733 if ( 'opaquelocktoken:' == substr( $v, 0, 16 ) ) {
734 if ( substr( $v, 16 ) == $lock_token ) {
735 dbg_error_log( "caldav", "Lock token '%s' validated OK against '%s'", $lock_token, $v );
736 return true;
741 else {
742 @dbg_error_log( "caldav", "Invalid lock token '%s' - not in Lock-token (%s) or If headers (%s) ", $lock_token, $this->lock_token, $this->if_clause );
745 return false;
750 * Returns the DB object associated with a lock token, or false.
752 * @param string $lock_token The opaquelocktoken which we are looking for
754 function GetLockDetails( $lock_token ) {
755 if ( !isset($this->_locks_found) && false === $this->IsLocked() ) return false;
756 if ( isset($this->_locks_found[$lock_token]) ) return $this->_locks_found[$lock_token];
757 return false;
762 * This will either (a) return false if no locks apply, or (b) return the lock_token
763 * which the request successfully included to open the lock, or:
764 * (c) respond directly to the client with the failure.
766 * @return mixed false (no lock) or opaquelocktoken (opened lock)
768 function FailIfLocked() {
769 if ( $existing_lock = $this->IsLocked() ) { // NOTE Assignment in if() is expected here.
770 dbg_error_log( "caldav", "There is a lock on '%s'", $this->path);
771 if ( ! $this->ValidateLockToken($existing_lock) ) {
772 $lock_row = $this->GetLockRow($existing_lock);
774 * Already locked - deny it
776 $response[] = new XMLElement( 'response', array(
777 new XMLElement( 'href', $lock_row->dav_name ),
778 new XMLElement( 'status', 'HTTP/1.1 423 Resource Locked')
780 if ( $lock_row->dav_name != $this->path ) {
781 $response[] = new XMLElement( 'response', array(
782 new XMLElement( 'href', $this->path ),
783 new XMLElement( 'propstat', array(
784 new XMLElement( 'prop', new XMLElement( 'lockdiscovery' ) ),
785 new XMLElement( 'status', 'HTTP/1.1 424 Failed Dependency')
789 $response = new XMLElement( "multistatus", $response, array('xmlns'=>'DAV:') );
790 $xmldoc = $response->Render(0,'<?xml version="1.0" encoding="utf-8" ?>');
791 $this->DoResponse( 207, $xmldoc, 'text/xml; charset="utf-8"' );
792 // Which we won't come back from
794 return $existing_lock;
796 return false;
801 * Coerces the Content-type of the request into something valid/appropriate
803 function CoerceContentType() {
804 if ( isset($this->content_type) ) {
805 $type = explode( '/', $this->content_type, 2);
806 /** @todo: Perhaps we should look at the target collection type, also. */
807 if ( $type[0] == 'text' ) return;
810 /** Null (or peculiar) content-type supplied so we have to try and work it out... */
811 $first_word = trim(substr( $this->raw_post, 0, 30));
812 $first_word = strtoupper( preg_replace( '/\s.*/s', '', $first_word ) );
813 switch( $first_word ) {
814 case '<?XML':
815 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/xml"',
816 (isset($this->content_type)?$this->content_type:'(null)') );
817 $this->content_type = 'text/xml';
818 break;
819 case 'BEGIN:VCALENDAR':
820 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/calendar"',
821 (isset($this->content_type)?$this->content_type:'(null)') );
822 $this->content_type = 'text/calendar';
823 break;
824 case 'BEGIN:VCARD':
825 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/vcard"',
826 (isset($this->content_type)?$this->content_type:'(null)') );
827 $this->content_type = 'text/vcard';
828 break;
829 default:
830 dbg_error_log( 'LOG NOTICE', 'Unusual content-type of "%s" and first word of content is "%s"',
831 (isset($this->content_type)?$this->content_type:'(null)'), $first_word );
833 $this->content_type = 'text/plain';
838 * Returns true if the URL referenced by this request points at a collection.
840 function IsCollection( ) {
841 if ( !isset($this->_is_collection) ) {
842 $this->_is_collection = preg_match( '#/$#', $this->path );
844 return $this->_is_collection;
849 * Returns true if the URL referenced by this request points at a calendar collection.
851 function IsCalendar( ) {
852 if ( !$this->IsCollection() || !isset($this->collection) ) return false;
853 return $this->collection->is_calendar == 't';
858 * Returns true if the URL referenced by this request points at an addressbook collection.
860 function IsAddressBook( ) {
861 if ( !$this->IsCollection() || !isset($this->collection) ) return false;
862 return $this->collection->is_addressbook == 't';
867 * Returns true if the URL referenced by this request points at a principal.
869 function IsPrincipal( ) {
870 if ( !isset($this->_is_principal) ) {
871 $this->_is_principal = preg_match( '#^/[^/]+/$#', $this->path );
873 return $this->_is_principal;
878 * Returns true if the URL referenced by this request is within a proxy URL
880 function IsProxyRequest( ) {
881 if ( !isset($this->_is_proxy_request) ) {
882 $this->_is_proxy_request = preg_match( '#^/[^/]+/calendar-proxy-(read|write)/?[^/]*$#', $this->path );
884 return $this->_is_proxy_request;
889 * Returns true if the request asked for infinite depth
891 function IsInfiniteDepth( ) {
892 return ($this->depth == DEPTH_INFINITY);
897 * Returns the ID of the collection of, or containing this request
899 function CollectionId( ) {
900 return $this->collection_id;
905 * Returns the array of supported privileges converted into XMLElements
907 function BuildSupportedPrivileges( &$reply, $privs = null ) {
908 $privileges = array();
909 if ( $privs === null ) $privs = self::supportedPrivileges();
910 foreach( $privs AS $k => $v ) {
911 dbg_error_log( 'caldav', 'Adding privilege "%s" which is "%s".', $k, $v );
912 $privilege = new XMLElement('privilege');
913 $reply->NSElement($privilege,$k);
914 $privset = array($privilege);
915 if ( is_array($v) ) {
916 dbg_error_log( 'caldav', '"%s" is a container of sub-privileges.', $k );
917 $privset = array_merge($privset, $this->BuildSupportedPrivileges($reply,$v));
919 else if ( $v == 'abstract' ) {
920 dbg_error_log( 'caldav', '"%s" is an abstract privilege.', $v );
921 $privset[] = new XMLElement('abstract');
923 else if ( strlen($v) > 1 ) {
924 $privset[] = new XMLElement('description', $v);
926 $privileges[] = new XMLElement('supported-privilege',$privset);
928 return $privileges;
933 * Are we allowed to do the requested activity
935 * +------------+------------------------------------------------------+
936 * | METHOD | PRIVILEGES |
937 * +------------+------------------------------------------------------+
938 * | MKCALENDAR | DAV:bind |
939 * | REPORT | DAV:read or CALDAV:read-free-busy (on all referenced |
940 * | | resources) |
941 * +------------+------------------------------------------------------+
943 * @param string $activity The activity we want to do.
945 function AllowedTo( $activity ) {
946 global $session;
947 dbg_error_log('caldav', 'Checking whether "%s" is allowed to "%s"', $session->principal->username(), $activity);
948 if ( isset($this->permissions['all']) ) return true;
949 switch( $activity ) {
950 case 'all':
951 return false; // If they got this far then they don't
952 break;
954 case "CALDAV:schedule-send-freebusy":
955 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
956 break;
958 case "CALDAV:schedule-send-invite":
959 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
960 break;
962 case "CALDAV:schedule-send-reply":
963 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
964 break;
966 case 'freebusy':
967 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
968 break;
970 case 'delete':
971 return isset($this->permissions['write']) || isset($this->permissions['unbind']);
972 break;
974 case 'proppatch':
975 return isset($this->permissions['write']) || isset($this->permissions['write-properties']);
976 break;
978 case 'modify':
979 return isset($this->permissions['write']) || isset($this->permissions['write-content']);
980 break;
982 case 'create':
983 return isset($this->permissions['write']) || isset($this->permissions['bind']);
984 break;
986 case 'mkcalendar':
987 case 'mkcol':
988 if ( !isset($this->permissions['write']) || !isset($this->permissions['bind']) ) return false;
989 if ( $this->is_principal ) return false;
990 if ( $this->path == '/' ) return false;
991 break;
993 default:
994 $test_bits = privilege_to_bits( $activity );
995 // dbg_error_log( 'caldav', 'request::AllowedTo("%s") (%s) against allowed "%s" => "%s" (%s)',
996 // (is_array($activity) ? implode(',',$activity) : $activity), decbin($test_bits),
997 // decbin($this->privileges), ($this->privileges & $test_bits), decbin($this->privileges & $test_bits) );
998 return (($this->privileges & $test_bits) > 0 );
999 break;
1002 return false;
1008 * Return the privileges bits for the current session user to this resource
1010 function Privileges() {
1011 return $this->privileges;
1016 * Is the user has the privileges to do what is requested.
1018 function HavePrivilegeTo( $do_what ) {
1019 $test_bits = privilege_to_bits( $do_what );
1020 // dbg_error_log( 'caldav', 'request::HavePrivilegeTo("%s") [%s] against allowed "%s" => "%s" (%s)',
1021 // (is_array($do_what) ? implode(',',$do_what) : $do_what), decbin($test_bits),
1022 // decbin($this->privileges), ($this->privileges & $test_bits), decbin($this->privileges & $test_bits) );
1023 return ($this->privileges & $test_bits) > 0;
1028 * Sometimes it's a perfectly formed request, but we just don't do that :-(
1029 * @param array $unsupported An array of the properties we don't support.
1031 function UnsupportedRequest( $unsupported ) {
1032 if ( isset($unsupported) && count($unsupported) > 0 ) {
1033 $badprops = new XMLElement( "prop" );
1034 foreach( $unsupported AS $k => $v ) {
1035 // Not supported at this point...
1036 dbg_error_log("ERROR", " %s: Support for $v:$k properties is not implemented yet", $this->method );
1037 $badprops->NewElement(strtolower($k),false,array("xmlns" => strtolower($v)));
1039 $error = new XMLElement("error", $badprops, array("xmlns" => "DAV:") );
1041 $this->XMLResponse( 422, $error );
1047 * Send a need-privileges error response. This function will only return
1048 * if the $href is not supplied and the current user has the specified
1049 * permission for the request path.
1051 * @param string $privilege The name of the needed privilege.
1052 * @param string $href The unconstructed URI where we needed the privilege.
1054 function NeedPrivilege( $privileges, $href=null ) {
1055 if ( is_string($privileges) ) $privileges = array( $privileges );
1056 if ( !isset($href) ) {
1057 if ( $this->HavePrivilegeTo($privileges) ) return;
1058 $href = $this->path;
1061 $reply = new XMLDocument( array('DAV:' => '') );
1062 $privnodes = array( $reply->href(ConstructURL($href)), new XMLElement( 'privilege' ) );
1063 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
1064 $reply->NSElement( $privnodes[1], $privileges[0] );
1065 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
1066 $xmldoc = $reply->Render('error',$xml);
1067 $this->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
1068 exit(0); // Unecessary, but might clarify things
1073 * Send an error response for a failed precondition.
1075 * @param int $status The status code for the failed precondition. Normally 403
1076 * @param string $precondition The namespaced precondition tag.
1077 * @param string $explanation An optional text explanation for the failure.
1079 function PreconditionFailed( $status, $precondition, $explanation = '') {
1080 $xmldoc = sprintf('<?xml version="1.0" encoding="utf-8" ?>
1081 <error xmlns="DAV:">
1082 <%s/>%s
1083 </error>', str_replace('DAV::', '', $precondition), $explanation );
1085 $this->DoResponse( $status, $xmldoc, 'text/xml; charset="utf-8"' );
1086 exit(0); // Unecessary, but might clarify things
1091 * Send a simple error informing the client that was a malformed request
1093 * @param string $text An optional text description of the failure.
1095 function MalformedRequest( $text = 'Bad request' ) {
1096 $this->DoResponse( 400, $text );
1097 exit(0); // Unecessary, but might clarify things
1102 * Send an XML Response. This function will never return.
1104 * @param int $status The HTTP status to respond
1105 * @param XMLElement $xmltree An XMLElement tree to be rendered
1107 function XMLResponse( $status, $xmltree ) {
1108 $xmldoc = $xmltree->Render(0,'<?xml version="1.0" encoding="utf-8" ?>');
1109 $etag = md5($xmldoc);
1110 header("ETag: \"$etag\"");
1111 $this->DoResponse( $status, $xmldoc, 'text/xml; charset="utf-8"' );
1112 exit(0); // Unecessary, but might clarify things
1116 * Utility function we call when we have a simple status-based response to
1117 * return to the client. Possibly
1119 * @param int $status The HTTP status code to send.
1120 * @param string $message The friendly text message to send with the response.
1122 function DoResponse( $status, $message="", $content_type="text/plain; charset=\"utf-8\"" ) {
1123 global $session, $c;
1124 @header( sprintf("HTTP/1.1 %d %s", $status, getStatusMessage($status)) );
1125 @header( sprintf("X-DAViCal-Version: DAViCal/%d.%d.%d; DB/%d.%d.%d", $c->code_major, $c->code_minor, $c->code_patch, $c->schema_major, $c->schema_minor, $c->schema_patch) );
1126 @header( "Content-type: ".$content_type );
1128 if ( (isset($c->dbg['ALL']) && $c->dbg['ALL']) || (isset($c->dbg['response']) && $c->dbg['response']) || $status > 399 ) {
1129 $lines = headers_list();
1130 dbg_error_log( "LOG ", "***************** Response Header ****************" );
1131 foreach( $lines AS $v ) {
1132 dbg_error_log( "LOG headers", "-->%s", $v );
1134 dbg_error_log( "LOG ", "******************** Response ********************" );
1135 // Log the request in all it's gory detail.
1136 $lines = preg_split( '#[\r\n]+#', $message);
1137 foreach( $lines AS $v ) {
1138 dbg_error_log( "LOG response", "-->%s", $v );
1142 header( "Content-Length: ".strlen($message) );
1143 echo $message;
1145 if ( isset($c->dbg['caldav']) && $c->dbg['caldav'] ) {
1146 if ( strlen($message) > 100 || strstr($message, "\n") ) {
1147 $message = substr( preg_replace("#\s+#m", ' ', $message ), 0, 100) . (strlen($message) > 100 ? "..." : "");
1150 dbg_error_log("caldav", "Status: %d, Message: %s, User: %d, Path: %s", $status, $message, $session->principal->user_no(), $this->path);
1152 if ( isset($c->dbg['statistics']) && $c->dbg['statistics'] ) {
1153 $script_time = microtime(true) - $c->script_start_time;
1154 @dbg_error_log("statistics", "Method: %s, Status: %d, Script: %5.3lfs, Queries: %5.3lfs, URL: %s",
1155 $this->method, $status, $script_time, $c->total_query_time, $this->path);
1158 exit(0);