commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / bin / deprecated / UpdateAddress.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 * A PHP cron script to format all the addresses in the database. Currently
30 * it only does geocoding if the geocode values are not set. At a later
31 * stage we will also handle USPS address cleanup and other formatting
32 * issues
33 *
34 */
35
36 define('THROTTLE_REQUESTS', 0);
37 function run() {
38 session_start();
39
40 require_once '../civicrm.config.php';
41 require_once 'CRM/Core/Config.php';
42
43 $config = CRM_Core_Config::singleton();
44
45 require_once 'Console/Getopt.php';
46 $shortOptions = "n:p:s:e:k:g:parse";
47 $longOptions = array('name=', 'pass=', 'key=', 'start=', 'end=', 'geocoding=', 'parse=');
48
49 $getopt = new Console_Getopt();
50 $args = $getopt->readPHPArgv();
51
52 array_shift($args);
53 list($valid, $dontCare) = $getopt->getopt2($args, $shortOptions, $longOptions);
54
55 $vars = array(
56 'start' => 's',
57 'end' => 'e',
58 'name' => 'n',
59 'pass' => 'p',
60 'key' => 'k',
61 'geocoding' => 'g',
62 'parse' => 'ap',
63 );
64
65 foreach ($vars as $var => $short) {
66 $$var = NULL;
67 foreach ($valid as $v) {
68 if ($v[0] == $short || $v[0] == "--$var") {
69 $$var = $v[1];
70 break;
71 }
72 }
73 if (!$$var) {
74 $$var = CRM_Utils_Array::value($var, $_REQUEST);
75 }
76 $_REQUEST[$var] = $$var;
77 }
78
79 // this does not return on failure
80 // require_once 'CRM/Utils/System.php';
81 CRM_Utils_System::authenticateScript(TRUE, $name, $pass);
82
83 //log the execution of script
84 CRM_Core_Error::debug_log_message('UpdateAddress.php');
85
86 // do check for geocoding.
87 $processGeocode = FALSE;
88 if (empty($config->geocodeMethod)) {
89 if ($geocoding == 'true') {
90 echo ts('Error: You need to set a mapping provider under Global Settings');
91 exit();
92 }
93 }
94 else {
95 $processGeocode = TRUE;
96 // user might want to over-ride.
97 if ($geocoding == 'false') {
98 $processGeocode = FALSE;
99 }
100 }
101
102 // do check for parse street address.
103 require_once 'CRM/Core/BAO/Setting.php';
104 $parseAddress = CRM_Utils_Array::value('street_address_parsing',
105 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
106 'address_options'
107 ),
108 FALSE
109 );
110 $parseStreetAddress = FALSE;
111 if (!$parseAddress) {
112 if ($parse == 'true') {
113 echo ts('Error: You need to enable Street Address Parsing under Global Settings >> Address Settings.');
114 exit();
115 }
116 }
117 else {
118 $parseStreetAddress = TRUE;
119 // user might want to over-ride.
120 if ($parse == 'false') {
121 $parseStreetAddress = FALSE;
122 }
123 }
124
125 // don't process.
126 if (!$parseStreetAddress && !$processGeocode) {
127 echo ts('Error: Both Geocode mapping as well as Street Address Parsing are disabled. You must configure one or both options to use this script.');
128 exit();
129 }
130
131 // we have an exclusive lock - run the mail queue
132 processContacts($config, $processGeocode, $parseStreetAddress, $start, $end);
133 }
134
135 /**
136 * @param $config
137 * @param $processGeocode
138 * @param $parseStreetAddress
139 * @param null $start
140 * @param null $end
141 */
142 function processContacts(&$config, $processGeocode, $parseStreetAddress, $start = NULL, $end = NULL) {
143 // build where clause.
144 $clause = array('( c.id = a.contact_id )');
145 if ($start) {
146 $clause[] = "( c.id >= $start )";
147 }
148 if ($end) {
149 $clause[] = "( c.id <= $end )";
150 }
151 if ($processGeocode) {
152 $clause[] = '( a.geo_code_1 is null OR a.geo_code_1 = 0 )';
153 $clause[] = '( a.geo_code_2 is null OR a.geo_code_2 = 0 )';
154 $clause[] = '( a.country_id is not null )';
155 }
156 $whereClause = implode(' AND ', $clause);
157
158 $query = "
159 SELECT c.id,
160 a.id as address_id,
161 a.street_address,
162 a.city,
163 a.postal_code,
164 s.name as state,
165 o.name as country
166 FROM civicrm_contact c
167 INNER JOIN civicrm_address a ON a.contact_id = c.id
168 LEFT JOIN civicrm_country o ON a.country_id = o.id
169 LEFT JOIN civicrm_state_province s ON a.state_province_id = s.id
170 WHERE {$whereClause}
171 ORDER BY a.id
172 ";
173
174 $totalGeocoded = $totalAddresses = $totalAddressParsed = 0;
175
176 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
177
178 if ($processGeocode) {
179 require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
180 }
181
182 require_once 'CRM/Core/DAO/Address.php';
183 require_once 'CRM/Core/BAO/Address.php';
184
185 $unparseableContactAddress = array();
186 while ($dao->fetch()) {
187 $totalAddresses++;
188 $params = array(
189 'street_address' => $dao->street_address,
190 'postal_code' => $dao->postal_code,
191 'city' => $dao->city,
192 'state_province' => $dao->state,
193 'country' => $dao->country,
194 );
195
196 $addressParams = array();
197
198 // process geocode.
199 if ($processGeocode) {
200 // loop through the address removing more information
201 // so we can get some geocode for a partial address
202 // i.e. city -> state -> country
203
204 $maxTries = 5;
205 do {
206 if (defined('THROTTLE_REQUESTS') &&
207 THROTTLE_REQUESTS
208 ) {
209 usleep(50000);
210 }
211
212 eval($config->geocodeMethod . '::format( $params, true );');
213 array_shift($params);
214 $maxTries--;
215 } while ((!isset($params['geo_code_1'])) &&
216 ($maxTries > 1)
217 );
218
219 if (isset($params['geo_code_1']) &&
220 $params['geo_code_1'] != 'null'
221 ) {
222 $totalGeocoded++;
223 $addressParams['geo_code_1'] = $params['geo_code_1'];
224 $addressParams['geo_code_2'] = $params['geo_code_2'];
225 }
226 }
227
228 // parse street address
229 if ($parseStreetAddress) {
230 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($dao->street_address);
231 $success = TRUE;
232 // consider address is automatically parseable,
233 // when we should found street_number and street_name
234 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
235 $success = FALSE;
236 }
237
238 // do check for all elements.
239 if ($success) {
240 $totalAddressParsed++;
241 }
242 elseif ($dao->street_address) {
243 //build contact edit url,
244 //so that user can manually fill the street address fields if the street address is not parsed, CRM-5886
245 $url = CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$dao->id}");
246 $unparseableContactAddress[] = " Contact ID: " . $dao->id . " <a href =\"$url\"> " . $dao->street_address . " </a> ";
247 // reset element values.
248 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
249 }
250 $addressParams = array_merge($addressParams, $parsedFields);
251 }
252
253 // finally update address object.
254 if (!empty($addressParams)) {
255 $address = new CRM_Core_DAO_Address();
256 $address->id = $dao->address_id;
257 $address->copyValues($addressParams);
258 $address->save();
259 $address->free();
260 }
261 }
262
263 echo ts("Addresses Evaluated: $totalAddresses\n");
264 if ($processGeocode) {
265 echo ts("Addresses Geocoded : $totalGeocoded\n");
266 }
267 if ($parseStreetAddress) {
268 echo ts("Street Address Parsed : $totalAddressParsed\n");
269 if ($unparseableContactAddress) {
270 echo ts("<br />\nFollowing is the list of contacts whose address is not parsed :<br />\n");
271 foreach ($unparseableContactAddress as $contactLink) {
272 echo ts("%1<br />\n", array(1 => $contactLink));
273 }
274 }
275 }
276 }
277
278 run();