3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_ProximityQuery
{
38 * Trigonometry for calculating geographical distances.
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
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
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);
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
57 static protected $_earthFlattening;
58 static protected $_earthRadiusSemiMinor;
59 static protected $_earthRadiusSemiMajor;
60 static protected $_earthEccentricitySQ;
62 static function initialize() {
63 static $_initialized = FALSE;
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);
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.
83 * Estimate the Earth's radius at a given latitude.
84 * Default to an approximate average radius for the United States.
87 static function earthRadius($latitude) {
88 $lat = deg2rad($latitude);
90 $x = cos($lat) / self
::$_earthRadiusSemiMajor;
91 $y = sin($lat) / self
::$_earthRadiusSemiMinor;
92 return 1.0 / sqrt($x * $x +
$y * $y);
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.
99 static function earthXYZ($longitude, $latitude, $height = 0) {
100 $long = deg2rad($longitude);
101 $lat = deg2rad($latitude);
103 $cosLong = cos($long);
105 $sinLong = sin($long);
108 $radius = self
::$_earthRadiusSemiMajor / sqrt(1 - self
::$_earthEccentricitySQ * $sinLat * $sinLat);
110 $x = ($radius +
$height) * $cosLat * $cosLong;
111 $y = ($radius +
$height) * $cosLat * $sinLong;
112 $z = ($radius * (1 - self
::$_earthEccentricitySQ) +
$height) * $sinLat;
114 return array($x, $y, $z);
118 * Convert a given angle to earth-surface distance.
120 static function earthArcLength($angle, $latitude) {
121 return deg2rad($angle) * self
::earthRadius($latitude);
125 * Estimate the min and max longitudes within $distance of a given location.
127 static function earthLongitudeRange($longitude, $latitude, $distance) {
128 $long = deg2rad($longitude);
129 $lat = deg2rad($latitude);
130 $radius = self
::earthRadius($latitude);
132 $angle = $distance / $radius;
133 $diff = asin(sin($angle) / cos($lat));
134 $minLong = $long - $diff;
135 $maxLong = $long +
$diff;
137 if ($minLong < - pi()) {
138 $minLong = $minLong +
pi() * 2;
141 if ($maxLong > pi()) {
142 $maxLong = $maxLong - pi() * 2;
145 return array(rad2deg($minLong),
151 * Estimate the min and max latitudes within $distance of a given location.
153 static function earthLatitudeRange($longitude, $latitude, $distance) {
154 $long = deg2rad($longitude);
155 $lat = deg2rad($latitude);
156 $radius = self
::earthRadius($latitude);
158 $angle = $distance / $radius;
159 $minLat = $lat - $angle;
160 $maxLat = $lat +
$angle;
161 $rightangle = pi() / 2.0;
163 // wrapped around the south pole
164 if ($minLat < - $rightangle) {
165 $overshoot = -$minLat - $rightangle;
166 $minLat = -$rightangle +
$overshoot;
167 if ($minLat > $maxLat) {
170 $minLat = -$rightangle;
173 // wrapped around the north pole
174 if ($maxLat > $rightangle) {
175 $overshoot = $maxLat - $rightangle;
176 $maxLat = $rightangle - $overshoot;
177 if ($maxLat < $minLat) {
180 $maxLat = $rightangle;
183 return array(rad2deg($minLat),
192 * @param string $tablePrefix
196 static function where($latitude, $longitude, $distance, $tablePrefix = 'civicrm_address') {
202 list($minLongitude, $maxLongitude) =
203 self
::earthLongitudeRange($longitude,
207 list($minLatitude, $maxLatitude) =
208 self
::earthLatitudeRange(
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 ";
220 if (!is_nan($maxLatitude)) {
221 $geoCodeWhere[] = "{$tablePrefix}.geo_code_1 <= $maxLatitude ";
223 if (!is_nan($minLongitude)) {
224 $geoCodeWhere[] = "{$tablePrefix}.geo_code_2 >= $minLongitude ";
226 if (!is_nan($maxLongitude)) {
227 $geoCodeWhere[] = "{$tablePrefix}.geo_code_2 <= $maxLongitude ";
229 $geoCodeWhereClause = implode(' AND ', $geoCodeWhere);
232 {$geoCodeWhereClause} AND
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
250 static function process(&$query, &$values) {
251 list($name, $op, $distance, $grouping, $wildcard) = $values;
253 // also get values array for all address related info
254 $proximityVars = array(
255 'street_address' => 1,
258 'state_province_id' => 0,
260 'state_province' => 0,
262 'distance_unit' => 0,
265 $proximityAddress = array();
267 foreach ($proximityVars as $var => $recordQill) {
268 $proximityValues = $query->getWhereValues("prox_{$var}", $grouping);
269 if (!empty($proximityValues) &&
270 !empty($proximityValues[2])
272 $proximityAddress[$var] = $proximityValues[2];
274 $qill[] = $proximityValues[2];
279 if (empty($proximityAddress)) {
283 if (isset($proximityAddress['state_province_id'])) {
284 $proximityAddress['state_province'] = CRM_Core_PseudoConstant
::stateProvince($proximityAddress['state_province_id']);
285 $qill[] = $proximityAddress['state_province'];
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
::countryForState($proximityAddress['state_province_id']);
294 elseif (isset($config->defaultContactCountry
)) {
295 $proximityAddress['country_id'] = $config->defaultContactCountry
;
299 if (isset($proximityAddress['country_id'])) {
300 $proximityAddress['country'] = CRM_Core_PseudoConstant
::country($proximityAddress['country_id']);
301 $qill[] = $proximityAddress['country'];
306 isset($proximityAddress['distance_unit']) &&
307 $proximityAddress['distance_unit'] == 'miles'
309 $qillUnits = " {$distance} " . ts('miles');
310 $distance = $distance * 1609.344;
313 $qillUnits = " {$distance} " . ts('km');
314 $distance = $distance * 1000.00;
317 $qill = ts('Proximity search to a distance of %1 from %2',
320 2 => implode(', ', $qill)
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'));
329 $query->_tables
['civicrm_address'] = $query->_whereTables
['civicrm_address'] = 1;
331 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $fnName) . '.php');
332 $fnName::format($proximityAddress);
334 !is_numeric(CRM_Utils_Array
::value('geo_code_1', $proximityAddress)) ||
335 !is_numeric(CRM_Utils_Array
::value('geo_code_2', $proximityAddress))
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) ';
344 $query->_qill
[$grouping][] = $qill;
345 $query->_where
[$grouping][] = self
::where(
346 $proximityAddress['geo_code_1'],
347 $proximityAddress['geo_code_2'],
357 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');
363 foreach ($input as $key => $_param) {
364 if (in_array($_param[0], $param_alter)) {
365 $input[$key][0] = 'prox_' . $_param[0];
367 // _id suffix where needed
368 if ($_param[0] == 'country' ||
$_param[0] == 'state_province') {
369 $input[$key][0] .= '_id';
371 // flatten state_province array
372 if (is_array($input[$key][2])) {
373 $input[$key][2] = $input[$key][2][0];