DAViCal
Loading...
Searching...
No Matches
caldav-REPORT-calquery.php
1<?php
2
3include_once('vCalendar.php');
4
8$qry_content = $xmltree->GetContent('urn:ietf:params:xml:ns:caldav:calendar-query');
9
10$properties = array();
11$include_properties = array();
12$need_expansion = false;
13foreach ($qry_content as $idx => $qqq)
14{
15 $proptype = $qry_content[$idx]->GetNSTag();
16 switch( $proptype ) {
17 case 'DAV::prop':
18 $qry_props = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/'.$proptype.'/*');
19 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
20 $propertyname = $v->GetNSTag();
21 $properties[$propertyname] = 1;
22 if ( $propertyname == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
23 }
24 break;
25
26 case 'DAV::allprop':
27 $properties['DAV::allprop'] = 1;
28 if ( $qry_content[$idx]->GetNSTag() == 'DAV::include' ) {
29 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
30 $include_properties[] = $v->GetNSTag();
31 if ( $v->GetNSTag() == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
32 }
33 }
34 break;
35 }
36}
37if ( empty($properties) ) $properties['DAV::allprop'] = 1;
38
39
45$qry_filters = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/urn:ietf:params:xml:ns:caldav:filter/*');
46if ( count($qry_filters) != 1 ) $qry_filters = false;
47
48
58function calquery_apply_filter( $filters, $item ) {
59 global $session, $c, $request;
60
61 if ( count($filters) == 0 ) return true;
62
63 dbg_error_log("calquery","Applying filter for item '%s'", $item->dav_name );
64 $ical = new vCalendar( $item->caldav_data );
65 return $ical->StartFilter($filters);
66}
67
68
72$need_post_filter = false;
73$range_filter = null;
74$parameter_match_num = 0;
75function SqlFilterFragment( $filter, $components, $property = null, $parameter = null) {
76 global $need_post_filter, $range_filter, $target_collection, $parameter_match_num;
77 $sql = "";
78 $params = array();
79 global $expand_range_start, $expand_range_end, $expand_as_floating;
80 if ( !is_array($filter) ) {
81 dbg_error_log( "calquery", "Filter is of type '%s', but should be an array of XML Tags.", gettype($filter) );
82 }
83
84 foreach( $filter AS $k => $v ) {
85 $tag = $v->GetNSTag();
86 dbg_error_log("calquery", "Processing $tag into SQL - %d, '%s', %d\n", count($components), $property, isset($parameter) );
87
88 $not_defined = "";
89 $not_defined_log = "";
90 switch( $tag ) {
91 case 'urn:ietf:params:xml:ns:caldav:is-not-defined':
92 $not_defined = "not "; // for SQL
93 $not_defined_log = "not-"; // for logging
94 // then fall through to IS-DEFINED case
95 case 'urn:ietf:params:xml:ns:caldav:is-defined':
96 if ( isset( $parameter ) ) {
97 $need_post_filter = true;
98 dbg_error_log("calquery", "Could not handle 'is-%sdefined' on property %s, parameter %s in SQL", $not_defined_log, $property, $parameter );
99 return false; // Not handled in SQL
100 }
101 if ( isset( $property ) ) {
102 # $property may include the table name, remove that for the switch.
103 if (strpos($property, '.')) {
104 $base_property = explode('.', $property)[1];
105 } else {
106 $base_property = $property;
107 }
108
109 // For some tables we want to check that the user actually sent us,
110 // and that may be in a column with a '_orig' suffix.
111 $property_suffix = '';
112
113 switch( $base_property ) {
114 case 'dtend':
115 case 'dtstart':
116 $property_suffix = '_orig';
117
118 case 'created':
119 case 'completed':
120 case 'dtend':
121 case 'dtstamp':
122 case 'dtstart':
123 case 'due':
124 if ( ! $target_collection->IsSchedulingCollection() ) {
125 if ($not_defined == "not ") {
126 // "not IS NOT NULL" is a syntax error in SQL.
127 $property_defined_match = "IS NULL";
128 $not_defined = '';
129 } else {
130 $property_defined_match = "IS NOT NULL";
131 }
132 }
133 break;
134
135 case 'priority':
136 case 'status':
137 case 'class':
138 if ($not_defined == "not ") {
139 // "not IS NOT NULL" is a syntax error in SQL.
140 $property_defined_match = "IS NULL";
141 $not_defined = '';
142 } else {
143 $property_defined_match = "IS NOT NULL";
144 }
145 break;
146
147 // These may be null or have the empty string, so we need a more complicated query.
148 case 'location':
149 case 'summary':
150 case 'url':
151 if ($not_defined == "not ") {
152 // "not IS NOT NULL" is a syntax error in SQL.
153 $property_defined_match = "IS NULL";
154 $condition = 'OR';
155 } else {
156 $property_defined_match = "IS NOT NULL";
157 $condition = 'AND';
158 }
159
160
161 $sql .= sprintf(" AND (%s %s %s %s %sLIKE '_%%') ", $property, $property_defined_match, $condition, $property, $not_defined);
162 $property_defined_match = null;
163 break;
164
165 default:
166 $property_defined_match = "LIKE '_%'"; // i.e. contains a single character or more
167 }
168
169 if (isset($property_defined_match)) {
170 $sql .= sprintf( "AND %s%s %s%s ", $property, $property_suffix, $not_defined, $property_defined_match );
171 }
172 }
173 break;
174
175 case 'urn:ietf:params:xml:ns:caldav:time-range':
180 $start_column = ($components[sizeof($components)-1] == 'VTODO' ? "due" : 'dtend'); // The column we compare against the START attribute
181 $finish_column = 'dtstart'; // The column we compare against the END attribute
182
183 $start = $v->GetAttribute("start");
184 $finish = $v->GetAttribute("end");
185
186 if ( isset($start) ) {
187 $params[':time_range_start'] = $start;
188 $time_range_start = new RepeatRuleDateTime($start);
189 } else {
190 # RFC 4791 Section 9.9 says that if start isn't set, then -infinity
191 # should be used. We can't specify that in PHP, and
192 # expand_event_instances has '-6 weeks' as the default.
193 # That's a bit short, go for one year prior to end, if defined,
194 # otherwise 1 year prior to now now.
195 if ( isset($finish) ) {
196 $time_range_start = new RepeatRuleDateTime($finish);
197 } else {
198 $time_range_start = new RepeatRuleDateTime;
199 }
200 $time_range_start->modify('-365 days');
201
202 $params[':time_range_start'] = $time_range_start->UTC();
203 }
204
205 if (! isset($expand_range_start) || $time_range_start > $expand_range_start ) {
206 # We overload the expand_range_start, and we may need to make it more restrictive.
207 $expand_range_start = $time_range_start;
208 }
209
210 if ( isset($finish) ) {
211 $params[':time_range_end'] = $finish;
212 $time_range_end = new RepeatRuleDateTime($finish);
213 } else {
214 # RFC 4791 Section 9.9 says that if end isn't set, then +infinity
215 # should be used. We can't specify that in PHP, and
216 # expand_event_instances has '+ 6 weeks' as the default. That's a
217 # bit short, go for two years from the start.
218 $time_range_end = clone($time_range_start);
219 $time_range_end->modify('+730 days');
220
221 $params[':time_range_end'] = $time_range_end->UTC();
222 }
223
224 if (! isset($expand_range_end) || $time_range_end < $expand_range_end ) {
225 # We overload the expand_range_end, and we may need to make it more restrictive.
226 $expand_range_end = $time_range_end;
227 }
228
229 $legacy_start_cond = "($start_column IS NULL AND $finish_column > :time_range_start) OR $start_column > :time_range_start";
230 $legacy_end_cond = "$finish_column < :time_range_end";
231
232 $new_start_cond = "last_instance_end IS NULL OR last_instance_end >= :time_range_start";
233 $new_end_cond = "first_instance_start <= :time_range_end";
234
235 if (!isset($start) && !isset($end)) {
236 $legacy_cond = "true";
237 $new_cond = "true";
238 } else if (!isset($start) && isset($end)) {
239 $legacy_cond = $legacy_end_cond;
240 $new_cond = $new_end_cond;
241 } else if (isset($start) && !isset($end)) {
242 $legacy_cond = $legacy_start_cond;
243 $new_cond = $new_start_cond;
244 } else if (isset($start) && isset($end)) {
245 $legacy_cond = "($legacy_end_cond) AND ($legacy_start_cond)";
246 $new_cond = "($new_end_cond) AND ($new_start_cond)";
247 }
248
249 $sql .= " AND (
250(first_instance_start IS NULL AND rrule IS NOT NULL OR $finish_column IS NULL OR ($legacy_cond))
251OR (first_instance_start IS NOT NULL AND ($new_cond))
252) ";
253
254 @dbg_error_log('calquery', 'filter-sql: %s', $sql);
255 @dbg_error_log('calquery', 'time-range-start: %s, time-range-end: %s, ', $params[':time_range_start'], $params[':time_range_end']);
256 $range_filter = new RepeatRuleDateRange((empty($start) ? null : new RepeatRuleDateTime($start)),
257 (empty($finish)? null : new RepeatRuleDateTime($finish)));
258 break;
259
260 case 'urn:ietf:params:xml:ns:caldav:text-match':
261 $search = $v->GetContent();
262 $negate = $v->GetAttribute("negate-condition");
263 $collation = $v->GetAttribute("collation");
264 if (! isset($collation)) {
265 $collation = '';
266 }
267 switch( strtolower($collation) ) {
268 case 'i;octet':
269 $comparison = 'LIKE';
270 break;
271 case 'i;ascii-casemap':
272 default:
273 $comparison = 'ILIKE';
274 break;
275 }
276 /* Append the match number to the SQL parameter, to allow multiple text match conditions within the same query */
277 $params[':text_match_'.$parameter_match_num] = '%'.$search.'%';
278 $fragment = sprintf( 'AND (%s%s %s :text_match_%s) ',
279 (isset($negate) && strtolower($negate) == "yes" ? $property.' IS NULL OR NOT ': ''),
280 $property, $comparison, $parameter_match_num );
281 $parameter_match_num++;
282
283 dbg_error_log('calquery', ' text-match: %s', $fragment );
284 $sql .= $fragment;
285 break;
286
287 case 'urn:ietf:params:xml:ns:caldav:comp-filter':
288 $comp_filter_name = $v->GetAttribute("name");
289 if ( $comp_filter_name != 'VCALENDAR' && count($components) == 0 ) {
290 $sql .= "AND caldav_data.caldav_type = :component_name_filter ";
291 $params[':component_name_filter'] = $comp_filter_name;
292 $components[] = $comp_filter_name;
293 }
294 $subfilter = $v->GetContent();
295 if ( is_array( $subfilter ) ) {
296 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
297 if ( $success === false ) continue 2; else {
298 $sql .= $success['sql'];
299 $params = array_merge( $params, $success['params'] );
300 }
301 }
302 break;
303
304 case 'urn:ietf:params:xml:ns:caldav:prop-filter':
305 $propertyname = $v->GetAttribute("name");
306 switch( $propertyname ) {
307 case 'PERCENT-COMPLETE':
308 $subproperty = 'percent_complete';
309 break;
310
311 case 'UID':
312 case 'SUMMARY':
313// case 'LOCATION':
314 case 'DESCRIPTION':
315 case 'CLASS':
316 case 'TRANSP':
317 case 'RRULE': // Likely that this is not much use
318 case 'URL':
319 case 'STATUS':
320 case 'CREATED':
321 case 'DTSTAMP':
322 case 'DTSTART':
323 case 'DTEND':
324 case 'DUE':
325 case 'PRIORITY':
326 $subproperty = 'calendar_item.'.strtolower($propertyname);
327 break;
328
329 case 'COMPLETED':
330 default:
331 $need_post_filter = true;
332 unset($subproperty);
333 dbg_error_log("calquery", "Could not handle 'prop-filter' on %s in SQL", $propertyname );
334 continue 3;
335 }
336 if ( isset($subproperty) ) {
337 $subfilter = $v->GetContent();
338 $success = SqlFilterFragment( $subfilter, $components, $subproperty, $parameter );
339 if ( $success === false ) continue 2; else {
340 $sql .= $success['sql'];
341 $params = array_merge( $params, $success['params'] );
342 }
343 }
344 break;
345
346 case 'urn:ietf:params:xml:ns:caldav:param-filter':
347 $need_post_filter = true;
348 return false; // Can't handle PARAM-FILTER conditions in the SQL
349 $parameter = $v->GetAttribute("name");
350 $subfilter = $v->GetContent();
351 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
352 if ( $success === false ) continue 2; else {
353 $sql .= $success['sql'];
354 $params = array_merge( $params, $success['params'] );
355 }
356 break;
357
358 default:
359 dbg_error_log("calquery", "Could not handle unknown tag '%s' in calendar query report", $tag );
360 break;
361 }
362 }
363 dbg_error_log("calquery", "Generated SQL was '%s'", $sql );
364 return array( 'sql' => $sql, 'params' => $params );
365}
366
375function BuildSqlFilter( $filter ) {
376 $components = array();
377 if ( $filter->GetNSTag() == "urn:ietf:params:xml:ns:caldav:comp-filter" && $filter->GetAttribute("name") == "VCALENDAR" )
378 $filter = $filter->GetContent(); // Everything is inside a VCALENDAR AFAICS
379 else {
380 dbg_error_log("calquery", "Got bizarre CALDAV:FILTER[%s=%s]] which does not contain comp-filter = VCALENDAR!!", $filter->GetNSTag(), $filter->GetAttribute("name") );
381 }
382 return SqlFilterFragment( $filter, $components );
383}
384
385
390$responses = array();
391$target_collection = new DAVResource($request->path);
392$bound_from = $target_collection->bound_from();
393if ( !$target_collection->Exists() ) {
394 $request->DoResponse( 404 );
395}
396
397$params = array();
398
399if ( ! ($target_collection->IsCalendar() || $target_collection->IsSchedulingCollection()) ) {
400 if ( !(isset($c->allow_recursive_report) && $c->allow_recursive_report) ) {
401 $request->DoResponse( 403, translate('The calendar-query report must be run against a calendar or a scheduling collection') );
402 }
403 else if ( $request->path == '/' || $target_collection->IsPrincipal() || $target_collection->IsAddressbook() ) {
404 $request->DoResponse( 403, translate('The calendar-query report may not be run against that URL.') );
405 }
409 $where = 'WHERE caldav_data.collection_id IN ';
410 $where .= '(SELECT bound_source_id FROM dav_binding WHERE dav_binding.dav_name ~ :path_match ';
411 $where .= 'UNION ';
412 $where .= 'SELECT collection_id FROM collection WHERE collection.dav_name ~ :path_match) ';
413 $distinct = 'DISTINCT ON (calendar_item.uid) ';
414 $params[':path_match'] = '^'.$target_collection->bound_from();
415}
416else {
417 $where = ' WHERE caldav_data.collection_id = ' . $target_collection->resource_id();
418 $distinct = '';
419}
420
421if ( is_array($qry_filters) ) {
422 dbg_log_array( "calquery", "qry_filters", $qry_filters, true );
423 $components = array();
424 $filter_fragment = SqlFilterFragment( $qry_filters, $components );
425 if ( $filter_fragment !== false ) {
426 $where .= ' '.$filter_fragment['sql'];
427 $params = array_merge( $params, $filter_fragment['params']);
428 }
429}
430if ( $target_collection->Privileges() != privilege_to_bits('DAV::all') ) {
431 $where .= " AND (calendar_item.class != 'PRIVATE' OR calendar_item.class IS NULL) ";
432}
433
434if ( isset($c->hide_TODO) && ($c->hide_TODO === true || (is_string($c->hide_TODO) && preg_match($c->hide_TODO, $_SERVER['HTTP_USER_AGENT']))) && ! $target_collection->HavePrivilegeTo('all') ) {
435 $where .= " AND caldav_data.caldav_type NOT IN ('VTODO') ";
436}
437
438if ( isset($c->hide_older_than) && intval($c->hide_older_than > 0) ) {
439 $where .= " AND (CASE WHEN caldav_data.caldav_type<>'VEVENT' OR calendar_item.dtstart IS NULL OR calendar_item.rrule IS NOT NULL THEN true ELSE calendar_item.dtstart > (now() - interval '".intval($c->hide_older_than)." days') END) ";
440}
441
442$sql = 'SELECT '.$distinct.' caldav_data.*,calendar_item.*,collection.timezone AS collection_tzid FROM collection INNER JOIN caldav_data USING(collection_id) INNER JOIN calendar_item USING(dav_id) '. $where;
443if ( isset($c->strict_result_ordering) && $c->strict_result_ordering ) $sql .= " ORDER BY caldav_data.dav_id";
444$qry = new AwlQuery( $sql, $params );
445if ( $qry->Exec("calquery",__LINE__,__FILE__) && $qry->rows() > 0 ) {
446 while( $dav_object = $qry->Fetch() ) {
447 try {
448 if ( !$need_post_filter || calquery_apply_filter( $qry_filters, $dav_object ) ) {
449 if ( $bound_from != $target_collection->dav_name() ) {
450 $dav_object->dav_name = str_replace( $bound_from, $target_collection->dav_name(), $dav_object->dav_name);
451 }
452 if ( $need_expansion || isset($range_filter) ) {
453 $vResource = new vComponent($dav_object->caldav_data);
454 $expanded = getVCalendarRange($vResource, $dav_object->collection_tzid);
455 if ( !$expanded->overlaps($range_filter) ) continue;
456
457 $expanded = expand_event_instances($vResource, $expand_range_start, $expand_range_end, $expand_as_floating , $dav_object->collection_tzid);
458
459 if ( $expanded->ComponentCount() == 0 ) continue;
460
461 # We only keep the expanded instaneces if need_expansion is set,
462 # RFC4791 Section 7.4. Otherwise we should return the original
463 # caldav_data.
464 if ( $need_expansion ) {
465 $dav_object->caldav_data = $expanded->Render();
466 }
467 }
468 else if ( isset($range_filter) ) {
469 $vResource = new vComponent($dav_object->caldav_data);
470 $expanded = getVCalendarRange($vResource);
471 dbg_error_log('calquery', 'Expanded to %s:%s which might overlap %s:%s',
472 $expanded->from, $expanded->until, $range_filter->from, $range_filter->until );
473 if ( !$expanded->overlaps($range_filter) ) continue;
474 }
475 $responses[] = component_to_xml( $properties, $dav_object );
476 }
477 }
478 catch( Exception $e ) {
479 dbg_error_log( 'ERROR', 'Exception handling "%s" - skipping', $dav_object->dav_name);
480 }
481 }
482}
483
484$multistatus = new XMLElement( "multistatus", $responses, $reply->GetXmlNsArray() );
485
486$request->XMLResponse( 207, $multistatus );