Merge branch 'master' of github.com:DAViCal/davical into github
[davical.git] / inc / caldav-REPORT-calquery.php
blob365b890534ee9ad6e5302cfef6f5ae80db59952e
1 <?php
3 include_once('vCalendar.php');
5 $need_expansion = false;
6 function check_for_expansion( $calendar_data_node ) {
7 global $need_expansion, $expand_range_start, $expand_range_end, $expand_as_floating;
9 if ( !class_exists('DateTime') ) return; /** We don't support expansion on PHP5.1 */
11 $expansion = $calendar_data_node->GetElements('urn:ietf:params:xml:ns:caldav:expand');
12 if ( isset($expansion[0]) ) {
13 $need_expansion = true;
14 $expand_range_start = $expansion[0]->GetAttribute('start');
15 $expand_range_end = $expansion[0]->GetAttribute('end');
16 $expand_as_floating = $expansion[0]->GetAttribute('floating');
17 if ( isset($expand_range_start) ) $expand_range_start = new RepeatRuleDateTime($expand_range_start);
18 if ( isset($expand_range_end) ) $expand_range_end = new RepeatRuleDateTime($expand_range_end);
19 if ( isset($expand_as_floating) && $expand_as_floating == "yes" )
20 $expand_as_floating = true;
21 else
22 $expand_as_floating = false;
26 /**
27 * Build the array of properties to include in the report output
29 $qry_content = $xmltree->GetContent('urn:ietf:params:xml:ns:caldav:calendar-query');
31 $properties = array();
32 $include_properties = array();
33 while (list($idx, $qqq) = each($qry_content))
35 $proptype = $qry_content[$idx]->GetNSTag();
36 switch( $proptype ) {
37 case 'DAV::prop':
38 $qry_props = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/'.$proptype.'/*');
39 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
40 $propertyname = $v->GetNSTag();
41 $properties[$propertyname] = 1;
42 if ( $propertyname == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
44 break;
46 case 'DAV::allprop':
47 $properties['DAV::allprop'] = 1;
48 if ( $qry_content[$idx]->GetNSTag() == 'DAV::include' ) {
49 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
50 $include_properties[] = $v->GetNSTag(); /** $include_properties is referenced in DAVResource where allprop is expanded */
51 if ( $v->GetNSTag() == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
54 break;
57 if ( empty($properties) ) $properties['DAV::allprop'] = 1;
60 /**
61 * There can only be *one* FILTER element, and it must contain *one* COMP-FILTER
62 * element. In every case I can see this contained COMP-FILTER element will
63 * necessarily be a VCALENDAR, which then may contain other COMP-FILTER etc.
65 $qry_filters = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/urn:ietf:params:xml:ns:caldav:filter/*');
66 if ( count($qry_filters) != 1 ) $qry_filters = false;
69 /**
70 * While we can construct our SQL to apply some filters in the query, other filters
71 * need to be checked against the retrieved record. This is for handling those ones.
73 * @param array $filter An array of XMLElement which is the filter definition
74 * @param string $item The database row retrieved for this calendar item
76 * @return boolean True if the check succeeded, false otherwise.
78 function apply_filter( $filters, $item ) {
79 global $session, $c, $request;
81 if ( count($filters) == 0 ) return true;
83 dbg_error_log("calquery","Applying filter for item '%s'", $item->dav_name );
84 $ical = new vCalendar( $item->caldav_data );
85 return $ical->StartFilter($filters);
89 /**
90 * Process a filter fragment returning an SQL fragment
92 $need_post_filter = false;
93 $range_filter = null;
94 function SqlFilterFragment( $filter, $components, $property = null, $parameter = null ) {
95 global $need_post_filter, $range_filter, $target_collection;
96 $sql = "";
97 $params = array();
98 if ( !is_array($filter) ) {
99 dbg_error_log( "calquery", "Filter is of type '%s', but should be an array of XML Tags.", gettype($filter) );
102 foreach( $filter AS $k => $v ) {
103 $tag = $v->GetNSTag();
104 dbg_error_log("calquery", "Processing $tag into SQL - %d, '%s', %d\n", count($components), $property, isset($parameter) );
106 $not_defined = "";
107 switch( $tag ) {
108 case 'urn:ietf:params:xml:ns:caldav:is-not-defined':
109 $not_defined = "not-"; // then fall through to IS-DEFINED case
110 case 'urn:ietf:params:xml:ns:caldav:is-defined':
111 if ( isset( $parameter ) ) {
112 $need_post_filter = true;
113 dbg_error_log("calquery", "Could not handle 'is-%sdefined' on property %s, parameter %s in SQL", $not_defined, $property, $parameter );
114 return false; // Not handled in SQL
116 if ( isset( $property ) ) {
117 switch( $property ) {
118 case 'created':
119 case 'completed': /** @todo when it can be handled in the SQL - see around line 200 below */
120 case 'dtend':
121 case 'dtstamp':
122 case 'dtstart':
123 if ( ! $target_collection->IsSchedulingCollection() ) {
124 $property_defined_match = "IS NOT NULL";
126 break;
128 case 'priority':
129 $property_defined_match = "IS NOT NULL";
130 break;
132 default:
133 $property_defined_match = "LIKE '_%'"; // i.e. contains a single character or more
135 $sql .= sprintf( "AND %s %s%s ", $property, $not_defined, $property_defined_match );
137 break;
139 case 'urn:ietf:params:xml:ns:caldav:time-range':
141 * @todo We should probably allow time range queries against other properties, since
142 * eventually some client may want to do this.
144 $start_column = ($components[sizeof($components)-1] == 'VTODO' ? "due" : 'dtend'); // The column we compare against the START attribute
145 $finish_column = 'dtstart'; // The column we compare against the END attribute
146 $start = $v->GetAttribute("start");
147 $finish = $v->GetAttribute("end");
148 $start_sql = $finish_sql = '';
149 if ( isset($start) ) {
150 $params[':time_range_start'] = $start;
151 $start_sql .= ' (('.$start_column.' IS NULL AND '.$finish_column.' > :time_range_start) OR '.$start_column.' > :time_range_start) ';
153 if ( isset($finish) ) {
154 $params[':time_range_end'] = $finish;
155 $finish_sql = ' '.$finish_column.' < :time_range_end ';
157 if ( isset($start) || isset($finish) ) {
158 $sql .= ' AND (rrule IS NOT NULL OR '.$finish_column.' IS NULL OR (';
159 if ( isset($start) ) $sql .= $start_sql;
160 if ( isset($start) && isset($finish) ) $sql .= ' AND ';
161 if ( isset($finish) ) $sql .= $finish_sql;
162 $sql .= '))';
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;
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 switch( strtolower($collation) ) {
175 case 'i;octet':
176 $comparison = 'LIKE';
177 break;
178 case 'i;ascii-casemap':
179 default:
180 $comparison = 'ILIKE';
181 break;
183 $params[':text_match'] = '%'.$search.'%';
184 $fragment = sprintf( 'AND (%s%s %s :text_match) ',
185 (isset($negate) && strtolower($negate) == "yes" ? $property.' IS NULL OR NOT ': ''),
186 $property, $comparison );
187 dbg_error_log('calquery', ' text-match: %s', $fragment );
188 $sql .= $fragment;
189 break;
191 case 'urn:ietf:params:xml:ns:caldav:comp-filter':
192 $comp_filter_name = $v->GetAttribute("name");
193 if ( $comp_filter_name != 'VCALENDAR' && count($components) == 0 ) {
194 $sql .= "AND caldav_data.caldav_type = :component_name_filter ";
195 $params[':component_name_filter'] = $comp_filter_name;
196 $components[] = $comp_filter_name;
198 $subfilter = $v->GetContent();
199 if ( is_array( $subfilter ) ) {
200 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
201 if ( $success === false ) continue; else {
202 $sql .= $success['sql'];
203 $params = array_merge( $params, $success['params'] );
206 break;
208 case 'urn:ietf:params:xml:ns:caldav:prop-filter':
209 $propertyname = $v->GetAttribute("name");
210 switch( $propertyname ) {
211 case 'PERCENT-COMPLETE':
212 $subproperty = 'percent_complete';
213 break;
215 case 'UID':
216 case 'SUMMARY':
217 // case 'LOCATION':
218 case 'DESCRIPTION':
219 case 'CLASS':
220 case 'TRANSP':
221 case 'RRULE': // Likely that this is not much use
222 case 'URL':
223 case 'STATUS':
224 case 'CREATED':
225 case 'DTSTAMP':
226 case 'DTSTART':
227 case 'DTEND':
228 case 'DUE':
229 case 'PRIORITY':
230 $subproperty = 'calendar_item.'.strtolower($propertyname);
231 break;
233 case 'COMPLETED': /** @todo this should be moved into the properties supported in SQL. */
234 default:
235 $need_post_filter = true;
236 dbg_error_log("calquery", "Could not handle 'prop-filter' on %s in SQL", $propertyname );
237 continue;
239 if ( isset($subproperty) ) {
240 $subfilter = $v->GetContent();
241 $success = SqlFilterFragment( $subfilter, $components, $subproperty, $parameter );
242 if ( $success === false ) continue; else {
243 $sql .= $success['sql'];
244 $params = array_merge( $params, $success['params'] );
247 break;
249 case 'urn:ietf:params:xml:ns:caldav:param-filter':
250 $need_post_filter = true;
251 return false; // Can't handle PARAM-FILTER conditions in the SQL
252 $parameter = $v->GetAttribute("name");
253 $subfilter = $v->GetContent();
254 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
255 if ( $success === false ) continue; else {
256 $sql .= $success['sql'];
257 $params = array_merge( $params, $success['params'] );
259 break;
261 default:
262 dbg_error_log("calquery", "Could not handle unknown tag '%s' in calendar query report", $tag );
263 break;
266 dbg_error_log("calquery", "Generated SQL was '%s'", $sql );
267 return array( 'sql' => $sql, 'params' => $params );
271 * Build an SQL 'WHERE' clause which implements (parts of) the filter. The
272 * elements of the filter which are implemented in the SQL will be removed.
274 * @param arrayref &$filter A reference to an array of XMLElement defining the filter
276 * @return string A string suitable for use as an SQL 'WHERE' clause selecting the desired records.
278 function BuildSqlFilter( $filter ) {
279 $components = array();
280 if ( $filter->GetNSTag() == "urn:ietf:params:xml:ns:caldav:comp-filter" && $filter->GetAttribute("name") == "VCALENDAR" )
281 $filter = $filter->GetContent(); // Everything is inside a VCALENDAR AFAICS
282 else {
283 dbg_error_log("calquery", "Got bizarre CALDAV:FILTER[%s=%s]] which does not contain comp-filter = VCALENDAR!!", $filter->GetNSTag(), $filter->GetAttribute("name") );
285 return SqlFilterFragment( $filter, $components );
290 * Something that we can handle, at least roughly correctly.
293 $responses = array();
294 $target_collection = new DAVResource($request->path);
295 $bound_from = $target_collection->bound_from();
296 if ( !$target_collection->Exists() ) {
297 $request->DoResponse( 404 );
300 $params = array();
302 if ( ! ($target_collection->IsCalendar() || $target_collection->IsSchedulingCollection()) ) {
303 if ( !(isset($c->allow_recursive_report) && $c->allow_recursive_report) ) {
304 $request->DoResponse( 403, translate('The calendar-query report must be run against a calendar or a scheduling collection') );
306 else if ( $request->path == '/' || $target_collection->IsPrincipal() || $target_collection->IsAddressbook() ) {
307 $request->DoResponse( 403, translate('The calendar-query report may not be run against that URL.') );
310 * We're here because they allow recursive reports, and this appears to be such a location.
312 $where = 'WHERE caldav_data.collection_id IN ';
313 $where .= '(SELECT bound_source_id FROM dav_binding WHERE dav_binding.dav_name ~ :path_match ';
314 $where .= 'UNION ';
315 $where .= 'SELECT collection_id FROM collection WHERE collection.dav_name ~ :path_match) ';
316 $distinct = 'DISTINCT ON (calendar_item.uid) ';
317 $params[':path_match'] = '^'.$target_collection->bound_from();
319 else {
320 $where = ' WHERE caldav_data.collection_id = ' . $target_collection->resource_id();
321 $distinct = '';
324 if ( is_array($qry_filters) ) {
325 dbg_log_array( "calquery", "qry_filters", $qry_filters, true );
326 $components = array();
327 $filter_fragment = SqlFilterFragment( $qry_filters, $components );
328 if ( $filter_fragment !== false ) {
329 $where .= ' '.$filter_fragment['sql'];
330 $params = array_merge( $params, $filter_fragment['params']);
333 if ( $target_collection->Privileges() != privilege_to_bits('DAV::all') ) {
334 $where .= " AND (calendar_item.class != 'PRIVATE' OR calendar_item.class IS NULL) ";
337 if ( 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') ) {
338 $where .= " AND caldav_data.caldav_type NOT IN ('VTODO') ";
341 if ( isset($c->hide_older_than) && intval($c->hide_older_than > 0) ) {
342 $where .= " AND (CASE WHEN caldav_data.caldav_type<>'VEVENT' OR calendar_item.dtstart IS NULL THEN true ELSE calendar_item.dtstart > (now() - interval '".intval($c->hide_older_than)." days') END) ";
345 $sql = 'SELECT '.$distinct.' caldav_data.*,calendar_item.* FROM collection INNER JOIN caldav_data USING(collection_id) INNER JOIN calendar_item USING(dav_id) '. $where;
346 if ( isset($c->strict_result_ordering) && $c->strict_result_ordering ) $sql .= " ORDER BY caldav_data.dav_id";
347 $qry = new AwlQuery( $sql, $params );
348 if ( $qry->Exec("calquery",__LINE__,__FILE__) && $qry->rows() > 0 ) {
349 while( $dav_object = $qry->Fetch() ) {
350 try {
351 if ( !$need_post_filter || apply_filter( $qry_filters, $dav_object ) ) {
352 if ( $bound_from != $target_collection->dav_name() ) {
353 $dav_object->dav_name = str_replace( $bound_from, $target_collection->dav_name(), $dav_object->dav_name);
355 if ( $need_expansion ) {
356 $vResource = new vComponent($dav_object->caldav_data);
357 $expanded = getVCalendarRange($vResource);
358 if ( !$expanded->overlaps($range_filter) ) continue;
360 $expanded = expand_event_instances($vResource, $expand_range_start, $expand_range_end, $expand_as_floating );
362 if ( $expanded->ComponentCount() == 0 ) continue;
363 if ( $need_expansion ) $dav_object->caldav_data = $expanded->Render();
365 else if ( isset($range_filter) ) {
366 $vResource = new vComponent($dav_object->caldav_data);
367 $expanded = getVCalendarRange($vResource);
368 dbg_error_log('calquery', 'Expanded to %s:%s which might overlap %s:%s',
369 $expanded->from, $expanded->until, $range_filter->from, $range_filter->until );
370 if ( !$expanded->overlaps($range_filter) ) continue;
372 $responses[] = component_to_xml( $properties, $dav_object );
375 catch( Exception $e ) {
376 dbg_error_log( 'ERROR', 'Exception handling "%s" - skipping', $dav_object->dav_name);
381 $multistatus = new XMLElement( "multistatus", $responses, $reply->GetXmlNsArray() );
383 $request->XMLResponse( 207, $multistatus );