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;
22 $expand_as_floating = false;
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 while (list($idx, $qqq) = each($qry_content))
34 $proptype = $qry_content[$idx]->GetTag();
37 $qry_props = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/'.$proptype.'/*');
38 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
39 $propertyname = preg_replace( '/^.*:/', '', $v->GetTag() );
40 $properties[$propertyname] = 1;
41 if ( $v->GetTag() == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
46 $properties['allprop'] = 1;
47 if ( $qry_content[$idx]->GetTag() == 'DAV::include' ) {
48 foreach( $qry_content[$idx]->GetElements() AS $k => $v ) {
49 $include_properties[] = $v->GetTag(); /** $include_properties is referenced in DAVResource where allprop is expanded */
50 if ( $v->GetTag() == 'urn:ietf:params:xml:ns:caldav:calendar-data' ) check_for_expansion($v);
58 * There can only be *one* FILTER element, and it must contain *one* COMP-FILTER
59 * element. In every case I can see this contained COMP-FILTER element will
60 * necessarily be a VCALENDAR, which then may contain other COMP-FILTER etc.
62 $qry_filters = $xmltree->GetPath('/urn:ietf:params:xml:ns:caldav:calendar-query/urn:ietf:params:xml:ns:caldav:filter/*');
63 if ( count($qry_filters) != 1 ) $qry_filters = false;
67 * While we can construct our SQL to apply some filters in the query, other filters
68 * need to be checked against the retrieved record. This is for handling those ones.
70 * @param array $filter An array of XMLElement which is the filter definition
71 * @param string $item The database row retrieved for this calendar item
73 * @return boolean True if the check succeeded, false otherwise.
75 function apply_filter( $filters, $item ) {
76 global $session, $c, $request;
78 if ( count($filters) == 0 ) return true;
80 dbg_error_log("calquery","Applying filter for item '%s'", $item->dav_name
);
81 $ical = new vCalendar( $item->caldav_data
);
82 return $ical->StartFilter($filters);
87 * Process a filter fragment returning an SQL fragment
89 $need_post_filter = false;
91 function SqlFilterFragment( $filter, $components, $property = null, $parameter = null ) {
92 global $need_post_filter, $range_filter, $target_collection;
95 if ( !is_array($filter) ) {
96 dbg_error_log( "calquery", "Filter is of type '%s', but should be an array of XML Tags.", gettype($filter) );
99 foreach( $filter AS $k => $v ) {
101 dbg_error_log("calquery", "Processing $tag into SQL - %d, '%s', %d\n", count($components), $property, isset($parameter) );
105 case 'urn:ietf:params:xml:ns:caldav:is-not-defined':
106 $not_defined = "not-"; // then fall through to IS-DEFINED case
107 case 'urn:ietf:params:xml:ns:caldav:is-defined':
108 if ( isset( $parameter ) ) {
109 $need_post_filter = true;
110 dbg_error_log("calquery", "Could not handle 'is-%sdefined' on property %s, parameter %s in SQL", $not_defined, $property, $parameter );
111 return false; // Not handled in SQL
113 if ( isset( $property ) ) {
114 switch( $property ) {
116 case 'completed': /** @todo when it can be handled in the SQL - see around line 200 below */
120 if ( ! $target_collection->IsSchedulingCollection() ) {
121 $property_defined_match = "IS NOT NULL";
126 $property_defined_match = "IS NOT NULL";
130 $property_defined_match = "LIKE '_%'"; // i.e. contains a single character or more
132 $sql .= sprintf( "AND %s %s%s ", $property, $not_defined, $property_defined_match );
136 case 'urn:ietf:params:xml:ns:caldav:time-range':
138 * @todo We should probably allow time range queries against other properties, since
139 * eventually some client may want to do this.
141 $start_column = ($components[sizeof($components)-1] == 'VTODO' ?
"due" : 'dtend'); // The column we compare against the START attribute
142 $finish_column = 'dtstart'; // The column we compare against the END attribute
143 $start = $v->GetAttribute("start");
144 $finish = $v->GetAttribute("end");
145 $start_sql = $finish_sql = '';
146 if ( isset($start) ) {
147 $params[':time_range_start'] = $start;
148 $start_sql .= ' (('.$start_column.' IS NULL AND '.$finish_column.' > :time_range_start) OR '.$start_column.' > :time_range_start) ';
150 if ( isset($finish) ) {
151 $params[':time_range_end'] = $finish;
152 $finish_sql = ' '.$finish_column.' < :time_range_end ';
154 if ( isset($start) ||
isset($finish) ) {
155 $sql .= ' AND (rrule IS NOT NULL OR '.$finish_column.' IS NULL OR (';
156 if ( isset($start) ) $sql .= $start_sql;
157 if ( isset($start) && isset($finish) ) $sql .= ' AND ';
158 if ( isset($finish) ) $sql .= $finish_sql;
161 @dbg_error_log
('calquery', 'filter-sql: %s', $sql);
162 @dbg_error_log
('calquery', 'time-range-start: %s, time-range-end: %s, ', $params[':time_range_start'], $params[':time_range_end']);
163 $range_filter = new RepeatRuleDateRange((empty($start) ?
null : new RepeatRuleDateTime($start)),
164 (empty($finish)?
null : new RepeatRuleDateTime($finish)));
167 case 'urn:ietf:params:xml:ns:caldav:text-match':
168 $search = $v->GetContent();
169 $negate = $v->GetAttribute("negate-condition");
170 $collation = $v->GetAttribute("collation");
171 switch( strtolower($collation) ) {
173 $comparison = 'LIKE';
175 case 'i;ascii-casemap':
177 $comparison = 'ILIKE';
180 $params[':text_match'] = '%'.$search.'%';
181 $fragment = sprintf( 'AND (%s%s %s :text_match) ',
182 (isset($negate) && strtolower($negate) == "yes" ?
$property.' IS NULL OR NOT ': ''),
183 $property, $comparison );
184 dbg_error_log('calquery', ' text-match: %s', $fragment );
188 case 'urn:ietf:params:xml:ns:caldav:comp-filter':
189 $comp_filter_name = $v->GetAttribute("name");
190 if ( $comp_filter_name != 'VCALENDAR' && count($components) == 0 ) {
191 $sql .= "AND caldav_data.caldav_type = :component_name_filter ";
192 $params[':component_name_filter'] = $comp_filter_name;
193 $components[] = $comp_filter_name;
195 $subfilter = $v->GetContent();
196 if ( is_array( $subfilter ) ) {
197 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
198 if ( $success === false ) continue; else {
199 $sql .= $success['sql'];
200 $params = array_merge( $params, $success['params'] );
205 case 'urn:ietf:params:xml:ns:caldav:prop-filter':
206 $propertyname = $v->GetAttribute("name");
207 switch( $propertyname ) {
208 case 'PERCENT-COMPLETE':
209 $subproperty = 'percent_complete';
218 case 'RRULE': // Likely that this is not much use
227 $subproperty = 'calendar_item.'.strtolower($propertyname);
230 case 'COMPLETED': /** @todo this should be moved into the properties supported in SQL. */
232 $need_post_filter = true;
233 dbg_error_log("calquery", "Could not handle 'prop-filter' on %s in SQL", $propertyname );
236 if ( isset($subproperty) ) {
237 $subfilter = $v->GetContent();
238 $success = SqlFilterFragment( $subfilter, $components, $subproperty, $parameter );
239 if ( $success === false ) continue; else {
240 $sql .= $success['sql'];
241 $params = array_merge( $params, $success['params'] );
246 case 'urn:ietf:params:xml:ns:caldav:param-filter':
247 $need_post_filter = true;
248 return false; // Can't handle PARAM-FILTER conditions in the SQL
249 $parameter = $v->GetAttribute("name");
250 $subfilter = $v->GetContent();
251 $success = SqlFilterFragment( $subfilter, $components, $property, $parameter );
252 if ( $success === false ) continue; else {
253 $sql .= $success['sql'];
254 $params = array_merge( $params, $success['params'] );
259 dbg_error_log("calquery", "Could not handle unknown tag '%s' in calendar query report", $tag );
263 dbg_error_log("calquery", "Generated SQL was '%s'", $sql );
264 return array( 'sql' => $sql, 'params' => $params );
268 * Build an SQL 'WHERE' clause which implements (parts of) the filter. The
269 * elements of the filter which are implemented in the SQL will be removed.
271 * @param arrayref &$filter A reference to an array of XMLElement defining the filter
273 * @return string A string suitable for use as an SQL 'WHERE' clause selecting the desired records.
275 function BuildSqlFilter( $filter ) {
276 $components = array();
277 if ( $filter->GetTag() == "urn:ietf:params:xml:ns:caldav:comp-filter" && $filter->GetAttribute("name") == "VCALENDAR" )
278 $filter = $filter->GetContent(); // Everything is inside a VCALENDAR AFAICS
280 dbg_error_log("calquery", "Got bizarre CALDAV:FILTER[%s=%s]] which does not contain comp-filter = VCALENDAR!!", $filter->GetTag(), $filter->GetAttribute("name") );
282 return SqlFilterFragment( $filter, $components );
287 * Something that we can handle, at least roughly correctly.
290 $responses = array();
291 $target_collection = new DAVResource($request->path
);
292 $bound_from = $target_collection->bound_from();
293 if ( !$target_collection->Exists() ) {
294 $request->DoResponse( 404 );
298 $where = ' WHERE caldav_data.collection_id = ' . $target_collection->resource_id();
300 if ( ! ($target_collection->IsCalendar() ||
$target_collection->IsSchedulingCollection()) ) {
301 if ( !(isset($c->allow_recursive_report
) && $c->allow_recursive_report
) ||
$target_collection->IsSchedulingCollection() ) {
302 $request->DoResponse( 403, translate('The calendar-query report must be run against a calendar or a scheduling collection') );
305 * We're here because they allow recursive reports, and this appears to be such a location.
307 $where = 'WHERE (collection.dav_name ~ :path_match ';
308 $where .= 'OR collection.collection_id IN (SELECT bound_source_id FROM dav_binding WHERE dav_binding.dav_name ~ :path_match)) ';
309 $params = array( ':path_match' => '^'.$target_collection->bound_from() );
312 if ( is_array($qry_filters) ) {
313 dbg_log_array( "calquery", "qry_filters", $qry_filters, true );
314 $components = array();
315 $filter_fragment = SqlFilterFragment( $qry_filters, $components );
316 if ( $filter_fragment !== false ) {
317 $where .= ' '.$filter_fragment['sql'];
318 $params = array_merge( $params, $filter_fragment['params']);
321 if ( $target_collection->Privileges() != privilege_to_bits('DAV::all') ) {
322 $where .= " AND (calendar_item.class != 'PRIVATE' OR calendar_item.class IS NULL) ";
325 if ( isset($c->hide_TODO
) && $c->hide_TODO
&& ! $target_collection->HavePrivilegeTo('DAV::write-content') ) {
326 $where .= " AND caldav_data.caldav_type NOT IN ('VTODO') ";
329 if ( isset($c->hide_older_than
) && intval($c->hide_older_than
> 0) ) {
330 $where .= " AND calendar_item.dtstart > (now() - interval '".intval($c->hide_older_than
)." days') ";
333 $sql = 'SELECT caldav_data.*,calendar_item.* FROM collection INNER JOIN caldav_data USING(collection_id) INNER JOIN calendar_item USING(dav_id) '. $where;
334 if ( isset($c->strict_result_ordering
) && $c->strict_result_ordering
) $sql .= " ORDER BY caldav_data.dav_id";
335 $qry = new AwlQuery( $sql, $params );
336 if ( $qry->Exec("calquery",__LINE__
,__FILE__
) && $qry->rows() > 0 ) {
337 while( $dav_object = $qry->Fetch() ) {
338 if ( !$need_post_filter ||
apply_filter( $qry_filters, $dav_object ) ) {
339 if ( $bound_from != $target_collection->dav_name() ) {
340 $dav_object->dav_name
= str_replace( $bound_from, $target_collection->dav_name(), $dav_object->dav_name
);
342 if ( $need_expansion ) {
343 $vResource = new vComponent($dav_object->caldav_data
);
344 $expanded = getVCalendarRange($vResource);
345 if ( !$expanded->overlaps($range_filter) ) continue;
347 $expanded = expand_event_instances($vResource, $expand_range_start, $expand_range_end, $expand_as_floating );
349 if ( $expanded->ComponentCount() == 0 ) continue;
350 if ( $need_expansion ) $dav_object->caldav_data
= $expanded->Render();
352 else if ( isset($range_filter) ) {
353 $vResource = new vComponent($dav_object->caldav_data
);
354 $expanded = getVCalendarRange($vResource);
355 dbg_error_log('calquery', 'Expanded to %s:%s which might overlap %s:%s',
356 $expanded->from
, $expanded->until
, $range_filter->from
, $range_filter->until
);
357 if ( !$expanded->overlaps($range_filter) ) continue;
359 $responses[] = component_to_xml( $properties, $dav_object );
364 $multistatus = new XMLElement( "multistatus", $responses, $reply->GetXmlNsArray() );
366 $request->XMLResponse( 207, $multistatus );