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