INFRA-132 - Trailing commas for multiline arrays
[civicrm-core.git] / CRM / Contact / BAO / ProximityQuery.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Contact_BAO_ProximityQuery {
36
37 /**
38 * Trigonometry for calculating geographical distances.
39 *
40 * Modification made in: CRM-13904
41 * http://en.wikipedia.org/wiki/Great-circle_distance
42 * http://www.movable-type.co.uk/scripts/latlong.html
43 *
44 * All function arguments and return values measure distances in metres
45 * and angles in degrees. The ellipsoid model is from the WGS-84 datum.
46 * Ka-Ping Yee, 2003-08-11
47
48 * earth_radius_semimajor = 6378137.0;
49 * earth_flattening = 1/298.257223563;
50 * earth_radius_semiminor = $earth_radius_semimajor * (1 - $earth_flattening);
51 * earth_eccentricity_sq = 2*$earth_flattening - pow($earth_flattening, 2);
52
53 * This library is an implementation of UCB CS graduate student, Ka-Ping Yee (http://www.zesty.ca).
54 * This version has been taken from Drupal's location module: http://drupal.org/project/location
55 **/
56
57 static protected $_earthFlattening;
58 static protected $_earthRadiusSemiMinor;
59 static protected $_earthRadiusSemiMajor;
60 static protected $_earthEccentricitySQ;
61
62 public static function initialize() {
63 static $_initialized = FALSE;
64
65 if (!$_initialized) {
66 $_initialized = TRUE;
67
68 self::$_earthFlattening = 1.0 / 298.257223563;
69 self::$_earthRadiusSemiMajor = 6378137.0;
70 self::$_earthRadiusSemiMinor = self::$_earthRadiusSemiMajor * (1.0 - self::$_earthFlattening);
71 self::$_earthEccentricitySQ = 2 * self::$_earthFlattening - pow(self::$_earthFlattening, 2);
72 }
73 }
74
75 /**
76 * Latitudes in all of U. S.: from -7.2 (American Samoa) to 70.5 (Alaska).
77 * Latitudes in continental U. S.: from 24.6 (Florida) to 49.0 (Washington).
78 * Average latitude of all U. S. zipcodes: 37.9.
79 */
80
81 /*
82 /**
83 * Estimate the Earth's radius at a given latitude.
84 * Default to an approximate average radius for the United States.
85 */
86
87 public static function earthRadius($latitude) {
88 $lat = deg2rad($latitude);
89
90 $x = cos($lat) / self::$_earthRadiusSemiMajor;
91 $y = sin($lat) / self::$_earthRadiusSemiMinor;
92 return 1.0 / sqrt($x * $x + $y * $y);
93 }
94
95 /**
96 * Convert longitude and latitude to earth-centered earth-fixed coordinates.
97 * X axis is 0 long, 0 lat; Y axis is 90 deg E; Z axis is north pole.
98 */
99 public static function earthXYZ($longitude, $latitude, $height = 0) {
100 $long = deg2rad($longitude);
101 $lat = deg2rad($latitude);
102
103 $cosLong = cos($long);
104 $cosLat = cos($lat);
105 $sinLong = sin($long);
106 $sinLat = sin($lat);
107
108 $radius = self::$_earthRadiusSemiMajor / sqrt(1 - self::$_earthEccentricitySQ * $sinLat * $sinLat);
109
110 $x = ($radius + $height) * $cosLat * $cosLong;
111 $y = ($radius + $height) * $cosLat * $sinLong;
112 $z = ($radius * (1 - self::$_earthEccentricitySQ) + $height) * $sinLat;
113
114 return array($x, $y, $z);
115 }
116
117 /**
118 * Convert a given angle to earth-surface distance.
119 */
120 public static function earthArcLength($angle, $latitude) {
121 return deg2rad($angle) * self::earthRadius($latitude);
122 }
123
124 /**
125 * Estimate the min and max longitudes within $distance of a given location.
126 */
127 public static function earthLongitudeRange($longitude, $latitude, $distance) {
128 $long = deg2rad($longitude);
129 $lat = deg2rad($latitude);
130 $radius = self::earthRadius($latitude);
131
132 $angle = $distance / $radius;
133 $diff = asin(sin($angle) / cos($lat));
134 $minLong = $long - $diff;
135 $maxLong = $long + $diff;
136
137 if ($minLong < - pi()) {
138 $minLong = $minLong + pi() * 2;
139 }
140
141 if ($maxLong > pi()) {
142 $maxLong = $maxLong - pi() * 2;
143 }
144
145 return array(rad2deg($minLong),
146 rad2deg($maxLong),
147 );
148 }
149
150 /**
151 * Estimate the min and max latitudes within $distance of a given location.
152 */
153 public static function earthLatitudeRange($longitude, $latitude, $distance) {
154 $long = deg2rad($longitude);
155 $lat = deg2rad($latitude);
156 $radius = self::earthRadius($latitude);
157
158 $angle = $distance / $radius;
159 $minLat = $lat - $angle;
160 $maxLat = $lat + $angle;
161 $rightangle = pi() / 2.0;
162
163 // wrapped around the south pole
164 if ($minLat < - $rightangle) {
165 $overshoot = -$minLat - $rightangle;
166 $minLat = -$rightangle + $overshoot;
167 if ($minLat > $maxLat) {
168 $maxLat = $minLat;
169 }
170 $minLat = -$rightangle;
171 }
172
173 // wrapped around the north pole
174 if ($maxLat > $rightangle) {
175 $overshoot = $maxLat - $rightangle;
176 $maxLat = $rightangle - $overshoot;
177 if ($maxLat < $minLat) {
178 $minLat = $maxLat;
179 }
180 $maxLat = $rightangle;
181 }
182
183 return array(rad2deg($minLat),
184 rad2deg($maxLat),
185 );
186 }
187
188 /**
189 * @param $latitude
190 * @param $longitude
191 * @param $distance
192 * @param string $tablePrefix
193 *
194 * @return string
195 */
196 public static function where($latitude, $longitude, $distance, $tablePrefix = 'civicrm_address') {
197 self::initialize();
198
199 $params = array();
200 $clause = array();
201
202 list($minLongitude, $maxLongitude) =
203 self::earthLongitudeRange($longitude,
204 $latitude,
205 $distance
206 );
207 list($minLatitude, $maxLatitude) =
208 self::earthLatitudeRange(
209 $longitude,
210 $latitude,
211 $distance
212 );
213
214 // DONT consider NAN values (which is returned by rad2deg php function)
215 // for checking BETWEEN geo_code's criteria as it throws obvious 'NAN' field not found DB: Error
216 $geoCodeWhere = array();
217 if (!is_nan($minLatitude)) {
218 $geoCodeWhere[] = "{$tablePrefix}.geo_code_1 >= $minLatitude ";
219 }
220 if (!is_nan($maxLatitude)) {
221 $geoCodeWhere[] = "{$tablePrefix}.geo_code_1 <= $maxLatitude ";
222 }
223 if (!is_nan($minLongitude)) {
224 $geoCodeWhere[] = "{$tablePrefix}.geo_code_2 >= $minLongitude ";
225 }
226 if (!is_nan($maxLongitude)) {
227 $geoCodeWhere[] = "{$tablePrefix}.geo_code_2 <= $maxLongitude ";
228 }
229 $geoCodeWhereClause = implode(' AND ', $geoCodeWhere);
230
231 $where = "
232 {$geoCodeWhereClause} AND
233 ACOS(
234 COS(RADIANS({$tablePrefix}.geo_code_1)) *
235 COS(RADIANS($latitude)) *
236 COS(RADIANS({$tablePrefix}.geo_code_2) - RADIANS($longitude)) +
237 SIN(RADIANS({$tablePrefix}.geo_code_1)) *
238 SIN(RADIANS($latitude))
239 ) * 6378137 <= $distance
240 ";
241 return $where;
242 }
243
244 /**
245 * @param $query
246 * @param $values
247 *
248 * @throws Exception
249 */
250 public static function process(&$query, &$values) {
251 list($name, $op, $distance, $grouping, $wildcard) = $values;
252
253 // also get values array for all address related info
254 $proximityVars = array(
255 'street_address' => 1,
256 'city' => 1,
257 'postal_code' => 1,
258 'state_province_id' => 0,
259 'country_id' => 0,
260 'state_province' => 0,
261 'country' => 0,
262 'distance_unit' => 0,
263 );
264
265 $proximityAddress = array();
266 $qill = array();
267 foreach ($proximityVars as $var => $recordQill) {
268 $proximityValues = $query->getWhereValues("prox_{$var}", $grouping);
269 if (!empty($proximityValues) &&
270 !empty($proximityValues[2])
271 ) {
272 $proximityAddress[$var] = $proximityValues[2];
273 if ($recordQill) {
274 $qill[] = $proximityValues[2];
275 }
276 }
277 }
278
279 if (empty($proximityAddress)) {
280 return;
281 }
282
283 if (isset($proximityAddress['state_province_id'])) {
284 $proximityAddress['state_province'] = CRM_Core_PseudoConstant::stateProvince($proximityAddress['state_province_id']);
285 $qill[] = $proximityAddress['state_province'];
286 }
287
288 $config = CRM_Core_Config::singleton();
289 if (!isset($proximityAddress['country_id'])) {
290 // get it from state if state is present
291 if (isset($proximityAddress['state_province_id'])) {
292 $proximityAddress['country_id'] = CRM_Core_PseudoConstant::countryIDForStateID($proximityAddress['state_province_id']);
293 }
294 elseif (isset($config->defaultContactCountry)) {
295 $proximityAddress['country_id'] = $config->defaultContactCountry;
296 }
297 }
298
299 if (isset($proximityAddress['country_id'])) {
300 $proximityAddress['country'] = CRM_Core_PseudoConstant::country($proximityAddress['country_id']);
301 $qill[] = $proximityAddress['country'];
302 }
303
304
305 if (
306 isset($proximityAddress['distance_unit']) &&
307 $proximityAddress['distance_unit'] == 'miles'
308 ) {
309 $qillUnits = " {$distance} " . ts('miles');
310 $distance = $distance * 1609.344;
311 }
312 else {
313 $qillUnits = " {$distance} " . ts('km');
314 $distance = $distance * 1000.00;
315 }
316
317 $qill = ts('Proximity search to a distance of %1 from %2',
318 array(
319 1 => $qillUnits,
320 2 => implode(', ', $qill),
321 )
322 );
323
324 $fnName = isset($config->geocodeMethod) ? $config->geocodeMethod : NULL;
325 if (empty($fnName)) {
326 CRM_Core_Error::fatal(ts('Proximity searching requires you to set a valid geocoding provider'));
327 }
328
329 $query->_tables['civicrm_address'] = $query->_whereTables['civicrm_address'] = 1;
330
331 require_once (str_replace('_', DIRECTORY_SEPARATOR, $fnName) . '.php');
332 $fnName::format($proximityAddress);
333 if (
334 !is_numeric(CRM_Utils_Array::value('geo_code_1', $proximityAddress)) ||
335 !is_numeric(CRM_Utils_Array::value('geo_code_2', $proximityAddress))
336 ) {
337 // we are setting the where clause to 0 here, so we wont return anything
338 $qill .= ': ' . ts('We could not geocode the destination address.');
339 $query->_qill[$grouping][] = $qill;
340 $query->_where[$grouping][] = ' (0) ';
341 return;
342 }
343
344 $query->_qill[$grouping][] = $qill;
345 $query->_where[$grouping][] = self::where(
346 $proximityAddress['geo_code_1'],
347 $proximityAddress['geo_code_2'],
348 $distance
349 );
350
351 return;
352 }
353
354 /**
355 * @param $input
356 */
357 public static function fixInputParams(&$input) {
358 foreach ($input as $param) {
359 if (CRM_Utils_Array::value('0', $param) == 'prox_distance') {
360 // add prox_ prefix to these
361 $param_alter = array('street_address', 'city', 'postal_code', 'state_province', 'country');
362
363 foreach ($input as $key => $_param) {
364 if (in_array($_param[0], $param_alter)) {
365 $input[$key][0] = 'prox_' . $_param[0];
366
367 // _id suffix where needed
368 if ($_param[0] == 'country' || $_param[0] == 'state_province') {
369 $input[$key][0] .= '_id';
370
371 // flatten state_province array
372 if (is_array($input[$key][2])) {
373 $input[$key][2] = $input[$key][2][0];
374 }
375 }
376 }
377 }
378 return;
379 }
380 }
381 }
382 }