CRM-19784: Updated direct usages of the geocoding provider to use the
[civicrm-core.git] / CRM / Utils / Address / BatchUpdate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 */
33
34 /**
35 * A PHP cron script to format all the addresses in the database. Currently
36 * it only does geocoding if the geocode values are not set. At a later
37 * stage we will also handle USPS address cleanup and other formatting
38 * issues
39 */
40 class CRM_Utils_Address_BatchUpdate {
41
42 var $start = NULL;
43 var $end = NULL;
44 var $geocoding = 1;
45 var $parse = 1;
46 var $throttle = 0;
47
48 var $returnMessages = array();
49 var $returnError = 0;
50
51 /**
52 * Class constructor.
53 *
54 * @param array $params
55 */
56 public function __construct($params) {
57
58 foreach ($params as $name => $value) {
59 $this->$name = $value;
60 }
61
62 // fixme: more params verification
63 }
64
65 /**
66 * Run batch update.
67 *
68 * @return array
69 */
70 public function run() {
71
72 // do check for geocoding.
73 $processGeocode = FALSE;
74 if (!CRM_Utils_GeocodeProvider::getUsableClassName()) {
75 if (CRM_Utils_String::strtobool($this->geocoding) === TRUE) {
76 $this->returnMessages[] = ts('Error: You need to set a mapping provider under Administer > System Settings > Mapping and Geocoding');
77 $this->returnError = 1;
78 $this->returnResult();
79 }
80 }
81 else {
82 $processGeocode = TRUE;
83 // user might want to over-ride.
84 if (CRM_Utils_String::strtobool($this->geocoding) === FALSE) {
85 $processGeocode = FALSE;
86 }
87 }
88
89 // do check for parse street address.
90 $parseAddress = FALSE;
91 $parseAddress = CRM_Utils_Array::value('street_address_parsing',
92 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
93 'address_options'
94 ),
95 FALSE
96 );
97 $parseStreetAddress = FALSE;
98 if (!$parseAddress) {
99 if (CRM_Utils_String::strtobool($this->parse) === TRUE) {
100 $this->returnMessages[] = ts('Error: You need to enable Street Address Parsing under Administer > Localization > Address Settings.');
101 $this->returnError = 1;
102 return $this->returnResult();
103 }
104 }
105 else {
106 $parseStreetAddress = TRUE;
107 // user might want to over-ride.
108 if (CRM_Utils_String::strtobool($this->parse) === FALSE) {
109 $parseStreetAddress = FALSE;
110 }
111 }
112
113 // don't process.
114 if (!$parseStreetAddress && !$processGeocode) {
115 $this->returnMessages[] = ts('Error: Both Geocode mapping as well as Street Address Parsing are disabled. You must configure one or both options to use this script.');
116 $this->returnError = 1;
117 return $this->returnResult();
118 }
119
120 // do check for parse street address.
121 return $this->processContacts($processGeocode, $parseStreetAddress);
122 }
123
124 /**
125 * Process contacts.
126 *
127 * @param bool $processGeocode
128 * @param bool $parseStreetAddress
129 *
130 * @return array
131 * @throws Exception
132 */
133 public function processContacts($processGeocode, $parseStreetAddress) {
134 // build where clause.
135 $clause = array('( c.id = a.contact_id )');
136 $params = array();
137 if ($this->start) {
138 $clause[] = "( c.id >= %1 )";
139 $params[1] = array($this->start, 'Integer');
140 }
141
142 if ($this->end) {
143 $clause[] = "( c.id <= %2 )";
144 $params[2] = array($this->end, 'Integer');
145 }
146
147 if ($processGeocode) {
148 $clause[] = '( a.geo_code_1 is null OR a.geo_code_1 = 0 )';
149 $clause[] = '( a.geo_code_2 is null OR a.geo_code_2 = 0 )';
150 $clause[] = '( a.country_id is not null )';
151 }
152
153 $whereClause = implode(' AND ', $clause);
154
155 $query = "
156 SELECT c.id,
157 a.id as address_id,
158 a.street_address,
159 a.city,
160 a.postal_code,
161 s.name as state,
162 o.name as country
163 FROM civicrm_contact c
164 INNER JOIN civicrm_address a ON a.contact_id = c.id
165 LEFT JOIN civicrm_country o ON a.country_id = o.id
166 LEFT JOIN civicrm_state_province s ON a.state_province_id = s.id
167 WHERE {$whereClause}
168 ORDER BY a.id
169 ";
170
171 $totalGeocoded = $totalAddresses = $totalAddressParsed = 0;
172
173 $dao = CRM_Core_DAO::executeQuery($query, $params);
174
175 $unparseableContactAddress = array();
176 while ($dao->fetch()) {
177 $totalAddresses++;
178 $params = array(
179 'street_address' => $dao->street_address,
180 'postal_code' => $dao->postal_code,
181 'city' => $dao->city,
182 'state_province' => $dao->state,
183 'country' => $dao->country,
184 );
185
186 $addressParams = array();
187
188 // process geocode.
189 if ($processGeocode) {
190 // loop through the address removing more information
191 // so we can get some geocode for a partial address
192 // i.e. city -> state -> country
193
194 $maxTries = 5;
195 do {
196 if ($this->throttle) {
197 usleep(5000000);
198 }
199
200 CRM_Core_BAO_Address::addGeocoderData($params);
201
202 // see if we got a geocode error, in this case we'll trigger a fatal
203 // CRM-13760
204 if (
205 isset($params['geo_code_error']) &&
206 $params['geo_code_error'] == 'OVER_QUERY_LIMIT'
207 ) {
208 throw new CRM_Core_Exception('Aborting batch geocoding. Hit the over query limit on geocoder.');
209 }
210
211 array_shift($params);
212 $maxTries--;
213 } while (
214 (!isset($params['geo_code_1']) || $params['geo_code_1'] == 'null') &&
215 ($maxTries > 1)
216 );
217
218 if (isset($params['geo_code_1']) && $params['geo_code_1'] != 'null') {
219 $totalGeocoded++;
220 $addressParams = $params;
221 }
222 }
223
224 // parse street address
225 if ($parseStreetAddress) {
226 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($dao->street_address);
227 $success = TRUE;
228 // consider address is automatically parseable,
229 // when we should found street_number and street_name
230 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
231 $success = FALSE;
232 }
233
234 // do check for all elements.
235 if ($success) {
236 $totalAddressParsed++;
237 }
238 elseif ($dao->street_address) {
239 //build contact edit url,
240 //so that user can manually fill the street address fields if the street address is not parsed, CRM-5886
241 $url = CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$dao->id}");
242 $unparseableContactAddress[] = " Contact ID: " . $dao->id . " <a href =\"$url\"> " . $dao->street_address . " </a> ";
243 // reset element values.
244 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
245 }
246 $addressParams = array_merge($addressParams, $parsedFields);
247 }
248
249 // finally update address object.
250 if (!empty($addressParams)) {
251 $address = new CRM_Core_DAO_Address();
252 $address->id = $dao->address_id;
253 $address->copyValues($addressParams);
254 $address->save();
255 $address->free();
256 }
257 }
258
259 $this->returnMessages[] = ts("Addresses Evaluated: %1", array(
260 1 => $totalAddresses,
261 )) . "\n";
262 if ($processGeocode) {
263 $this->returnMessages[] = ts("Addresses Geocoded: %1", array(
264 1 => $totalGeocoded,
265 )) . "\n";
266 }
267 if ($parseStreetAddress) {
268 $this->returnMessages[] = ts("Street Addresses Parsed: %1", array(
269 1 => $totalAddressParsed,
270 )) . "\n";
271 if ($unparseableContactAddress) {
272 $this->returnMessages[] = "<br />\n" . ts("Following is the list of contacts whose address is not parsed:") . "<br />\n";
273 foreach ($unparseableContactAddress as $contactLink) {
274 $this->returnMessages[] = $contactLink . "<br />\n";
275 }
276 }
277 }
278
279 return $this->returnResult();
280 }
281
282 /**
283 * Return result.
284 *
285 * @return array
286 */
287 public function returnResult() {
288 $result = array();
289 $result['is_error'] = $this->returnError;
290 $result['messages'] = implode("", $this->returnMessages);
291 return $result;
292 }
293
294 }