Cheetah
ChZIPModule.php
Go to the documentation of this file.
1 <?php
2 
8 ch_import('ChWsbModule');
9 
10 class ChZIPModule extends ChWsbModule
11 {
12  var $_server = 'http://ws.geonames.org'; // geonames server to use for geocoding
13  var $_style = 'SHORT'; // SHORT,MEDIUM,LONG,FULL
14  var $_maxRows = 500; // max number of zip codes to return
15  var $_error = '';
16 
17  function __construct(&$aModule)
18  {
19  parent::__construct($aModule);
20  }
21 
22  function serviceGetSqlParts ($mixedCountry, $sZip, $sMetric, $iDistance, &$sJoin, &$aWhere)
23  {
24  if (!getParam('ch_zip_enabled'))
25  return false;
26 
27  $sWhere = '';
28 
29  // check input fields
30  $sZip = process_db_input( strtoupper( trim($sZip) ), CH_TAGS_STRIP);
31  $sMetric = process_db_input( $sMetric, CH_TAGS_STRIP);
32  $iDistance = (int)$iDistance;
33  if (is_array($mixedCountry)) {
34  $sCountry = process_db_input( $mixedCountry[0], CH_TAGS_STRIP); // no reason to search by zipcode in different countries
35  } else {
36  $sCountry = process_db_input( $mixedCountry, CH_TAGS_STRIP);
37  }
38 
39  // check GB and CA zipcodes
40  if ('CA' == $sCountry) {
41  $sZip = substr($sZip, 0, 3);
42  } elseif ('GB' == $sCountry) {
43  $sZip = strlen($sZip) > 4 ? trim(substr($sZip, 0, -3)) : trim($sZip);
44  }
45 
46  // search using google - Worls Maps module needs to be installed and configured
47  if ('Google' == getParam('ch_zip_mode') && $this->_oDb->isModule('wmap')) {
48  if ($sMetric == 'km')
49  $iDistance *= 0.62;
50 
51  do {
52  $sAddress = "$sZip " . str_replace('_', '', $GLOBALS['aPreValues']['Country'][$sCountry]['LKey']);
53  if (200 != $this->_geocodeGoogle ($sAddress, $fLat, $fLng, $sCountry)) {
54  $this->_setError (_t('_No zip codes found'));
55  break;
56  }
57 
58  if (!class_exists('RadiusAssistant'))
59  require_once( CH_DIRECTORY_PATH_INC . 'RadiusAssistant.inc.php' );
60 
61  $zcdRadius = new RadiusAssistant( $fLat, $fLng, $iDistance );
62  $minLat = $zcdRadius->MinLatitude();
63  $maxLat = $zcdRadius->MaxLatitude();
64  $minLong = $zcdRadius->MinLongitude();
65  $maxLong = $zcdRadius->MaxLongitude();
66 
67  $sWhere = " `Profiles`.`Country` = '$sCountry' AND `ch_wmap_locations`.`country` = '$sCountry' AND `ch_wmap_locations`.`failed` = 0 AND `ch_wmap_locations`.`lat` >= {$minLat} AND `ch_wmap_locations`.`lat` <= {$maxLat} AND `ch_wmap_locations`.`lng` >= {$minLong} AND `ch_wmap_locations`.`lng` <= {$maxLong} ";
68  $sJoin .= " INNER JOIN `ch_wmap_locations` ON (`ch_wmap_locations`.`part` = 'profiles' AND `ch_wmap_locations`.`id` = `Profiles`.`ID`) ";
69 
70  } while (0);
71  }
72  // search using geonames
73  else {
74  if ($sMetric != 'km')
75  $iDistance *= 1.61;
76 
77  if ($iDistance > 30 ) // free service don't allow to search more than 30 km
78  $iDistance = 30;
79 
80  do {
81  $s = $this->_readFromUrl($this->_server . "/findNearbyPostalCodes?postalcode={$sZip}&country={$sCountry}&radius={$iDistance}&style={$this->_style}&maxRows={$this->_maxRows}&username=" . trim(getParam('ch_zip_geonames_username')));
82  if (!$s) {
83  $this->_setError (_t('_Server is too busy'));
84  break;
85  }
86 
87  if (!$this->_getStatusMessage ($s))
88  break;
89 
90  if (false === ($aZips = $this->_getZipCodesArray ($s)))
91  break;
92 
93  foreach ($aZips as $k => $s)
94  $aZips[$k] = strtoupper($s);
95 
96  if ('GB' == $sCountry) {
97  $sWhere = " `Country` = '$sCountry' AND (";
98  foreach ($aZips as $s)
99  $sWhere .= " UPPER(IF(LENGTH(`Profiles`.`zip`) > 4,TRIM(SUBSTRING(`Profiles`.`zip`,1,LENGTH(`Profiles`.`zip`)-3)),`Profiles`.`zip`)) = '$s' OR ";
100  $sWhere = substr($sWhere, 0, -4);
101  $sWhere .= ")";
102  } elseif ('CA' == $sCountry)
103  $sWhere = " `Country` = '$sCountry' AND (UPPER(SUBSTRING(`Profiles`.`zip`,1,3)) = '" . join ("' OR UPPER(SUBSTRING(`Profiles`.`zip`,1,3)) = '", $aZips) . "') ";
104  else
105  $sWhere = " `Country` = '$sCountry' AND (UPPER(`Profiles`.`zip`) = '" . join ("' OR UPPER(`Profiles`.`zip`) = '", $aZips) . "') ";
106  } while (0);
107 
108  }
109 
110  if ($s = $this->getError()) {
111  $aWhere[] = ' 0 ';
112  } else {
113  foreach ($aWhere as $k => $v)
114  if (preg_match('/`zip`/', $v) || preg_match('/`Country`/', $v))
115  unset ($aWhere[$k]);
116  $aWhere[] = $sWhere ? $sWhere : ' 0 ';
117  }
118 
119  return true;
120  }
121 
123  {
124  if (!$this->isAdmin()) {
125  $this->_oTemplate->displayAccessDenied ();
126  return;
127  }
128 
129  $this->_oTemplate->pageStart();
130 
131  $iId = $this->_oDb->getSettingsCategory();
132  if(empty($iId)) {
133  echo MsgBox(_t('_sys_request_page_not_found_cpt'));
134  $this->_oTemplate->pageCodeAdmin (_t('_ch_zip_administration'));
135  return;
136  }
137 
138  ch_import('ChWsbAdminSettings');
139 
140  $mixedResult = '';
141  if(isset($_POST['save']) && isset($_POST['cat'])) {
143  $mixedResult = $oSettings->saveChanges($_POST);
144  }
145 
147  $sResult = $oSettings->getForm();
148 
149  if($mixedResult !== true && !empty($mixedResult))
150  $sResult = $mixedResult . $sResult;
151 
152  $aVars = array (
153  'content' => $sResult,
154  );
155  echo $this->_oTemplate->adminBlock ($this->_oTemplate->parseHtmlByName('default_padding', $aVars), _t('_ch_zip_administration'));
156 
157  $aVars = array (
158  'content' => _t('_ch_zip_help_text'),
159  );
160  echo $this->_oTemplate->adminBlock ($this->_oTemplate->parseHtmlByName('default_padding', $aVars), _t('_ch_zip_help'));
161 
162  $this->_oTemplate->addCssAdmin ('forms_adv.css');
163  $this->_oTemplate->pageCodeAdmin (_t('_ch_zip_administration'));
164  }
165 
166  function isAdmin ()
167  {
168  return $GLOBALS['logged']['admin'] ? true : false;
169  }
170 
171  function _readFromUrl ($sUrl)
172  {
173  if (function_exists('curl_init')) {
174  $curl = curl_init();
175 
176  curl_setopt($curl, CURLOPT_URL, $sUrl);
177  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
178  curl_setopt($curl, CURLOPT_HEADER, false);
179 
180  $s = curl_exec($curl);
181 
182  curl_close($curl);
183 
184  if (true === $s) $s = '';
185  } else {
186  $s = @file_get_contents($sUrl);
187  }
188  return $s;
189  }
190 
192  {
193  if (preg_match('/<totalResultsCount>(\d+)<\/totalResultsCount>/', $s, $m)) {
194  return $m[1];
195  }
196  return 0;
197  }
198 
199  function _getLat (&$s)
200  {
201  if (preg_match('/<lat>([0-9\.-]+)<\/lat>/', $s, $m)) {
202  return $m[1];
203  }
204  return false;
205  }
206 
207  function _getLng (&$s)
208  {
209  if (preg_match('/<lng>([0-9\.-]+)<\/lng>/', $s, $m)) {
210  return $m[1];
211  }
212  return false;
213  }
214 
215  function _getStatusMessage (&$s)
216  {
217  if (preg_match('/<status\s+message="(.*)"\s+value="(\d+)"\s*\/>/', $s, $m)) {
218  $this->_setError ($m[1]);
219  return false;
220  }
221  return true;
222  }
223 
224  function _getZipCodesArray (&$s)
225  {
226  if (!preg_match_all('/<postalcode>(.*)<\/postalcode>/', $s, $m)) {
227  $this->_setError (_t('_No zip codes found'));
228  return false;
229  }
230  return array_unique($m[1]);
231  }
232 
233  function _getCountriesArray (&$s)
234  {
235  if (!preg_match_all('/<countryCode>(.*)<\/countryCode>/', $s, $m)) {
236  return array ();
237  }
238  return array_unique($m[1]);
239  }
240 
241  function _setError ($s)
242  {
243  $this->_error = $s;
244  }
245 
246  function getError ()
247  {
248  return $this->_error;
249  }
250 
251  function _geocodeGoogle ($sAddress, &$fLatitude, &$fLongitude, &$sCountryCode)
252  {
253  $sAddress = rawurlencode($sAddress);
254 
255  $sUrl = "http://maps.googleapis.com/maps/api/geocode/json";
256 
257  $s = ch_file_get_contents($sUrl, array(
258  'address' => $sAddress,
259  'sensor' => 'false'
260  ));
261 
262  $oData = json_decode($s);
263  if (null == $oData)
264  return 404;
265 
266  if ('OK' != $oData->status)
267  return 404;
268 
269  foreach ($oData->results as $oResult) {
270 
271  $sShortNameCountry = '';
272  foreach ($oResult->address_components as $oAddressComponent)
273  if (in_array('country', $oAddressComponent->types))
274  $sShortNameCountry = $oAddressComponent->short_name;
275 
276  if (!$sCountryCode || ($sShortNameCountry && $sCountryCode == $sShortNameCountry)) {
277  $fLatitude = $oResult->geometry->location->lat;
278  $fLongitude = $oResult->geometry->location->lng;
279  $sCountryCode = $sShortNameCountry;
280  return 200;
281  }
282  }
283 
284  return 404;
285  }
286 }
process_db_input
process_db_input($sText, $iStripTags=0)
Definition: utils.inc.php:256
$oSettings
$oSettings
Definition: advanced_settings.php:20
ChZIPModule\_getTotalResultsNum
_getTotalResultsNum(&$s)
Definition: ChZIPModule.php:191
ChZIPModule\getError
getError()
Definition: ChZIPModule.php:246
true
if(!defined("TRUE_VAL")) define("TRUE_VAL" true
Definition: constants.inc.php:8
ChZIPModule\__construct
__construct(&$aModule)
Definition: ChZIPModule.php:17
ChZIPModule\_setError
_setError($s)
Definition: ChZIPModule.php:241
MsgBox
MsgBox($sText, $iTimer=0)
Definition: design.inc.php:175
$sResult
$sResult
Definition: advanced_settings.php:26
$aModule
$aModule
Definition: classifieds.php:21
ChZIPModule\_getZipCodesArray
_getZipCodesArray(&$s)
Definition: ChZIPModule.php:224
ch_import
ch_import($sClassName, $aModule=array())
Definition: utils.inc.php:1218
RadiusAssistant
Definition: RadiusAssistant.inc.php:9
ChZIPModule\serviceGetSqlParts
serviceGetSqlParts($mixedCountry, $sZip, $sMetric, $iDistance, &$sJoin, &$aWhere)
Definition: ChZIPModule.php:22
ChZIPModule\_getStatusMessage
_getStatusMessage(&$s)
Definition: ChZIPModule.php:215
ChZIPModule\isAdmin
isAdmin()
Definition: ChZIPModule.php:166
$sUrl
$sUrl
Definition: cart.php:15
php
$iId
$iId
Definition: license.php:15
ChZIPModule\_getLat
_getLat(&$s)
Definition: ChZIPModule.php:199
getParam
getParam($sParamName, $bUseCache=true)
Definition: db.inc.php:130
ChZIPModule\$_style
$_style
Definition: ChZIPModule.php:13
ch_file_get_contents
ch_file_get_contents($sFileUrl, $aParams=array(), $sMethod='get', $aHeaders=array(), &$sHttpCode=null)
Definition: utils.inc.php:1357
ChZIPModule\_getLng
_getLng(&$s)
Definition: ChZIPModule.php:207
ChZIPModule\actionAdministration
actionAdministration()
Definition: ChZIPModule.php:122
ChWsbModule
Definition: ChWsbModule.php:41
ChZIPModule\_readFromUrl
_readFromUrl($sUrl)
Definition: ChZIPModule.php:171
_t
_t($key, $arg0="", $arg1="", $arg2="")
Definition: languages.inc.php:509
ChZIPModule\$_server
$_server
Definition: ChZIPModule.php:12
ChWsbAdminSettings
Definition: ChWsbAdminSettings.php:35
ChZIPModule
Definition: ChZIPModule.php:11
CH_TAGS_STRIP
const CH_TAGS_STRIP
Definition: utils.inc.php:22
$aVars
$aVars
Definition: license.php:101
$s
$s
Definition: embed.php:13
ChZIPModule\_getCountriesArray
_getCountriesArray(&$s)
Definition: ChZIPModule.php:233
$sCountry
$sCountry
Definition: browse.php:26
empty
Attr AllowedRel this is empty
Definition: Attr.AllowedRel.txt:7
ChZIPModule\_geocodeGoogle
_geocodeGoogle($sAddress, &$fLatitude, &$fLongitude, &$sCountryCode)
Definition: ChZIPModule.php:251
ChZIPModule\$_maxRows
$_maxRows
Definition: ChZIPModule.php:14
ChZIPModule\$_error
$_error
Definition: ChZIPModule.php:15
as
as
Definition: Filter.ExtractStyleBlocks.Escaping.txt:10
$GLOBALS
$GLOBALS['iAdminPage']
Definition: advanced_settings.php:10