A more efficient query for GET including sub-collections.
[davical.git] / inc / caldav-REPORT-cardquery.php
blob0aefbe62b05dc1a24384dab48b5fd45c46332a41
1 <?php
3 require_once('vcard.php');
5 $address_data_properties = array();
6 function get_address_properties( $address_data_xml ) {
7 global $address_data_properties;
8 $expansion = $address_data_xml->GetElements();
9 foreach( $expansion AS $k => $v ) {
10 if ( $v instanceof XMLElement )
11 $address_data_properties[strtoupper($v->GetAttribute('name'))] = true;
16 /**
17 * Build the array of properties to include in the report output
19 $qry_content = $xmltree->GetContent('urn:ietf:params:xml:ns:carddav:addressbook-query');
20 $proptype = $qry_content[0]->GetNSTag();
21 $properties = array();
22 switch( $proptype ) {
23 case 'DAV::prop':
24 $qry_props = $xmltree->GetPath('/urn:ietf:params:xml:ns:carddav:addressbook-query/'.$proptype.'/*');
25 foreach( $qry_content[0]->GetElements() AS $k => $v ) {
26 $properties[$v->GetNSTag()] = 1;
27 if ( $v->GetNSTag() == 'urn:ietf:params:xml:ns:carddav:address-data' ) get_address_properties($v);
29 break;
31 case 'DAV::allprop':
32 $properties['allprop'] = 1;
33 if ( $qry_content[1]->GetNSTag() == 'DAV::include' ) {
34 foreach( $qry_content[1]->GetElements() AS $k => $v ) {
35 $include_properties[] = $v->GetNSTag(); /** $include_properties is referenced in DAVResource where allprop is expanded */
36 if ( $v->GetNSTag() == 'urn:ietf:params:xml:ns:carddav:address-data' ) get_address_properties($v);
39 break;
41 default:
42 $properties[$proptype] = 1;
45 /**
46 * There can only be *one* FILTER element.
48 $qry_filters = $xmltree->GetPath('/urn:ietf:params:xml:ns:carddav:addressbook-query/urn:ietf:params:xml:ns:carddav:filter/*');
49 if ( count($qry_filters) != 1 ) {
50 /* $qry_filters = $qry_filters[0]; // There can only be one FILTER element
52 else { */
53 $qry_filters = false;
57 /**
58 * While we can construct our SQL to apply some filters in the query, other filters
59 * need to be checked against the retrieved record. This is for handling those ones.
61 * @param array $filter An array of XMLElement which is the filter definition
62 * @param string $item The database row retrieved for this calendar item
64 * @return boolean True if the check succeeded, false otherwise.
66 function apply_filter( $filters, $item ) {
67 global $session, $c, $request;
69 if ( count($filters) == 0 ) return true;
71 dbg_error_log("cardquery","Applying filter for item '%s'", $item->dav_name );
72 $vcard = new vComponent( $item->caldav_data );
73 return $vcard->TestFilter($filters);
77 /**
78 * Process a filter fragment returning an SQL fragment
80 $need_post_filter = false;
81 $matchnum = 0;
82 function SqlFilterCardDAV( $filter, $components, $property = null, $parameter = null ) {
83 global $need_post_filter, $target_collection, $matchnum;
84 $sql = "";
85 $params = array();
86 if ( !is_array($filter) ) {
87 dbg_error_log( "cardquery", "Filter is of type '%s', but should be an array of XML Tags.", gettype($filter) );
90 foreach( $filter AS $k => $v ) {
91 $tag = $v->GetNSTag();
92 dbg_error_log("cardquery", "Processing $tag into SQL - %d, '%s', %d\n", count($components), $property, isset($parameter) );
94 $not_defined = "";
95 switch( $tag ) {
96 case 'urn:ietf:params:xml:ns:carddav:text-match':
97 $search = $v->GetContent();
98 $negate = $v->GetAttribute("negate-condition");
99 $collation = $v->GetAttribute("collation");
100 switch( strtolower($collation) ) {
101 case 'i;octet':
102 $comparison = 'LIKE';
103 break;
104 case 'i;ascii-casemap':
105 case 'i;unicode-casemap':
106 default:
107 $comparison = 'ILIKE';
108 break;
110 $pname = ':text_match_'.$matchnum++;
111 $params[$pname] = '%'.$search.'%';
112 dbg_error_log("cardquery", " text-match: (%s%s %s '%s') ", (isset($negate) && strtolower($negate) == "yes" ? "NOT ": ""),
113 $property, $comparison, $params[$pname] );
114 $sql .= sprintf( "AND (%s%s %s $pname) ", (isset($negate) && strtolower($negate) == "yes" ? "NOT ": ""),
115 $property, $comparison );
116 break;
118 case 'urn:ietf:params:xml:ns:carddav:prop-filter':
119 $propertyname = $v->GetAttribute("name");
120 switch( $propertyname ) {
121 case 'VERSION':
122 case 'UID':
123 case 'NICKNAME':
124 case 'FN':
125 case 'NOTE':
126 case 'ORG':
127 case 'URL':
128 case 'FBURL':
129 case 'CALADRURI':
130 case 'CALURI':
131 $property = strtolower($propertyname);
132 break;
134 case 'N':
135 $property = 'name';
136 break;
138 default:
139 $need_post_filter = true;
140 dbg_error_log("cardquery", "Could not handle 'prop-filter' on %s in SQL", $propertyname );
141 continue;
143 $subfilter = $v->GetContent();
144 $success = SqlFilterCardDAV( $subfilter, $components, $property, $parameter );
145 if ( $success === false ) continue; else {
146 $sql .= $success['sql'];
147 $params = array_merge( $params, $success['params'] );
149 break;
151 case 'urn:ietf:params:xml:ns:carddav:param-filter':
152 $need_post_filter = true;
153 return false; /** Figure out how to handle PARAM-FILTER conditions in the SQL */
155 $parameter = $v->GetAttribute("name");
156 $subfilter = $v->GetContent();
157 $success = SqlFilterCardDAV( $subfilter, $components, $property, $parameter );
158 if ( $success === false ) continue; else {
159 $sql .= $success['sql'];
160 $params = array_merge( $params, $success['params'] );
162 break;
165 default:
166 dbg_error_log("cardquery", "Could not handle unknown tag '%s' in calendar query report", $tag );
167 break;
170 dbg_error_log("cardquery", "Generated SQL was '%s'", $sql );
171 return array( 'sql' => $sql, 'params' => $params );
176 * Something that we can handle, at least roughly correctly.
179 $responses = array();
180 $target_collection = new DAVResource($request->path);
181 $bound_from = $target_collection->bound_from();
182 if ( !$target_collection->Exists() ) {
183 $request->DoResponse( 404 );
185 if ( ! ($target_collection->IsAddressbook() || $target_collection->IsSchedulingCollection()) ) {
186 $request->DoResponse( 403, translate('The addressbook-query report must be run against an addressbook collection') );
190 * @todo Once we are past DB version 1.2.1 we can change this query more radically. The best performance to
191 * date seems to be:
192 * SELECT caldav_data.*,address_item.* FROM collection JOIN address_item USING (collection_id,user_no)
193 * JOIN caldav_data USING (dav_id) WHERE collection.dav_name = '/user1/home/'
194 * AND caldav_data.caldav_type = 'VEVENT' ORDER BY caldav_data.user_no, caldav_data.dav_name;
197 $params = array();
198 $where = ' WHERE caldav_data.collection_id = ' . $target_collection->resource_id();
199 if ( is_array($qry_filters) ) {
200 dbg_log_array( 'cardquery', 'qry_filters', $qry_filters, true );
201 $components = array();
202 $filter_fragment = SqlFilterCardDAV( $qry_filters, $components );
203 if ( $filter_fragment !== false ) {
204 $where .= ' '.$filter_fragment['sql'];
205 $params = $filter_fragment['params'];
208 else {
209 dbg_error_log( 'cardquery', 'No query filters' );
212 $sql = 'SELECT * FROM caldav_data INNER JOIN addressbook_resource USING(dav_id)'. $where;
213 if ( isset($c->strict_result_ordering) && $c->strict_result_ordering ) $sql .= " ORDER BY dav_id";
214 $qry = new AwlQuery( $sql, $params );
215 if ( $qry->Exec("cardquery",__LINE__,__FILE__) && $qry->rows() > 0 ) {
216 while( $address_object = $qry->Fetch() ) {
217 if ( !$need_post_filter || apply_filter( $qry_filters, $address_object ) ) {
218 if ( $bound_from != $target_collection->dav_name() ) {
219 $address_object->dav_name = str_replace( $bound_from, $target_collection->dav_name(), $address_object->dav_name);
221 if ( count($address_data_properties) > 0 ) {
222 $vcard = new VCard($address_object->caldav_data);
223 $vcard->MaskProperties($address_data_properties);
224 $address_object->caldav_data = $vcard->Render();
226 $responses[] = component_to_xml( $properties, $address_object );
230 $multistatus = new XMLElement( "multistatus", $responses, $reply->GetXmlNsArray() );
232 $request->XMLResponse( 207, $multistatus );