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