DAViCal
CalDAVRequest.php
1<?php
17require_once("AwlCache.php");
18require_once("XMLDocument.php");
19require_once("DAVPrincipal.php");
20require_once("DAVTicket.php");
21
22define('DEPTH_INFINITY', 9999);
23
24
31{
32 var $options;
33
38
43
48 var $depth;
49
54 var $principal;
55
61
66
71
76
82
87 protected $exists;
88
93
97 protected $privileges;
98
103
107 public $ticket;
108
113 private $prefer;
114
118 function __construct( $options = array() ) {
119 global $session, $c, $debugging;
120
121 $this->options = $options;
122 if ( !isset($this->options['allow_by_email']) ) $this->options['allow_by_email'] = false;
123
124 if ( isset($_SERVER['HTTP_PREFER']) ) {
125 $this->prefer = explode( ',', $_SERVER['HTTP_PREFER']);
126 }
127 else if ( isset($_SERVER['HTTP_BRIEF']) && (strtoupper($_SERVER['HTTP_BRIEF']) == 'T') ) {
128 $this->prefer = array( 'return=minimal');
129 }
130 else
131 $this->prefer = array();
132
146 if ( isset($_SERVER['PATH_INFO']) ) {
147 $this->path = $_SERVER['PATH_INFO'];
148 }
149 else {
150 $this->path = '/';
151 if ( isset($_SERVER['REQUEST_URI']) ) {
152 if ( preg_match( '{^(.*?\.php)([^?]*)}', $_SERVER['REQUEST_URI'], $matches ) ) {
153 $this->path = $matches[2];
154 if ( substr($this->path,0,1) != '/' )
155 $this->path = '/'.$this->path;
156 }
157 else if ( $_SERVER['REQUEST_URI'] != '/' ) {
158 dbg_error_log('LOG', 'Server is not supplying PATH_INFO and REQUEST_URI does not include a PHP program. Wildly guessing "/"!!!');
159 }
160 }
161 }
162 $this->path = rawurldecode($this->path);
163
165 if ( preg_match( '#^(/[^/]+/[^/]+).ics$#', $this->path, $matches ) ) {
166 $this->path = $matches[1]. '/';
167 }
168
169 if ( isset($c->replace_path) && isset($c->replace_path['from']) && isset($c->replace_path['to']) ) {
170 $this->path = preg_replace($c->replace_path['from'], $c->replace_path['to'], $this->path);
171 }
172
173 // dbg_error_log( "caldav", "Sanitising path '%s'", $this->path );
174 $bad_chars_regex = '/[\\^\\[\\(\\\\]/';
175 if ( preg_match( $bad_chars_regex, $this->path ) ) {
176 $this->DoResponse( 400, translate("The calendar path contains illegal characters.") );
177 }
178 if ( strstr($this->path,'//') ) $this->path = preg_replace( '#//+#', '/', $this->path);
179
180 if ( !isset($c->raw_post) ) $c->raw_post = file_get_contents( 'php://input');
181 if ( isset($_SERVER['HTTP_CONTENT_ENCODING']) ) {
182 $encoding = $_SERVER['HTTP_CONTENT_ENCODING'];
183 @dbg_error_log('caldav', 'Content-Encoding: %s', $encoding );
184 $encoding = preg_replace('{[^a-z0-9-]}i','',$encoding);
185 if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || isset($c->dbg['caldav'])) ) {
186 $fh = fopen('/var/log/davical/encoded_data.debug'.$encoding,'w');
187 if ( $fh ) {
188 fwrite($fh,$c->raw_post);
189 fclose($fh);
190 }
191 }
192 switch( $encoding ) {
193 case 'gzip':
194 $this->raw_post = @gzdecode($c->raw_post);
195 break;
196 case 'deflate':
197 $this->raw_post = @gzinflate($c->raw_post);
198 break;
199 case 'compress':
200 $this->raw_post = @gzuncompress($c->raw_post);
201 break;
202 default:
203 }
204 if ( empty($this->raw_post) && !empty($c->raw_post) ) {
205 $this->PreconditionFailed(415, 'content-encoding', sprintf('Unable to decode "%s" content encoding.', $_SERVER['HTTP_CONTENT_ENCODING']));
206 }
207 $c->raw_post = $this->raw_post;
208 }
209 else {
210 $this->raw_post = $c->raw_post;
211 }
212
213 if ( isset($debugging) && isset($_GET['method']) ) {
214 $_SERVER['REQUEST_METHOD'] = $_GET['method'];
215 }
216 else if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) ){
217 $_SERVER['REQUEST_METHOD'] = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
218 }
219 $this->method = $_SERVER['REQUEST_METHOD'];
220 if (isset($_SERVER['CONTENT_TYPE'])) {
221 $this->content_type = $_SERVER['CONTENT_TYPE'];
222 if ( preg_match( '{^(\S+/\S+?)\s*(;.*)?$}', $this->content_type, $matches ) ) {
223 $this->content_type = $matches[1];
224 }
225 } else {
226 $this->content_type = null;
227 }
228 if ( strlen($c->raw_post) > 0 ) {
229 if ( $this->method == 'PROPFIND' || $this->method == 'REPORT' || $this->method == 'PROPPATCH' || $this->method == 'BIND' || $this->method == 'MKTICKET' || $this->method == 'ACL' ) {
230 if ( !preg_match( '{^(text|application)/xml$}', $this->content_type ) ) {
231 @dbg_error_log( "LOG request", 'Request is "%s" but client set content-type to "%s". Assuming they meant XML!',
232 $this->method, $this->content_type );
233 $this->content_type = 'text/xml';
234 }
235 }
236 else if ( $this->method == 'PUT' || $this->method == 'POST' ) {
237 $this->CoerceContentType();
238 }
239 }
240 else {
241 $this->content_type = 'text/plain';
242 }
243 $this->user_agent = ((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "Probably Mulberry"));
244
248 if ( isset($_SERVER['HTTP_DEPTH']) ) {
249 $this->depth = $_SERVER['HTTP_DEPTH'];
250 }
251 else {
257 switch( $this->method ) {
258 case 'DELETE':
259 case 'MOVE':
260 case 'COPY':
261 case 'LOCK':
262 $this->depth = 'infinity';
263 break;
264
265 case 'REPORT':
266 $this->depth = 0;
267 break;
268
269 case 'PROPFIND':
270 default:
271 $this->depth = 0;
272 }
273 }
274 if ( !is_int($this->depth) && "infinity" == $this->depth ) $this->depth = DEPTH_INFINITY;
275 $this->depth = intval($this->depth);
276
280 if ( isset($_SERVER['HTTP_DESTINATION']) ) {
281 $this->destination = $_SERVER['HTTP_DESTINATION'];
282 if ( preg_match('{^(https?)://([a-z.-]+)(:[0-9]+)?(/.*)$}', $this->destination, $matches ) ) {
283 $this->destination = $matches[4];
284 }
285 }
286 $this->overwrite = ( isset($_SERVER['HTTP_OVERWRITE']) && ($_SERVER['HTTP_OVERWRITE'] == 'F') ? false : true ); // RFC4918, 9.8.4 says default True.
287
291 if ( isset($_SERVER['HTTP_IF']) ) $this->if_clause = $_SERVER['HTTP_IF'];
292 if ( isset($_SERVER['HTTP_LOCK_TOKEN']) && preg_match( '#[<]opaquelocktoken:(.*)[>]#', $_SERVER['HTTP_LOCK_TOKEN'], $matches ) ) {
293 $this->lock_token = $matches[1];
294 }
295
299 if ( isset($_GET['ticket']) ) {
300 $this->ticket = new DAVTicket($_GET['ticket']);
301 }
302 else if ( isset($_SERVER['HTTP_TICKET']) ) {
303 $this->ticket = new DAVTicket($_SERVER['HTTP_TICKET']);
304 }
305
309 if ( isset($_SERVER['HTTP_TIMEOUT']) ) {
310 $timeouts = explode( ',', $_SERVER['HTTP_TIMEOUT'] );
311 foreach( $timeouts AS $k => $v ) {
312 if ( strtolower($v) == 'infinite' ) {
313 $this->timeout = (isset($c->maximum_lock_timeout) ? $c->maximum_lock_timeout : 86400 * 100);
314 break;
315 }
316 elseif ( strtolower(substr($v,0,7)) == 'second-' ) {
317 $this->timeout = min( intval(substr($v,7)), (isset($c->maximum_lock_timeout) ? $c->maximum_lock_timeout : 86400 * 100) );
318 break;
319 }
320 }
321 if ( ! isset($this->timeout) || $this->timeout == 0 ) $this->timeout = (isset($c->default_lock_timeout) ? $c->default_lock_timeout : 900);
322 }
323
324 $this->principal = new Principal('path',$this->path);
325
337 $sql = "SELECT * FROM collection WHERE dav_name = :exact_name";
338 $params = array( ':exact_name' => $this->path );
339 if ( !preg_match( '#/$#', $this->path ) ) {
340 $sql .= " OR dav_name = :truncated_name OR dav_name = :trailing_slash_name";
341 $params[':truncated_name'] = preg_replace( '#[^/]*$#', '', $this->path);
342 $params[':trailing_slash_name'] = $this->path."/";
343 }
344 $sql .= " ORDER BY LENGTH(dav_name) DESC LIMIT 1";
345 $qry = new AwlQuery( $sql, $params );
346 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $qry->rows() == 1 && ($row = $qry->Fetch()) ) {
347 if ( $row->dav_name == $this->path."/" ) {
348 $this->path = $row->dav_name;
349 dbg_error_log( "caldav", "Path is actually a collection - sending Content-Location header." );
350 header( "Content-Location: ".ConstructURL($this->path) );
351 }
352
353 $this->collection_id = $row->collection_id;
354 $this->collection_path = $row->dav_name;
355 $this->collection_type = ($row->is_calendar == 't' ? 'calendar' : 'collection');
356 $this->collection = $row;
357 if ( preg_match( '#^((/[^/]+/)\.(in|out)/)[^/]*$#', $this->path, $matches ) ) {
358 $this->collection_type = 'schedule-'. $matches[3]. 'box';
359 }
360 $this->collection->type = $this->collection_type;
361 }
362 else if ( preg_match( '{^( ( / ([^/]+) / ) \.(in|out)/ ) [^/]*$}x', $this->path, $matches ) ) {
363 // The request is for a scheduling inbox or outbox (or something inside one) and we should auto-create it
364 $params = array( ':username' => $matches[3], ':parent_container' => $matches[2], ':dav_name' => $matches[1] );
365 $params[':boxname'] = ($matches[4] == 'in' ? ' Inbox' : ' Outbox');
366 $this->collection_type = 'schedule-'. $matches[4]. 'box';
367 $params[':resourcetypes'] = sprintf('<DAV::collection/><urn:ietf:params:xml:ns:caldav:%s/>', $this->collection_type );
368 $sql = <<<EOSQL
369INSERT INTO collection ( user_no, parent_container, dav_name, dav_displayname, is_calendar, created, modified, dav_etag, resourcetypes )
370 VALUES( (SELECT user_no FROM usr WHERE username = text(:username)),
371 :parent_container, :dav_name,
372 (SELECT fullname FROM usr WHERE username = text(:username)) || :boxname,
373 FALSE, current_timestamp, current_timestamp, '1', :resourcetypes )
374EOSQL;
375
376 $qry = new AwlQuery( $sql, $params );
377 $qry->Exec('caldav',__LINE__,__FILE__);
378 dbg_error_log( 'caldav', 'Created new collection as "%s".', trim($params[':boxname']) );
379
380 // Uncache anything to do with the collection
381 $cache = getCacheInstance();
382 $cache->delete( 'collection-'.$params[':dav_name'], null );
383 $cache->delete( 'principal-'.$params[':parent_container'], null );
384
385 $qry = new AwlQuery( "SELECT * FROM collection WHERE dav_name = :dav_name", array( ':dav_name' => $matches[1] ) );
386 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $qry->rows() == 1 && ($row = $qry->Fetch()) ) {
387 $this->collection_id = $row->collection_id;
388 $this->collection_path = $matches[1];
389 $this->collection = $row;
390 $this->collection->type = $this->collection_type;
391 }
392 }
393 else if ( preg_match( '#^((/[^/]+/)calendar-proxy-(read|write))/?[^/]*$#', $this->path, $matches ) ) {
394 $this->collection_type = 'proxy';
395 $this->_is_proxy_request = true;
396 $this->proxy_type = $matches[3];
397 $this->collection_path = $matches[1].'/'; // Enforce trailling '/'
398 if ( $this->collection_path == $this->path."/" ) {
399 $this->path .= '/';
400 dbg_error_log( "caldav", "Path is actually a (proxy) collection - sending Content-Location header." );
401 header( "Content-Location: ".ConstructURL($this->path) );
402 }
403 }
404 else if ( $this->options['allow_by_email'] && preg_match( '#^/(\S+@\S+[.]\S+)/?$#', $this->path) ) {
406 $this->collection_id = -1;
407 $this->collection_type = 'email';
408 $this->collection_path = $this->path;
409 $this->_is_principal = true;
410 }
411 else if ( preg_match( '#^(/[^/?]+)/?$#', $this->path, $matches) || preg_match( '#^(/principals/[^/]+/[^/]+)/?$#', $this->path, $matches) ) {
412 $this->collection_id = -1;
413 $this->collection_path = $matches[1].'/'; // Enforce trailling '/'
414 $this->collection_type = 'principal';
415 $this->_is_principal = true;
416 if ( $this->collection_path == $this->path."/" ) {
417 $this->path .= '/';
418 dbg_error_log( "caldav", "Path is actually a collection - sending Content-Location header." );
419 header( "Content-Location: ".ConstructURL($this->path) );
420 }
421 if ( preg_match( '#^(/principals/[^/]+/[^/]+)/?$#', $this->path, $matches) ) {
422 // Force a depth of 0 on these, which are at the wrong URL.
423 $this->depth = 0;
424 }
425 }
426 else if ( $this->path == '/' ) {
427 $this->collection_id = -1;
428 $this->collection_path = '/';
429 $this->collection_type = 'root';
430 }
431
432 if ( $this->collection_path == $this->path ) $this->_is_collection = true;
433 dbg_error_log( "caldav", " Collection '%s' is %d, type %s", $this->collection_path, $this->collection_id, $this->collection_type );
434
438 $this->principal = new DAVPrincipal( array( "path" => $this->path, "options" => $this->options ) );
439 $this->user_no = $this->principal->user_no();
440 $this->username = $this->principal->username();
441 $this->by_email = $this->principal->byEmail();
442 $this->principal_id = $this->principal->principal_id();
443
444 if ( $this->collection_type == 'principal' || $this->collection_type == 'email' || $this->collection_type == 'proxy' ) {
445 $this->collection = $this->principal->AsCollection();
446 if( $this->collection_type == 'proxy' ) {
447 $this->collection->is_proxy = 't';
448 $this->collection->type = 'proxy';
449 $this->collection->proxy_type = $this->proxy_type;
450 $this->collection->dav_displayname = sprintf('Proxy %s for %s', $this->proxy_type, $this->principal->username() );
451 }
452 }
453 elseif( $this->collection_type == 'root' ) {
454 $this->collection = (object) array(
455 'collection_id' => 0,
456 'dav_name' => '/',
457 'dav_etag' => md5($c->system_name),
458 'is_calendar' => 'f',
459 'is_addressbook' => 'f',
460 'is_principal' => 'f',
461 'user_no' => 0,
462 'dav_displayname' => $c->system_name,
463 'type' => 'root',
464 'created' => date('Ymd\THis')
465 );
466 }
467
471 $this->setPermissions();
472
473
478 if ( isset($this->content_type) && preg_match( '#(application|text)/xml#', $this->content_type ) ) {
479 if ( !isset($this->raw_post) || $this->raw_post == '' ) {
480 $this->XMLResponse( 400, new XMLElement( 'error', new XMLElement('missing-xml'), array( 'xmlns' => 'DAV:') ) );
481 }
482 $xml_parser = xml_parser_create_ns('UTF-8');
483 $this->xml_tags = array();
484 xml_parser_set_option ( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
485 xml_parser_set_option ( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
486 $rc = xml_parse_into_struct( $xml_parser, $this->raw_post, $this->xml_tags );
487 if ( $rc == false ) {
488 dbg_error_log( 'ERROR', 'XML parsing error: %s at line %d, column %d',
489 xml_error_string(xml_get_error_code($xml_parser)),
490 xml_get_current_line_number($xml_parser), xml_get_current_column_number($xml_parser) );
491 $this->XMLResponse( 400, new XMLElement( 'error', new XMLElement('invalid-xml'), array( 'xmlns' => 'DAV:') ) );
492 }
493 xml_parser_free($xml_parser);
494 if ( count($this->xml_tags) ) {
495 dbg_error_log( "caldav", " Parsed incoming XML request body." );
496 }
497 else {
498 $this->xml_tags = null;
499 dbg_error_log( "ERROR", "Incoming request sent content-type XML with no XML request body." );
500 }
501 }
502
506 if ( isset($_SERVER["HTTP_IF_NONE_MATCH"]) ) {
507 $this->etag_none_match = $_SERVER["HTTP_IF_NONE_MATCH"];
508 if ( $this->etag_none_match == '' ) unset($this->etag_none_match);
509 }
510 if ( isset($_SERVER["HTTP_IF_MATCH"]) ) {
511 $this->etag_if_match = $_SERVER["HTTP_IF_MATCH"];
512 if ( $this->etag_if_match == '' ) unset($this->etag_if_match);
513 }
514 }
515
516
529 function setPermissions() {
530 global $c, $session;
531
532 if ( $this->path == '/' || $this->path == '' ) {
533 $this->privileges = privilege_to_bits( array('read','read-free-busy','read-acl'));
534 dbg_error_log( "caldav", "Full read permissions for user accessing /" );
535 }
536 else if ( $session->AllowedTo("Admin") || $session->principal->user_no() == $this->user_no ) {
537 $this->privileges = privilege_to_bits('all');
538 dbg_error_log( "caldav", "Full permissions for %s", ( $session->principal->user_no() == $this->user_no ? "user accessing their own hierarchy" : "a systems administrator") );
539 }
540 else {
541 $this->privileges = 0;
542 if ( $this->IsPublic() ) {
543 $this->privileges = privilege_to_bits(array('read','read-free-busy'));
544 dbg_error_log( "caldav", "Basic read permissions for user accessing a public collection" );
545 }
546 else if ( isset($c->public_freebusy_url) && $c->public_freebusy_url ) {
547 $this->privileges = privilege_to_bits('read-free-busy');
548 dbg_error_log( "caldav", "Basic free/busy permissions for user accessing a public free/busy URL" );
549 }
550
554 $params = array( ':session_principal_id' => $session->principal->principal_id(), ':scan_depth' => $c->permission_scan_depth );
555 if ( isset($this->by_email) && $this->by_email ) {
556 $sql ='SELECT pprivs( :session_principal_id::int8, :request_principal_id::int8, :scan_depth::int ) AS perm';
557 $params[':request_principal_id'] = $this->principal_id;
558 }
559 else {
560 $sql = 'SELECT path_privs( :session_principal_id::int8, :request_path::text, :scan_depth::int ) AS perm';
561 $params[':request_path'] = $this->path;
562 }
563 $qry = new AwlQuery( $sql, $params );
564 if ( $qry->Exec('caldav',__LINE__,__FILE__) && $permission_result = $qry->Fetch() ) {
565 $perm = $permission_result->perm;
566 if (isset($perm)) $this->privileges |= bindec($permission_result->perm);
567 }
568
569 dbg_error_log( 'caldav', 'Restricted permissions for user accessing someone elses hierarchy: %s', decbin($this->privileges) );
570 if ( isset($this->ticket) && $this->ticket->MatchesPath($this->path) ) {
571 $this->privileges |= $this->ticket->privileges();
572 dbg_error_log( 'caldav', 'Applying permissions for ticket "%s" now: %s', $this->ticket->id(), decbin($this->privileges) );
573 }
574 }
575
577 $this->permissions = array();
578 $privs = bits_to_privilege($this->privileges);
579 foreach( $privs AS $k => $v ) {
580 switch( $v ) {
581 case 'DAV::all': $type = 'abstract'; break;
582 case 'DAV::write': $type = 'aggregate'; break;
583 default: $type = 'real';
584 }
585 $v = str_replace('DAV::', '', $v);
586 $this->permissions[$v] = $type;
587 }
588
589 }
590
591
599 function IsLocked() {
600 if ( !isset($this->_locks_found) ) {
601 $this->_locks_found = array();
602
603 $sql = 'DELETE FROM locks WHERE (start + timeout) < current_timestamp';
604 $qry = new AwlQuery($sql);
605 $qry->Exec('caldav',__LINE__,__FILE__);
606
610 $sql = 'SELECT * FROM locks WHERE :dav_name::text ~ (\'^\'||dav_name||:pattern_end_match)::text';
611 $qry = new AwlQuery($sql, array( ':dav_name' => $this->path, ':pattern_end_match' => ($this->IsInfiniteDepth() ? '' : '$') ) );
612 if ( $qry->Exec('caldav',__LINE__,__FILE__) ) {
613 while( $lock_row = $qry->Fetch() ) {
614 $this->_locks_found[$lock_row->opaquelocktoken] = $lock_row;
615 }
616 }
617 else {
618 $this->DoResponse(500,translate("Database Error"));
619 // Does not return.
620 }
621 }
622
623 foreach( $this->_locks_found AS $lock_token => $lock_row ) {
624 if ( $lock_row->depth == DEPTH_INFINITY || $lock_row->dav_name == $this->path ) {
625 return $lock_token;
626 }
627 }
628
629 return false; // Nothing matched
630 }
631
632
636 function IsPublic() {
637 if ( isset($this->collection) && isset($this->collection->publicly_readable) && $this->collection->publicly_readable == 't' ) {
638 return true;
639 }
640 return false;
641 }
642
643
644 private static function supportedPrivileges() {
645 return array(
646 'all' => array(
647 'read' => translate('Read the content of a resource or collection'),
648 'write' => array(
649 'bind' => translate('Create a resource or collection'),
650 'unbind' => translate('Delete a resource or collection'),
651 'write-content' => translate('Write content'),
652 'write-properties' => translate('Write properties')
653 ),
654 'urn:ietf:params:xml:ns:caldav:read-free-busy' => translate('Read the free/busy information for a calendar collection'),
655 'read-acl' => translate('Read ACLs for a resource or collection'),
656 'read-current-user-privilege-set' => translate('Read the details of the current user\'s access control to this resource.'),
657 'write-acl' => translate('Write ACLs for a resource or collection'),
658 'unlock' => translate('Remove a lock'),
659
660 'urn:ietf:params:xml:ns:caldav:schedule-deliver' => array(
661 'urn:ietf:params:xml:ns:caldav:schedule-deliver-invite'=> translate('Deliver scheduling invitations from an organiser to this scheduling inbox'),
662 'urn:ietf:params:xml:ns:caldav:schedule-deliver-reply' => translate('Deliver scheduling replies from an attendee to this scheduling inbox'),
663 'urn:ietf:params:xml:ns:caldav:schedule-query-freebusy' => translate('Allow free/busy enquiries targeted at the owner of this scheduling inbox')
664 ),
665
666 'urn:ietf:params:xml:ns:caldav:schedule-send' => array(
667 'urn:ietf:params:xml:ns:caldav:schedule-send-invite' => translate('Send scheduling invitations as an organiser from the owner of this scheduling outbox.'),
668 'urn:ietf:params:xml:ns:caldav:schedule-send-reply' => translate('Send scheduling replies as an attendee from the owner of this scheduling outbox.'),
669 'urn:ietf:params:xml:ns:caldav:schedule-send-freebusy' => translate('Send free/busy enquiries')
670 )
671 )
672 );
673 }
674
678 function dav_name() {
679 if ( isset($this->path) ) return $this->path;
680 return null;
681 }
682
683
687 function GetDepthName( ) {
688 if ( $this->IsInfiniteDepth() ) return 'infinity';
689 return $this->depth;
690 }
691
696 function DepthRegexTail( $for_collection_report = false) {
697 if ( $this->IsInfiniteDepth() ) return '';
698 if ( $this->depth == 0 && $for_collection_report ) return '[^/]+$';
699 if ( $this->depth == 0 ) return '$';
700 return '[^/]*/?$';
701 }
702
708 function GetLockRow( $lock_token ) {
709 if ( isset($this->_locks_found) && isset($this->_locks_found[$lock_token]) ) {
710 return $this->_locks_found[$lock_token];
711 }
712
713 $qry = new AwlQuery('SELECT * FROM locks WHERE opaquelocktoken = :lock_token', array( ':lock_token' => $lock_token ) );
714 if ( $qry->Exec('caldav',__LINE__,__FILE__) ) {
715 $lock_row = $qry->Fetch();
716 $this->_locks_found = array( $lock_token => $lock_row );
717 return $this->_locks_found[$lock_token];
718 }
719 else {
720 $this->DoResponse( 500, translate("Database Error") );
721 }
722
723 return false; // Nothing matched
724 }
725
726
733 function ValidateLockToken( $lock_token ) {
734 if ( isset($this->lock_token) && $this->lock_token == $lock_token ) {
735 dbg_error_log( "caldav", "They supplied a valid lock token. Great!" );
736 return true;
737 }
738 if ( isset($this->if_clause) ) {
739 dbg_error_log( "caldav", "Checking lock token '%s' against '%s'", $lock_token, $this->if_clause );
740 $tokens = preg_split( '/[<>]/', $this->if_clause );
741 foreach( $tokens AS $k => $v ) {
742 dbg_error_log( "caldav", "Checking lock token '%s' against '%s'", $lock_token, $v );
743 if ( 'opaquelocktoken:' == substr( $v, 0, 16 ) ) {
744 if ( substr( $v, 16 ) == $lock_token ) {
745 dbg_error_log( "caldav", "Lock token '%s' validated OK against '%s'", $lock_token, $v );
746 return true;
747 }
748 }
749 }
750 }
751 else {
752 @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 );
753 }
754
755 return false;
756 }
757
758
764 function GetLockDetails( $lock_token ) {
765 if ( !isset($this->_locks_found) && false === $this->IsLocked() ) return false;
766 if ( isset($this->_locks_found[$lock_token]) ) return $this->_locks_found[$lock_token];
767 return false;
768 }
769
770
778 function FailIfLocked() {
779 if ( $existing_lock = $this->IsLocked() ) { // NOTE Assignment in if() is expected here.
780 dbg_error_log( "caldav", "There is a lock on '%s'", $this->path);
781 if ( ! $this->ValidateLockToken($existing_lock) ) {
782 $lock_row = $this->GetLockRow($existing_lock);
786 $response[] = new XMLElement( 'response', array(
787 new XMLElement( 'href', $lock_row->dav_name ),
788 new XMLElement( 'status', 'HTTP/1.1 423 Resource Locked')
789 ));
790 if ( $lock_row->dav_name != $this->path ) {
791 $response[] = new XMLElement( 'response', array(
792 new XMLElement( 'href', $this->path ),
793 new XMLElement( 'propstat', array(
794 new XMLElement( 'prop', new XMLElement( 'lockdiscovery' ) ),
795 new XMLElement( 'status', 'HTTP/1.1 424 Failed Dependency')
796 ))
797 ));
798 }
799 $response = new XMLElement( "multistatus", $response, array('xmlns'=>'DAV:') );
800 $xmldoc = $response->Render(0,'<?xml version="1.0" encoding="utf-8" ?>');
801 $this->DoResponse( 207, $xmldoc, 'text/xml; charset="utf-8"' );
802 // Which we won't come back from
803 }
804 return $existing_lock;
805 }
806 return false;
807 }
808
809
813 function CoerceContentType() {
814 if ( isset($this->content_type) ) {
815 $type = explode( '/', $this->content_type, 2);
817 if ( $type[0] == 'text' ) {
818 if ( !empty($type[1]) && ($type[1] == 'vcard' || $type[1] == 'calendar' || $type[1] == 'x-vcard') ) {
819 return;
820 }
821 }
822 }
823
825 $first_word = trim(substr( $this->raw_post, 0, 30));
826 $first_word = strtoupper( preg_replace( '/\s.*/s', '', $first_word ) );
827 switch( $first_word ) {
828 case '<?XML':
829 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/xml"',
830 (isset($this->content_type)?$this->content_type:'(null)') );
831 $this->content_type = 'text/xml';
832 break;
833 case 'BEGIN:VCALENDAR':
834 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/calendar"',
835 (isset($this->content_type)?$this->content_type:'(null)') );
836 $this->content_type = 'text/calendar';
837 break;
838 case 'BEGIN:VCARD':
839 dbg_error_log( 'LOG WARNING', 'Application sent content-type of "%s" instead of "text/vcard"',
840 (isset($this->content_type)?$this->content_type:'(null)') );
841 $this->content_type = 'text/vcard';
842 break;
843 default:
844 dbg_error_log( 'LOG NOTICE', 'Unusual content-type of "%s" and first word of content is "%s"',
845 (isset($this->content_type)?$this->content_type:'(null)'), $first_word );
846 }
847 if ( empty($this->content_type) ) $this->content_type = 'text/plain';
848 }
849
850
854 function PreferMinimal() {
855 if ( empty($this->prefer) ) return false;
856 foreach( $this->prefer AS $v ) {
857 if ( $v == 'return=minimal' ) return true;
858 if ( $v == 'return-minimal' ) return true; // RFC7240 up until draft -15 (Oct 2012)
859 }
860 return false;
861 }
862
866 function IsCollection( ) {
867 if ( !isset($this->_is_collection) ) {
868 $this->_is_collection = preg_match( '#/$#', $this->path );
869 }
870 return $this->_is_collection;
871 }
872
873
877 function IsCalendar( ) {
878 if ( !$this->IsCollection() || !isset($this->collection) ) return false;
879 return $this->collection->is_calendar == 't';
880 }
881
882
886 function IsAddressBook( ) {
887 if ( !$this->IsCollection() || !isset($this->collection) ) return false;
888 return $this->collection->is_addressbook == 't';
889 }
890
891
895 function IsPrincipal( ) {
896 if ( !isset($this->_is_principal) ) {
897 $this->_is_principal = preg_match( '#^/[^/]+/$#', $this->path );
898 }
899 return $this->_is_principal;
900 }
901
902
906 function IsProxyRequest( ) {
907 if ( !isset($this->_is_proxy_request) ) {
908 $this->_is_proxy_request = preg_match( '#^/[^/]+/calendar-proxy-(read|write)/?[^/]*$#', $this->path );
909 }
910 return $this->_is_proxy_request;
911 }
912
913
917 function IsInfiniteDepth( ) {
918 return ($this->depth == DEPTH_INFINITY);
919 }
920
921
925 function CollectionId( ) {
927 }
928
929
933 function BuildSupportedPrivileges( &$reply, $privs = null ) {
934 $privileges = array();
935 if ( $privs === null ) $privs = self::supportedPrivileges();
936 foreach( $privs AS $k => $v ) {
937 dbg_error_log( 'caldav', 'Adding privilege "%s" which is "%s".', $k, $v );
938 $privilege = new XMLElement('privilege');
939 $reply->NSElement($privilege,$k);
940 $privset = array($privilege);
941 if ( is_array($v) ) {
942 dbg_error_log( 'caldav', '"%s" is a container of sub-privileges.', $k );
943 $privset = array_merge($privset, $this->BuildSupportedPrivileges($reply,$v));
944 }
945 else if ( $v == 'abstract' ) {
946 dbg_error_log( 'caldav', '"%s" is an abstract privilege.', $v );
947 $privset[] = new XMLElement('abstract');
948 }
949 else if ( strlen($v) > 1 ) {
950 $privset[] = new XMLElement('description', $v);
951 }
952 $privileges[] = new XMLElement('supported-privilege',$privset);
953 }
954 return $privileges;
955 }
956
957
971 function AllowedTo( $activity ) {
972 global $session;
973 dbg_error_log('caldav', 'Checking whether "%s" is allowed to "%s"', $session->principal->username(), $activity);
974 if ( isset($this->permissions['all']) ) return true;
975 switch( $activity ) {
976 case 'all':
977 return false; // If they got this far then they don't
978 break;
979
980 case "CALDAV:schedule-send-freebusy":
981 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
982 break;
983
984 case "CALDAV:schedule-send-invite":
985 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
986 break;
987
988 case "CALDAV:schedule-send-reply":
989 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
990 break;
991
992 case 'freebusy':
993 return isset($this->permissions['read']) || isset($this->permissions['urn:ietf:params:xml:ns:caldav:read-free-busy']);
994 break;
995
996 case 'delete':
997 return isset($this->permissions['write']) || isset($this->permissions['unbind']);
998 break;
999
1000 case 'proppatch':
1001 return isset($this->permissions['write']) || isset($this->permissions['write-properties']);
1002 break;
1003
1004 case 'modify':
1005 return isset($this->permissions['write']) || isset($this->permissions['write-content']);
1006 break;
1007
1008 case 'create':
1009 return isset($this->permissions['write']) || isset($this->permissions['bind']);
1010 break;
1011
1012 case 'mkcalendar':
1013 case 'mkcol':
1014 if ( !isset($this->permissions['write']) || !isset($this->permissions['bind']) ) return false;
1015 if ( $this->is_principal ) return false;
1016 if ( $this->path == '/' ) return false;
1017 break;
1018
1019 default:
1020 $test_bits = privilege_to_bits( $activity );
1021// dbg_error_log( 'caldav', 'request::AllowedTo("%s") (%s) against allowed "%s" => "%s" (%s)',
1022// (is_array($activity) ? implode(',',$activity) : $activity), decbin($test_bits),
1023// decbin($this->privileges), ($this->privileges & $test_bits), decbin($this->privileges & $test_bits) );
1024 return (($this->privileges & $test_bits) > 0 );
1025 break;
1026 }
1027
1028 return false;
1029 }
1030
1031
1032
1036 function Privileges() {
1037 return $this->privileges;
1038 }
1039
1040
1047 function CheckEtagMatch( $exists, $dest_etag ) {
1048 global $c;
1049
1050 if ( ! $exists ) {
1051 if ( (isset($this->etag_if_match) && $this->etag_if_match != '') ) {
1058 $this->PreconditionFailed(412, 'if-match', translate('No resource exists at the destination.'));
1059 }
1060 }
1061 else {
1062
1063 if ( isset($c->strict_etag_checking) && $c->strict_etag_checking )
1064 $trim_chars = '\'\\" ';
1065 else
1066 $trim_chars = ' ';
1067
1068 if ( isset($this->etag_if_match) && $this->etag_if_match != '' && $this->etag_if_match != '*'
1069 && trim( $this->etag_if_match, $trim_chars) != trim( $dest_etag, $trim_chars ) ) {
1076 $this->PreconditionFailed(412,'if-match',sprintf('Existing resource ETag of %s does not match %s', $dest_etag, $this->etag_if_match) );
1077 }
1078 else if ( isset($this->etag_none_match) && $this->etag_none_match != ''
1079 && ($this->etag_none_match == $dest_etag || $this->etag_none_match == '*') ) {
1088 $this->PreconditionFailed(412,'if-none-match', translate( 'Existing resource matches "If-None-Match" header - not accepted.'));
1089 }
1090 }
1091
1092 }
1093
1094
1098 function HavePrivilegeTo( $do_what ) {
1099 $test_bits = privilege_to_bits( $do_what );
1100// dbg_error_log( 'caldav', 'request::HavePrivilegeTo("%s") [%s] against allowed "%s" => "%s" (%s)',
1101// (is_array($do_what) ? implode(',',$do_what) : $do_what), decbin($test_bits),
1102// decbin($this->privileges), ($this->privileges & $test_bits), decbin($this->privileges & $test_bits) );
1103 return ($this->privileges & $test_bits) > 0;
1104 }
1105
1106
1111 function UnsupportedRequest( $unsupported ) {
1112 if ( isset($unsupported) && count($unsupported) > 0 ) {
1113 $badprops = new XMLElement( "prop" );
1114 foreach( $unsupported AS $k => $v ) {
1115 // Not supported at this point...
1116 dbg_error_log("ERROR", " %s: Support for $v:$k properties is not implemented yet", $this->method );
1117 $badprops->NewElement(strtolower($k),false,array("xmlns" => strtolower($v)));
1118 }
1119 $error = new XMLElement("error", $badprops, array("xmlns" => "DAV:") );
1120
1121 $this->XMLResponse( 422, $error );
1122 }
1123 }
1124
1125
1134 function NeedPrivilege( $privileges, $href=null ) {
1135 if ( is_string($privileges) ) $privileges = array( $privileges );
1136 if ( !isset($href) ) {
1137 if ( $this->HavePrivilegeTo($privileges) ) return;
1138 $href = $this->path;
1139 }
1140
1141 $reply = new XMLDocument( array('DAV:' => '') );
1142 $privnodes = array( $reply->href(ConstructURL($href)), new XMLElement( 'privilege' ) );
1143 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
1144 $reply->NSElement( $privnodes[1], $privileges[0] );
1145 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
1146 $xmldoc = $reply->Render('error',$xml);
1147 $this->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
1148 exit(0); // Unecessary, but might clarify things
1149 }
1150
1151
1159 function PreconditionFailed( $status, $precondition, $explanation = '', $xmlns='DAV:') {
1160 $xmldoc = sprintf('<?xml version="1.0" encoding="utf-8" ?>
1161<error xmlns="%s">
1162 <%s/>%s
1163</error>', $xmlns, str_replace($xmlns.':', '', $precondition), $explanation );
1164
1165 $this->DoResponse( $status, $xmldoc, 'text/xml; charset="utf-8"' );
1166 exit(0); // Unecessary, but might clarify things
1167 }
1168
1169
1175 function MalformedRequest( $text = 'Bad request' ) {
1176 $this->DoResponse( 400, $text );
1177 exit(0); // Unecessary, but might clarify things
1178 }
1179
1180
1187 function XMLResponse( $status, $xmltree ) {
1188 $xmldoc = $xmltree->Render(0,'<?xml version="1.0" encoding="utf-8" ?>');
1189 $etag = md5($xmldoc);
1190 if ( !headers_sent() ) header("ETag: \"$etag\"");
1191 $this->DoResponse( $status, $xmldoc, 'text/xml; charset="utf-8"' );
1192 exit(0); // Unecessary, but might clarify things
1193 }
1194
1195 public static function kill_on_exit() {
1196 posix_kill( getmypid(), 28 );
1197 }
1198
1206 function DoResponse( $status, $message="", $content_type="text/plain; charset=\"utf-8\"" ) {
1207 global $session, $c;
1208 if ( !headers_sent() ) @header( sprintf("HTTP/1.1 %d %s", $status, getStatusMessage($status)) );
1209 if ( !headers_sent() ) @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) );
1210 if ( !headers_sent() ) header( "Content-type: ".$content_type );
1211
1212 if ( (isset($c->dbg['ALL']) && $c->dbg['ALL']) || (isset($c->dbg['response']) && $c->dbg['response'])
1213 || $status == 400 || $status == 402 || $status == 403 || $status > 404 ) {
1214 @dbg_error_log( "LOG ", 'Response status %03d for %s %s', $status, $this->method, $_SERVER['REQUEST_URI'] );
1215 $lines = headers_list();
1216 dbg_error_log( "LOG ", "***************** Response Header ****************" );
1217 foreach( $lines AS $v ) {
1218 dbg_error_log( "LOG headers", "-->%s", $v );
1219 }
1220 dbg_error_log( "LOG ", "******************** Response ********************" );
1221 // Log the request in all it's gory detail.
1222 $lines = preg_split( '#[\r\n]+#', $message);
1223 foreach( $lines AS $v ) {
1224 dbg_error_log( "LOG response", "-->%s", $v );
1225 }
1226 }
1227
1228 $script_finish = microtime(true);
1229 $script_time = $script_finish - $c->script_start_time;
1230 $message_length = strlen($message);
1231 if ( $message != '' ) {
1232 if ( !headers_sent() ) header( "Content-Length: ".$message_length );
1233 echo $message;
1234 }
1235
1236 if ( isset($c->dbg['caldav']) && $c->dbg['caldav'] ) {
1237 if ( $message_length > 100 || strstr($message, "\n") ) {
1238 $message = substr( preg_replace("#\s+#m", ' ', $message ), 0, 100) . ($message_length > 100 ? "..." : "");
1239 }
1240
1241 dbg_error_log("caldav", "Status: %d, Message: %s, User: %d, Path: %s", $status, $message, $session->principal->user_no(), $this->path);
1242 }
1243 if ( isset($c->dbg['statistics']) && $c->dbg['statistics'] ) {
1244 $memory = '';
1245 if ( function_exists('memory_get_usage') ) {
1246 $memory = sprintf( ', Memory: %dk, Peak: %dk', memory_get_usage()/1024, memory_get_peak_usage(true)/1024);
1247 }
1248 @dbg_error_log("statistics", "Method: %s, Status: %d, Script: %5.3lfs, Queries: %5.3lfs, URL: %s%s",
1249 $this->method, $status, $script_time, $c->total_query_time, $this->path, $memory);
1250 }
1251 try {
1252 @ob_flush(); // Seems like it should be better to do the following but is problematic on PHP5.3 at least: while ( ob_get_level() > 0 ) ob_end_flush();
1253 }
1254 catch( Exception $ignored ) {}
1255
1256 if ( isset($c->metrics_style) && $c->metrics_style !== false ) {
1257 $flush_time = microtime(true) - $script_finish;
1258 $this->DoMetrics($status, $message_length, $script_time, $flush_time);
1259 }
1260
1261 if ( isset($c->exit_after_memory_exceeds) && function_exists('memory_get_peak_usage') && memory_get_peak_usage(true) > $c->exit_after_memory_exceeds ) { // 64M
1262 @dbg_error_log("statistics", "Peak memory use exceeds %d bytes (%d) - killing process %d", $c->exit_after_memory_exceeds, memory_get_peak_usage(true), getmypid());
1263 register_shutdown_function( 'CalDAVRequest::kill_on_exit' );
1264 }
1265
1266 exit(0);
1267 }
1268
1269
1278 function DoMetrics($status, $response_size, $script_time, $flush_time) {
1279 global $c;
1280 static $ns = 'metrics';
1281
1282 $method = (empty($this->method) ? 'UNKNOWN' : $this->method);
1283
1284 // If they want 'both' or 'all' or something then that's what they will get
1285 // If they don't want counters, they must want to use memcache!
1286 if ( $c->metrics_style != 'counters' ) {
1287 $cache = getCacheInstance();
1288 if ( $cache->isActive() ) {
1289
1290 $base_key = $method.':';
1291 $count_like_this = $cache->increment( $ns, $base_key.$status );
1292 $cache->increment( $ns, $base_key.'size', $response_size );
1293 $cache->increment( $ns, $base_key.'script_time', intval($script_time * 1000000) );
1294 $cache->increment( $ns, $base_key.'flush_time', intval($flush_time * 1000000) );
1295 $cache->increment( $ns, $base_key.'query_time', intval($c->total_query_time * 1000000) );
1296
1297 if ( $count_like_this == 1 ) {
1298 // We need to maintain a set of details regarding the methods and statuses we have
1299 // encountered, so we know what to retrieve. Since this is the first one like
1300 // this, we add it to the index.
1301 try {
1302 $index = unserialize($cache->get($ns, 'index'));
1303 } catch (Exception $e) {
1304 $index = array('methods' => array(), 'statuses' => array());
1305 }
1306 $index['methods'][$method] = 1;
1307 $index['statuses'][$status] = 1;
1308 $cache->set($ns, 'index', serialize($index), 0);
1309 }
1310 }
1311 else {
1312 error_log("Full statistics are only available with a working Memcache configuration");
1313 }
1314 }
1315
1316 // If they don't want memcache, they must want to use counters!
1317 if ( $c->metrics_style != 'memcache' ) {
1318 $qstring = "SELECT nextval('%s')";
1319 switch( $method ) {
1320 case 'OPTIONS':
1321 case 'REPORT':
1322 case 'PROPFIND':
1323 case 'GET':
1324 case 'PUT':
1325 case 'HEAD':
1326 case 'PROPPATCH':
1327 case 'POST':
1328 case 'MKCALENDAR':
1329 case 'MKCOL':
1330 case 'DELETE':
1331 case 'MOVE':
1332 case 'ACL':
1333 case 'LOCK':
1334 case 'UNLOCK':
1335 case 'MKTICKET':
1336 case 'DELTICKET':
1337 case 'BIND':
1338 $counter = strtolower($this->method);
1339 break;
1340 default:
1341 $counter = 'unknown';
1342 break;
1343 }
1344 $qry = new AwlQuery( "SELECT nextval('metrics_count_" . $counter . "')" );
1345 $qry->Exec('always',__LINE__,__FILE__);
1346 }
1347 }
1348}
1349
GetLockDetails( $lock_token)
__construct( $options=array())
DepthRegexTail( $for_collection_report=false)
CheckEtagMatch( $exists, $dest_etag)
DoMetrics($status, $response_size, $script_time, $flush_time)
ValidateLockToken( $lock_token)
GetLockRow( $lock_token)
XMLResponse( $status, $xmltree)
PreconditionFailed( $status, $precondition, $explanation='', $xmlns='DAV:')
BuildSupportedPrivileges(&$reply, $privs=null)
AllowedTo( $activity)
DoResponse( $status, $message="", $content_type="text/plain; charset=\"utf-8\"")