DAViCal
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
73$need_post_filter = false;
74$range_filter = null;
75$parameter_match_num = 0;
76function SqlFilterFragment( $filter, $components, $property = null, $parameter = null) {
77 global $need_post_filter, $range_filter, $target_collection, $parameter_match_num;
78 $sql = "";
79 $params = array();
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 switch( $tag ) {
90 case 'urn:ietf:params:xml:ns:caldav:is-not-defined':
91 $not_defined = "not-"; // then fall through to IS-DEFINED case
92 case 'urn:ietf:params:xml:ns:caldav:is-defined':
93 if ( isset( $parameter ) ) {
94 $need_post_filter = true;
95 dbg_error_log("calquery", "Could not handle 'is-%sdefined' on property %s, parameter %s in SQL", $not_defined, $property, $parameter );
96 return false; // Not handled in SQL
97 }
98 if ( isset( $property ) ) {
99 switch( $property ) {
100 case 'created':
101 case 'completed':
102 case 'dtend':
103 case 'dtstamp':
104 case 'dtstart':
105 if ( ! $target_collection->IsSchedulingCollection() ) {
106 $property_defined_match = "IS NOT NULL";
107 }
108 break;
109
110 case 'priority':
111 $property_defined_match = "IS NOT NULL";
112 break;
113
114 default:
115 $property_defined_match = "LIKE '_%'"; // i.e. contains a single character or more
116 }
117 $sql .= sprintf( "AND %s %s%s ", $property, $not_defined, $property_defined_match );
118 }
119 break;
120
121 case 'urn:ietf:params:xml:ns:caldav:time-range':
126 $start_column = ($components[sizeof($components)-1] == 'VTODO' ? "due" : 'dtend'); // The column we compare against the START attribute
127 $finish_column = 'dtstart'; // The column we compare against the END attribute
128
129 $start = $v->GetAttribute("start");
130 $finish = $v->GetAttribute("end");
131
132 if ( isset($start) )
133 $params[':time_range_start'] = $start;
134
135 if ( isset($finish) )
136 $params[':time_range_end'] = $finish;
137
138
139 $legacy_start_cond = "($start_column IS NULL AND $finish_column > :time_range_start) OR $start_column > :time_range_start";
140 $legacy_end_cond = "$finish_column < :time_range_end";
141
142 $new_start_cond = "last_instance_end IS NULL OR last_instance_end >= :time_range_start";
143 $new_end_cond = "first_instance_start <= :time_range_end";
144
145 if (!isset($start) && !isset($end)) {
146 $legacy_cond = "true";
147 $new_cond = "true";
148 } else if (!isset($start) && isset($end)) {
149 $legacy_cond = $legacy_end_cond;
150 $new_cond = $new_end_cond;
151 } else if (isset($start) && !isset($end)) {
152 $legacy_cond = $legacy_start_cond;
153 $new_cond = $new_start_cond;
154 } else if (isset($start) && isset($end)) {
155 $legacy_cond = "($legacy_end_cond) AND ($legacy_start_cond)";
156 $new_cond = "($new_end_cond) AND ($new_start_cond)";
157 }
158
159 $sql .= " AND (
160(first_instance_start IS NULL AND rrule IS NOT NULL OR $finish_column IS NULL OR ($legacy_cond))
161OR (first_instance_start IS NOT NULL AND ($new_cond))
162) ";
163
164 @dbg_error_log('calquery', 'filter-sql: %s', $sql);
165 @dbg_error_log('calquery', 'time-range-start: %s, time-range-end: %s, ', $params[':time_range_start'], $params[':time_range_end']);
166 $range_filter = new RepeatRuleDateRange((empty($start) ? null : new RepeatRuleDateTime($start)),
167 (empty($finish)? null : new RepeatRuleDateTime($finish)));
168 break;
169
170 case 'urn:ietf:params:xml:ns:caldav:text-match':
171 $search = $v->GetContent();
172 $negate = $v->GetAttribute("negate-condition");
173 $collation = $v->GetAttribute("collation");
174 if (! isset($collation)) {
175 $collation = '';
176 }
177 switch( strtolower($collation) ) {
178 case 'i;octet':
179 $comparison = 'LIKE';
180 break;
181 case 'i;ascii-casemap':
182 default:
183 $comparison = 'ILIKE';
184 break;
185 }
186 /* Append the match number to the SQL parameter, to allow multiple text match conditions within the same query */
187 $params[':text_match_'.$parameter_match_num] = '%'.$search.'%';
188 $fragment = sprintf( 'AND (%s%s %s :text_match_%s) ',
189 (isset($negate) && strtolower($negate) == "yes" ? $property.' IS NULL OR NOT ': ''),
190 $property, $comparison, $parameter_match_num );
191 $parameter_match_num++;
192
193 dbg_error_log('calquery', ' text-match: %s', $fragment );
194 $sql .= $fragment;
195 break;
196
197 case 'urn:ietf:params:xml:ns:caldav:comp-filter':
198 $comp_filter_name = $v->GetAttribute("name");
199 if ( $comp_filter_name != 'VCALENDAR' && count($components) == 0 ) {
200 $sql .= "AND caldav_data.caldav_type = :component_name_filter ";
201 $params[':component_name_filter'] = $comp_filter_name;
202 $components[] = $comp_filter_name;
203 }
204 $subfilter = $v->GetContent();
205 if ( is_array( $subfilter ) ) {
206 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
207 if ( $success === false ) continue 2; else {
208 $sql .= $success['sql'];
209 $params = array_merge( $params, $success['params'] );
210 }
211 }
212 break;
213
214 case 'urn:ietf:params:xml:ns:caldav:prop-filter':
215 $propertyname = $v->GetAttribute("name");
216 switch( $propertyname ) {
217 case 'PERCENT-COMPLETE':
218 $subproperty = 'percent_complete';
219 break;
220
221 case 'UID':
222 case 'SUMMARY':
223// case 'LOCATION':
224 case 'DESCRIPTION':
225 case 'CLASS':
226 case 'TRANSP':
227 case 'RRULE': // Likely that this is not much use
228 case 'URL':
229 case 'STATUS':
230 case 'CREATED':
231 case 'DTSTAMP':
232 case 'DTSTART':
233 case 'DTEND':
234 case 'DUE':
235 case 'PRIORITY':
236 $subproperty = 'calendar_item.'.strtolower($propertyname);
237 break;
238
239 case 'COMPLETED':
240 default:
241 $need_post_filter = true;
242 unset($subproperty);
243 dbg_error_log("calquery", "Could not handle 'prop-filter' on %s in SQL", $propertyname );
244 continue 3;
245 }
246 if ( isset($subproperty) ) {
247 $subfilter = $v->GetContent();
248 $success = SqlFilterFragment( $subfilter, $components, $subproperty, $parameter );
249 if ( $success === false ) continue 2; else {
250 $sql .= $success['sql'];
251 $params = array_merge( $params, $success['params'] );
252 }
253 }
254 break;
255
256 case 'urn:ietf:params:xml:ns:caldav:param-filter':
257 $need_post_filter = true;
258 return false; // Can't handle PARAM-FILTER conditions in the SQL
259 $parameter = $v->GetAttribute("name");
260 $subfilter = $v->GetContent();
261 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
262 if ( $success === false ) continue 2; else {
263 $sql .= $success['sql'];
264 $params = array_merge( $params, $success['params'] );
265 }
266 break;
267
268 default:
269 dbg_error_log("calquery", "Could not handle unknown tag '%s' in calendar query report", $tag );
270 break;
271 }
272 }
273 dbg_error_log("calquery", "Generated SQL was '%s'", $sql );
274 return array( 'sql' => $sql, 'params' => $params );
275}
276
285function BuildSqlFilter( $filter ) {
286 $components = array();
287 if ( $filter->GetNSTag() == "urn:ietf:params:xml:ns:caldav:comp-filter" && $filter->GetAttribute("name") == "VCALENDAR" )
288 $filter = $filter->GetContent(); // Everything is inside a VCALENDAR AFAICS
289 else {
290 dbg_error_log("calquery", "Got bizarre CALDAV:FILTER[%s=%s]] which does not contain comp-filter = VCALENDAR!!", $filter->GetNSTag(), $filter->GetAttribute("name") );
291 }
292 return SqlFilterFragment( $filter, $components );
293}
294
295
300$responses = array();
301$target_collection = new DAVResource($request->path);
302$bound_from = $target_collection->bound_from();
303if ( !$target_collection->Exists() ) {
304 $request->DoResponse( 404 );
305}
306
307$params = array();
308
309if ( ! ($target_collection->IsCalendar() || $target_collection->IsSchedulingCollection()) ) {
310 if ( !(isset($c->allow_recursive_report) && $c->allow_recursive_report) ) {
311 $request->DoResponse( 403, translate('The calendar-query report must be run against a calendar or a scheduling collection') );
312 }
313 else if ( $request->path == '/' || $target_collection->IsPrincipal() || $target_collection->IsAddressbook() ) {
314 $request->DoResponse( 403, translate('The calendar-query report may not be run against that URL.') );
315 }
319 $where = 'WHERE caldav_data.collection_id IN ';
320 $where .= '(SELECT bound_source_id FROM dav_binding WHERE dav_binding.dav_name ~ :path_match ';
321 $where .= 'UNION ';
322 $where .= 'SELECT collection_id FROM collection WHERE collection.dav_name ~ :path_match) ';
323 $distinct = 'DISTINCT ON (calendar_item.uid) ';
324 $params[':path_match'] = '^'.$target_collection->bound_from();
325}
326else {
327 $where = ' WHERE caldav_data.collection_id = ' . $target_collection->resource_id();
328 $distinct = '';
329}
330
331if ( is_array($qry_filters) ) {
332 dbg_log_array( "calquery", "qry_filters", $qry_filters, true );
333 $components = array();
334 $filter_fragment = SqlFilterFragment( $qry_filters, $components );
335 if ( $filter_fragment !== false ) {
336 $where .= ' '.$filter_fragment['sql'];
337 $params = array_merge( $params, $filter_fragment['params']);
338 }
339}
340if ( $target_collection->Privileges() != privilege_to_bits('DAV::all') ) {
341 $where .= " AND (calendar_item.class != 'PRIVATE' OR calendar_item.class IS NULL) ";
342}
343
344if ( 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') ) {
345 $where .= " AND caldav_data.caldav_type NOT IN ('VTODO') ";
346}
347
348if ( isset($c->hide_older_than) && intval($c->hide_older_than > 0) ) {
349 $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) ";
350}
351
352$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;
353if ( isset($c->strict_result_ordering) && $c->strict_result_ordering ) $sql .= " ORDER BY caldav_data.dav_id";
354$qry = new AwlQuery( $sql, $params );
355if ( $qry->Exec("calquery",__LINE__,__FILE__) && $qry->rows() > 0 ) {
356 while( $dav_object = $qry->Fetch() ) {
357 try {
358 if ( !$need_post_filter || calquery_apply_filter( $qry_filters, $dav_object ) ) {
359 if ( $bound_from != $target_collection->dav_name() ) {
360 $dav_object->dav_name = str_replace( $bound_from, $target_collection->dav_name(), $dav_object->dav_name);
361 }
362 if ( $need_expansion ) {
363 $vResource = new vComponent($dav_object->caldav_data);
364 $expanded = getVCalendarRange($vResource, $dav_object->collection_tzid);
365 if ( !$expanded->overlaps($range_filter) ) continue;
366
367 $expanded = expand_event_instances($vResource, $expand_range_start, $expand_range_end, $expand_as_floating , $dav_object->collection_tzid);
368
369 if ( $expanded->ComponentCount() == 0 ) continue;
370 if ( $need_expansion ) $dav_object->caldav_data = $expanded->Render();
371 }
372 else if ( isset($range_filter) ) {
373 $vResource = new vComponent($dav_object->caldav_data);
374 $expanded = getVCalendarRange($vResource);
375 dbg_error_log('calquery', 'Expanded to %s:%s which might overlap %s:%s',
376 $expanded->from, $expanded->until, $range_filter->from, $range_filter->until );
377 if ( !$expanded->overlaps($range_filter) ) continue;
378 }
379 $responses[] = component_to_xml( $properties, $dav_object );
380 }
381 }
382 catch( Exception $e ) {
383 dbg_error_log( 'ERROR', 'Exception handling "%s" - skipping', $dav_object->dav_name);
384 }
385 }
386}
387
388$multistatus = new XMLElement( "multistatus", $responses, $reply->GetXmlNsArray() );
389
390$request->XMLResponse( 207, $multistatus );