Merge pull request #4875 from civicrm/minor-fix
[civicrm-core.git] / CRM / Utils / Geocode / Yahoo.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
36 /**
37 * Class that uses Yahoo! PlaceFinder API to retrieve the lat/long of an address
38 * Documentation is at http://developer.yahoo.com/geo/placefinder/
39 */
40 class CRM_Utils_Geocode_Yahoo {
41
42 /**
43 * Server to retrieve the lat/long
44 *
45 * @var string
46 * @static
47 */
48 static protected $_server = 'query.yahooapis.com';
49
50 /**
51 * Uri of service
52 *
53 * @var string
54 * @static
55 */
56 static protected $_uri = '/v1/public/yql';
57
58 /**
59 * Function that takes an address array and gets the latitude / longitude
60 * and postal code for this address. Note that at a later stage, we could
61 * make this function also clean up the address into a more valid format
62 *
63 * @param array $values
64 * Associative array of address data: country, street_address, city, state_province, postal code.
65 * @param bool $stateName
66 * This parameter currently has no function.
67 *
68 * @return boolean
69 * true if we modified the address, false otherwise
70 * @static
71 */
72 public static function format(&$values, $stateName = FALSE) {
73 CRM_Utils_System::checkPHPVersion(5, TRUE);
74
75 $config = CRM_Core_Config::singleton();
76
77 $whereComponents = array();
78
79 if (!empty($values['street_address'])) {
80 $whereComponents['street'] = $values['street_address'];
81 }
82
83 if ($city = CRM_Utils_Array::value('city', $values)) {
84 $whereComponents['city'] = $city;
85 }
86
87 if (!empty($values['state_province'])) {
88 if (!empty($values['state_province_id'])) {
89 $stateProvince = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $values['state_province_id']);
90 }
91 else {
92 if (!$stateName) {
93 $stateProvince = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince',
94 $values['state_province'],
95 'name',
96 'abbreviation'
97 );
98 }
99 else {
100 $stateProvince = $values['state_province'];
101 }
102 }
103
104 // dont add state twice if replicated in city (happens in NZ and other countries, CRM-2632)
105 if ($stateProvince != $city) {
106 $whereComponents['state'] = $stateProvince;
107 }
108 }
109
110 if (!empty($values['postal_code'])) {
111 $whereComponents['postal'] = $values['postal_code'];
112 }
113
114 if (!empty($values['country'])) {
115 $whereComponents['country'] = $values['country'];
116 }
117
118 foreach ($whereComponents as $componentName => $componentValue) {
119 $whereComponents[$componentName] = urlencode("$componentName=\"$componentValue\"");
120 }
121
122 $add = 'q=' . urlencode('select * from geo.placefinder where ');
123
124 $add .= join(urlencode(' and '), $whereComponents);
125
126 $add .= "&appid=" . urlencode($config->mapAPIKey);
127
128 $query = 'http://' . self::$_server . self::$_uri . '?' . $add;
129
130 require_once 'HTTP/Request.php';
131 $request = new HTTP_Request($query);
132 $request->sendRequest();
133 $string = $request->getResponseBody();
134 // see CRM-11359 for why we suppress errors with @
135 $xml = @simplexml_load_string($string);
136
137 if ($xml === FALSE) {
138 // account blocked maybe?
139 CRM_Core_Error::debug_var('Geocoding failed. Message from Yahoo:', $string);
140 return FALSE;
141 }
142
143 if ($xml->getName() == 'error') {
144 CRM_Core_Error::debug_var('query', $query);
145 CRM_Core_Error::debug_log_message('Geocoding failed. Message from Yahoo: ' . (string) $xml->description);
146 return FALSE;
147 }
148
149 if (is_a($xml->results->Result, 'SimpleXMLElement')) {
150 $result = array();
151 $result = get_object_vars($xml->results->Result);
152 foreach ($result as $key => $val) {
153 if (is_scalar($val) &&
154 strlen($val)
155 ) {
156 $ret[(string) $key] = (string) $val;
157 }
158 }
159
160 $values['geo_code_1'] = $ret['latitude'];
161 $values['geo_code_2'] = $ret['longitude'];
162
163 if (!empty($ret['postal'])) {
164 $current_pc = CRM_Utils_Array::value('postal_code', $values);
165 $skip_postal = FALSE;
166
167 if ($current_pc) {
168 $current_pc_suffix = CRM_Utils_Array::value('postal_code_suffix', $values);
169 $current_pc_complete = $current_pc . $current_pc_suffix;
170 $new_pc_complete = preg_replace("/[+-]/", '', $ret['postal']);
171
172 // if a postal code was already entered, don't change it, except to make it more precise
173 if (strpos($new_pc_complete, $current_pc_complete) !== 0) {
174 // Don't bother anonymous users with the message - they can't change a form they just submitted anyway
175 if (CRM_Utils_System::isUserLoggedIn()) {
176 $msg = ts('The Yahoo Geocoding system returned a different postal code (%1) than the one you entered (%2). If you want the Yahoo value, please delete the current postal code and save again.', array(
177 1 => $ret['postal'],
178 2 => $current_pc_suffix ? "$current_pc-$current_pc_suffix" : $current_pc,
179 ));
180
181 CRM_Core_Session::setStatus($msg, ts('Postal Code Mismatch'), 'error');
182 }
183 $skip_postal = TRUE;
184 }
185 }
186
187 if (!$skip_postal) {
188 $values['postal_code'] = $ret['postal'];
189
190 /* the following logic to split the string was borrowed from
191 CRM/Core/BAO/Address.php -- CRM_Core_BAO_Address::fixAddress.
192 This is actually the function that calls the geocoding
193 script to begin with, but the postal code business takes
194 place before geocoding gets called.
195 */
196
197 if (preg_match('/^(\d{4,5})[+-](\d{4})$/',
198 $ret['postal'],
199 $match
200 )
201 ) {
202 $values['postal_code'] = $match[1];
203 $values['postal_code_suffix'] = $match[2];
204 }
205 }
206 }
207 return TRUE;
208 }
209
210 // reset the geo code values if we did not get any good values
211 $values['geo_code_1'] = $values['geo_code_2'] = 'null';
212 return FALSE;
213 }
214 }