'Service currently unavailable.'); // log_cronstatus(); // echo "#successfully completed"; // include("../footer_developer.php"); // exit_wrapper(); // } if($jsonencodedpropertyinput) { $jsonencodedpropertyinput=json_decode($jsonencodedpropertyinput); } $settings=geocode_get_settings($vendor); if(!$address && !$propertyid) developer_error("You must pass an address or propertyid to get the geocoding information"); if(!$address && $propertyid && !$clientcompany) { $address=property_fulladdress($propertyid); } else if(!$address && $propertyid && $clientcompany) { $clicoprop=db_first("select clientcompanypropertyaddress,clientcompanypropertycity,clientcompanypropertystate,clientcompanypropertyzip from tblclientcompanyproperty where clientcompanypropertyid=".db_number($propertyid)); $address=$clicoprop[clientcompanypropertyaddress]." ".$clicoprop[clientcompanypropertycity].", ".$clicoprop[clientcompanypropertystate]." ".$clicoprop[clientcompanypropertyzip]; $msgappend="These results were queried from the address input on this page and not the saved address in the RIO system."; } if($jsonencodedpropertyinput) { $address=$jsonencodedpropertyinput->inputaddress." ".$jsonencodedpropertyinput->input_city.", ".$jsonencodedpropertyinput->input_state." ".$jsonencodedpropertyinput->input_zip; } $geocode_exists=geocode_exists($address,$propertyid); $db[settings]=$settings; $db[geocode_exists]=$geocode_exists; $db[address]=$address; $db[propertyid]=$propertyid; if($geocode_exists) { return array($geocode_exists); } global $runinmode; $url=$settings[apiurl]."address=".str_replace(' ',"+",$address).$settings[apiurlkeyending].$settings[apikey][$runinmode]; $contents=file_get_contents($url); $geoloc=json_decode($contents); // we officially did a request -- add to the counter... geocode_trackusage('api',$propertyid,$address); if($geoloc->status=="ZERO_RESULTS") { return "Zero Results were found for this address. Please check the address and try again."; } $prsedres=geocode_parsed_result($geoloc,$propertyid); geocode_trackcredit($prsedres); set_geocode_cacheand_db($address,$propertyid,$prsedres); $prsedresx=$prsedres; return $prsedres; } function increment_request_no_result() { $q="select geocodedailyapihitsid,geocodedailyapihitsrequested from tblgeocodedailyapihits where geocodedailyapihitsdatetime > TIMESTAMP 'today'"; $r=db_first($q); $incremented=$r[geocodedailyapihitsrequested]+1; if(!$r) { $q2="insert into tblgeocodedailyapihits (geocodedailyapihitsrequested) values (".db_number($incremented).")"; $r2=db_exec($q2); } else{ $q2="update tblgeocodedailyapihits set geocodedailyapihitsrequested=".db_number($incremented)." where geocodedailyapihitsid=$r[geocodedailyapihitsid] "; $r2=db_exec($q2); } } function increment_request_with_result() { $q="select geocodedailyapihitsid,geocodedailyapihitsreceived from tblgeocodedailyapihits where geocodedailyapihitsdatetime > TIMESTAMP 'today'"; $r=db_first($q); $incremented=$r[geocodedailyapihitsreceived]+1; if(!$r) { $q2="insert into tblgeocodedailyapihits (geocodedailyapihitsreceived) values (".db_number($incremented).")"; $r2=db_exec($q2); } else{ $q2="update tblgeocodedailyapihits set geocodedailyapihitsreceived=".db_number($incremented)." where geocodedailyapihitsid=$r[geocodedailyapihitsid] "; $r2=db_exec($q2); } } function geocode_trackcredit($apiresult) { if(!$apiresult[lat]) increment_request_no_result(); else increment_request_with_result(); } function geocode_parsed_result($json,$propertyid) { $results=$json->results; $res=array(); foreach($results as $rk=>$resultobj) { $res[$rk][formatted_address]=$results[$rk]->formatted_address; $frmaddress=$results[$rk]->formatted_address; $addressx=explode(",",$frmaddress); $addrcomp=$resultobj->address_components; foreach($addrcomp as $compk=>$compdata) { $types=$compdata->types; if($types[0]=="route") { $res[$rk][street]=$compdata->long_name; } if($types[0]=="locality") { $res[$rk][city]=$compdata->long_name; } if($types[0]=="administrative_area_level_1") { $res[$rk][state]=$compdata->long_name; } if($types[0]=="postal_code") { $res[$rk][zip]=$compdata->long_name; } if($types[0]=="street_number") { $res[$rk][number]=$compdata->long_name; } } $res[$rk][lat]=$results[$rk]->geometry->location->lat; $res[$rk][lng]=$results[$rk]->geometry->location->lng; $res[$rk][propertyid]=$propertyid; } return $res; } function geocodesaveexists($type,$id) { $sql="select geocodesaveid from tblgeocodesave where geocodesavetype='$type' and geocodesavetypeid=".db_number($id); //d($sql,'$sql'); if(db_query($sql)) return 1; return 0; } function update_staff_in_entity_coords($parentid,$applytoarray,$type) { $sql="select * from tblgeocodesave where geocodesavetype='$type' and geocodesavetypeid =".db_number($parentid); $res=db_first($sql); if(!$res) { d("Did not find the Parent id of $type in the geocodesave table... We dont have the data we need to we are skipping for $type of id: $parentid"); return; } $newdata[geocodesaveaddress]=$res[geocodesaveaddress]; $newdata[geocodesavecity]=$res[geocodesavecity]; $newdata[geocodesavestate]=$res[geocodesavestate]; $newdata[geocodesavezip]=$res[geocodesavezip]; $newdata[geocodesavelatitude]=$res[geocodesavelatitude]; $newdata[geocodesavelongitude]=$res[geocodesavelongitude]; foreach($applytoarray as $appk=>$appvals) { if(geocodesaveexists('staff',$appvals[id])) { $squeel='update tblgeocodesave set '; foreach($newdata as $nk=>$nv) { $squeel.="".$nk." = ".db_tick($nv).","; } $squeel=rtrim($squeel,","); $squeel.=",geocodesaveupdateddate=now() where geocodesavetype='staff' and geocodesavetypeid=".db_number($appvals[id]); }else { $squeel='insert into tblgeocodesave ('; $squeel.=implode(',',array_keys($newdata)); $squeel.=",geocodesavetype,geocodesavetypeid) values ('"; $squeel.=implode("','",array_values($newdata)); $squeel.="','staff','".$appvals[id]."')"; } $cntr++; } db_exec($squeel); } function geocode_getcoordinates($address,$city,$state,$zip,$propertyid=0,$type="",$typeid="") { return gc_getcoords('google',$address." ".$city.", ".$state." ".$zip,$propertyid,$type,$typeid); } function geocodable($address,$city,$state,$zip) { if(!$zip) return false; if(!$address) return false; //if(!$city) // I have found the way to geocode without city or state // return false; //if(!$state) // return false; if(stristr($address,'po box')) return false; if(stristr($address,'p.o.')) return false; return true; } function geocoded_setcache($geocodedarray) { $_SESSION['geocodedcache'][data]=$geocodedarray; $_SESSION['geocodedcache'][time]=time(); } function geocoded_cached() { if(isset($_SESSION['geocodedcache'][data])) { $cachetime=$_SESSION['geocodedcache'][time]; $nowtime=time(); $agelimit=60*60*24; //(1 day) if($cachetime>($nowtime-$agelimit)) return $_SESSION['geocodedcache'][data]; else { unset($_SESSION['geocodedcache']); return 0; } } else return 0; } function save_geocode_query($type,$qry,$skipquery=0) { global $geocode_count; global $runsql; d($qry,'$qry'); //d($_SESSION['geocodedcache'],'browser cache'); //d($runsql,'$runsql'); // //if(!$runsql) // return; // if(geo_creditsremaining()<(.20*2500)) // { // developer_error("You have less than 20 percent (".geo_creditsremaining().") of your geocode credits remaining."); // } // if(geo_creditsremaining()<(.10*2500)) // { // developer_error("You have less than 10 percent (".geo_creditsremaining().") of your geocode credits remaining."); // } // if(!geo_creditsremaining()) // { // developer_error('Geocode is reporting 0 credits available.'); // return array('system_error' => 'Service currently unavailable.'); // log_cronstatus(); // echo "#successfully completed"; // include("../footer_developer.php"); // exit_wrapper(); // } $expiryinterval= "1 day"; if($type=='staff' || $type=='officelocation' || $type=='company' || $type=='accountstaff') { //return; $expiryinterval= "30 days "; } if($typeforquery) $qrytype=$typeforquery; else $qrytype=$type; //if(geocoded_cached()) // $geocoded=geocoded_cached(); //else //{ $geoquery="select * , case when geocodesaveupdateddate < now() - interval '".$expiryinterval."' then 1 else 0 end as old from tblgeocodesave where geocodesavetype='$qrytype' "; $geoquery.=" order by geocodesavetypeid "; $geocoded=db_query($geoquery,0,1,geocodesavetypeid); d($geoquery,'$geoquery'); d($geocoded,'$geocoded'); // geocoded_setcache($geocoded); //} $cnt=0; //d(__line__.geocoded,$geocoded); //d($geoquery,'$geoquery'); foreach($qry as $row) { //d($row,'$row'); //if($cnt>1) // die(); if($type=='clientcompanyproperty') $propertyid=$row[id]; //d($row,'$row'); //d($propertyid,'$propertyid'); if($row[accountinactive]) unset($row[accountinactive]); if($row[companyinactive]) unset($row[companyinactive]); if($row[clientcompanydev]) unset($row[clientcompanydev]); if($row[clientcompanycloaked]) unset($row[clientcompanycloaked]); if($row[clientcompanyinactivedate]) unset($row[clientcompanyinactivedate]); if($row[companycloaked]) unset($row[companycloaked]); //if($row[companyinactive]) // unset($row[companyinactive]); $cnt++; //continue; $typeid = $row[id]; //d($typeid,'$typeid'); $row[zip] = str_pad($row[zip],5,"0",STR_PAD_LEFT ); unset($row[id]); $cache = $geocoded[$typeid]; $geocodesaveid = $cache[geocodesaveid]; if(!$row[address]&&!$row[city]&&!$row[state]&&!$row[zip]) { d("ungeocodable address: skipping $row[address],$row[city],$row[state],$row[zip]",$row); continue; } $address = $row[address]; $city = $row[city]; $state = $row[state]; $zip = $row[zip]; geocode_addresscheck($address,$city,$state,$zip); // Check address //d("Would run geocode address check"); $row[address] = $address; $row[city] = $city; $row[state] = $state; $row[zip] = $zip; if(!geocodable($row[address],$row[city],$row[state],$row[zip]) && !is_numeric($row[zip])) { d("ungeocodable address: skipping $row[address],$row[city],$row[state],$row[zip]",$row); continue; } elseif(is_numeric($row[zip])) ; else ; $update=1;//update by default $updateablecolumnsarray=array("address","city","state","zip","latitude","longitude"); if($cache) //if there is a cache saved already , then do a compare and update if the values in the cache have changed. { //d(__line__.": ".$cache[geocodesaveaddress],$cache); $update=0; if($cache[old] || ( $cache[geocodesavelatitude]==-1 && $cache[geocodesavelongitude]==-1 )) { //d("Old Cache, update",$cache); $update=1; } if(!$update) { foreach($row as $fld=>$value) { $value=str_replace('\\','',$value); if(db_col(trim(strtolower($cache["geocodesave$fld"])))!==db_col(trim(strtolower($value))) && in_array($fld,$updateablecolumnsarray)) { d("$fld differ, update '".$cache["geocodesave$fld"]."' != '".$value."'"); $update=1; } } } } //exit; if($update) { $geocode_count++; //if($geocode_count>200) //{ // d("killing out after running 200"); // d(type,$type); // d(geocoderun,$geocoderun); // d(geocoderuncnt,$geocoderuncnt); // d("ran $updatesrun updates of we are at $cnt of ".count($qry)); // log_cronstatus(); // echo "#successfully completed"; // include("../footer_developer.php"); // exit_wrapper(); //} //continue; d($row,"row"); $coor = geocode_getcoordinates($row[address],$row[city],$row[state],$row[zip],$propertyid,$type,$typeid); d($coor,'$coor'); if(!$coor) { $geocode_count--; //d("Invalid return, skipping $row[address],$row[city],$row[state],$row[zip]",$coor); continue; } if(!$coor[lat]||!$coor[lng]) { d("Invalid return latitude: $coor[latitude], longitude: $coor[longitude], skipping $row[address],$row[city],$row[state],$row[zip]",$coor); continue; } if(strlen($coor[lat])>15||strlen($coor[lng])>15) { developer_error("Invalid return latitude: $coor[lat], longitude: $coor[lng], skipping $row[address],$row[city],$row[state],$row[zip]",$coor); //developer_message("Invalid return ; } if(!$geocodesaveid) { if($type=='clientcompanyproperty') { $sqlvaladd=",$propertyid"; $sqladdcol=", geocodesavepropertyid"; } $geocodesaveid = db_nextid('geocodesave'); $sql = "insert into tblgeocodesave (geocodesaveid, geocodesavetype, geocodesavetypeid $sqladdcol) values ($geocodesaveid, '$type', $typeid $sqlvaladd)"; //d($sql); $insertstorun[$geocodesaveid]=$sql; //db_exec($sql,1); } $byziponly=0; $row[latitude]=$coor[lat]; $row[longitude]=$coor[lng]; geocode_trackcredit($coor); $coorsreceieved[]=$coor; /* if($row[latitude]==-1 && $row[longitude]==-1) { //look up the address again using just the zipcode d("Running geocode by zipcode"); $coor = geocode_getcoordinatesfromzip($row[zip]); // if we can not get the coordinates from the address, try for the zip d("returned by zipcode",$coor); $byziponly=1; $row[latitude]=$coor[latitude]; $row[longitude]=$coor[longitude]; } */ $geocoderun["$address $city $state $zip"]="lat:$coor[lat], long: $coor[lng]"; $geocoderuncnt["$address $city $state $zip"].="$type $typeid"; $sql = "update tblgeocodesave set geocodesaveupdateddate=now() ,geocodesavebyzipcodeonly=$byziponly "; foreach($updateablecolumnsarray as $upk) { if($upk=='clientcompanydev' ||$upk=='clientcompanycloaked' ||$upk=='clientcompanyinactivedate'|| $upk=='companyinactive' ||$upk=='accountinactive') continue; $sql.=", geocodesave$upk = '".db_col(trim($row[$upk]))."'"; } $sql .=" where geocodesaveid = $geocodesaveid "; $updatesrun++; $updatestorun[$geocodesaveid]=$sql; $gc[add]=$row[address]; $gc[city]=$row[city]; $gc[state]=$row[state]; $gc[zip]=$row[zip]; $gc[pid]=$propertyid; $gc[type]=$type; $gc[typeid]=$typeid; $gc[coors]=$coor; $updatedproperties[]=$gc; //d($sql,$row); //d(cache,$cache); //db_exec($sql,1); //return; } } d($coorsreceieved,'all recieved coordinates'); d($insertstorun,'$insertstorun'); d($updatestorun,'$updatestorun'); if(count($insertstorun)) foreach($insertstorun as $sql) db_exec($sql,1); if(count($updatestorun)) foreach($updatestorun as $sql) db_exec($sql,1); d("we have sent an api request and received a valid response ".$geocode_count." times for this run"); d("Array of properties updated",$updatedproperties); d("Ran ".count($insertstorun)." Inserts to tblgeocodesave "); d("Ran ".count($updatestorun)." Updates to tblgeocodesave "); } function gc_getcoords($vendor,$address="",$propertyid=0,$typeof,$typeid) { //d($address,'$address in getcoords'); $settings=geocode_get_settings($vendor); if(!$address && !$propertyid) developer_error("You must pass an address or propertyid to get the geocoding information"); if(!$address && $propertyid && !$clientcompany) { $address=property_fulladdress($propertyid); } else if(!$address && $propertyid && $clientcompany) { $clicoprop=db_first("select clientcompanypropertyaddress,clientcompanypropertycity,clientcompanypropertystate,clientcompanypropertyzip from tblclientcompanyproperty where clientcompanypropertyid=".db_number($propertyid)); $address=$clicoprop[clientcompanypropertyaddress]." ".$clicoprop[clientcompanypropertycity].", ".$clicoprop[clientcompanypropertystate]." ".$clicoprop[clientcompanypropertyzip]; $msgappend="These results were queried from the address input on this page and not the saved address in the RIO system."; } global $runinmode; $url=$settings[apiurl]."address=".str_replace(' ',"+",$address).$settings[apiurlkeyending].$settings[apikey][$runinmode]; $contents=file_get_contents($url); $geoloc=json_decode($contents); d($geoloc,'$geoloc in get coords'); $geores=$geoloc->results[0]; //d($geores,'$geores'); $goe=$geores->geometry->location; //d($goe,'$goe'); $res[lat]=$goe->lat; $res[lng]=$goe->lng; // we officially did a request -- add to the counter... //geocode_trackusage('api',$propertyid,$address); if($geoloc->status=="ZERO_RESULTS" ) { return 0; } if(db_number($res[lat]) && db_number($res[lng])) geocode_trackusage('api',$propertyid,$address,$typeof,$typeid); return $res; } function get_geocode_query($type,$id=0) { if(is_array($id)) $id=$id[0]; if($type=="clientcompanyproperty") { return "select distinct clientcompanypropertyid as id , clientcompanypropertyaddress as address ,clientcompanypropertycity as city ,clientcompanypropertystate as state ,clientcompanypropertyzip as zip ,clientcompanydev ,clientcompanycloaked ,clientcompanyinactivedate from tblclientcompanyproperty join tblclientcompany using(clientcompanyid) where 0=0 and clientcompanypropertyid=".db_number($id)." "; } else if($type=="property") { return "select distinct propertyid as id , propertyaddress as address ,propertycity as city ,propertystate as state ,propertyzip as zip from tblproperty join tblcompany using(companyid) where 0=0 and propertyid=".db_number($id)." "; } else if($type=="officelocation") { return "select distinct officelocationid as id ,officelocationaddress as address ,officelocationcity as city , officelocationstate as state , officelocationzip as zip ,accountinactive ,companyinactive from tblofficelocation left join tblaccount using (accountid) left join tblcompany using (companyid) where 0 = 0 and officelocationid=".db_number($id)." "; } else if($type=="company") { return "select distinct companyid as id , companyaddress as address ,companycity as city ,companystate as state ,companyzip as zip from tblcompany join tbllogin using(companyid) join tblstaff using(staffid) where 0=0 and companyid=".db_number($id)." "; } else if($type=="staff") { return "select distinct staffid as id , case when tblofficelocation.officelocationid is not null then officelocationaddress else companyaddress end as address , case when tblofficelocation.officelocationid is not null then officelocationcity else companycity end as city , case when tblofficelocation.officelocationid is not null then officelocationstate else companystate end as state , case when tblofficelocation.officelocationid is not null then officelocationzip else companyzip end as zip , tblcompany.companyid as companyid , tblofficelocation.officelocationid as officeid , tblcompany.companydeveloper as companydev , tblcompany.companycloaked as companycloaked from tblstaff join tbllogin using(staffid) join tblcompany using(companyid) join tblstaffgroup using(staffid) join tblgroup using(groupid) left join tblofficelocation using(officelocationid) where 0=0 and staffid=".db_number($id)." "; } else if($type=="accountstaff") { return "select accountstaffid as id , officelocationaddress as address , officelocationcity as city , officelocationstate as state , officelocationzip as zip , * from tbllogin join tblaccountstaff using (accountstaffid) join tblofficelocation using (officelocationid) where 0=0 and accountstaffid=".db_number($id)." "; } } // below is legacy geocodeer functionality function gc_mapquest_build_array($temparray) { foreach($temparray[results] as $key=>$val) { if($val[locations]) { $thisloc=$val[locations][0]; $outarr[$key][lat]=$thisloc[latLng][lat]; $outarr[$key][long]=$thisloc[latLng][lng]; $outarr[$key][number]=db_number($thisloc[street]); //$outarr[$key][prefix]=$val[]; $outarr[$key][street]=str_replace(db_number($thisloc[street]),"",$thisloc[street]); $outarr[$key][type]=$thisloc[adminArea6Type]; //$outarr[$key][suffix]=$val[]; $outarr[$key][city]=$thisloc[adminArea5]; $outarr[$key][state]=$thisloc[adminArea3]; $outarr[$key][zip]=$thisloc[postalCode]; } //$outarr[$key][gc]=$val[]; } return $outarr; } function geocode_mapquestparseaddress($address,$city,$state,$zip,$skipordinal=0) { /* Result will be array of elements first member is always original data Array ( [0] => Array ( [number] => 3502 [prefix] => [street] => Bannock [type] => [suffix] => [city] => Boise [state] => ID [zip] => 83702 [gc] => original address ) [1] => Array ( [lat] => 43.623489 [long] => -116.225152 [number] => 2801 [prefix] => [street] => Bannock [type] => St [suffix] => [city] => Boise City [state] => ID [zip] => 83702 [gc] => geocoder modified ) [2] => Array ( [lat] => 43.623489 [long] => -116.223852 [number] => 2701 [prefix] => W [street] => Bannock [type] => St [suffix] => [city] => Boise City [state] => ID [zip] => 83702 [gc] => geocoder modified ) ) */ $apikey="YG57j8HjeeMA9MwWoGDOMrwkwXvibFZ6"; $apisecret="UHCEGtgNfGojiUSi"; timetrack(geocode_getcoordinates); if (strlen($zip)<5) // this is a fix for empty return, now we will get an error=2: couldn't find this address! sorry as response for invalid data. $zip=" "; //geocode_addresscheck($address,$city,$state,$zip,($skipordinal ? 1:0)); $straddress = "$address,$city,$state,$zip"; //$url = "http://geocoder.us/member/service/namedcsv?address=" . (urlencode($straddress))."&parse_address=1"; $url="http://www.mapquestapi.com/geocoding/v1/address?key=".$apikey."&location=". (urlencode($straddress)).""; //d($url,'$url'); //$uname="" $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmp = curl_exec($ch); //d($tmp,'$tmp'); $ret =json_decode($tmp, true); //d($ret); $validationarray=gc_mapquest_build_array($ret); //d($validationarray); //exit; return $validationarray; } function monitor_creditspent($zip,$dataarray=array()) { $savearray=array( "action"=>"validateaddressgeocode - cronjob" , "description"=>"Validation run in cron job" , "actionvalue"=>1 , "trackidtype"=>"zip" , "trackidnumber"=>db_col($zip) , "monitorextraserialized"=>serialize($dataarray) ); save_action_monitor($savearray); } function parse_geocoder_scrapedhtml_forcreditsavailable($lookfor,$html) { // at the time this function was written, the location of the credits available is in the Look Up Credits.div.b element // if the html changes on the scraped page, the parserr will need to be updated to find the data in a different location on the page $lookx=explode(".",$lookfor); $xhtml=explode($lookx[0],$html); //d($html,'$html'); if($lookx[1]) { $xhtml=explode($lookx[1],$xhtml[1]); } if($lookx[2]) { $xhtml=explode($lookx[2],$xhtml[1]); } //d($xhtml,'$xhtml'); $creditsavailable=db_number($xhtml[1]); return $creditsavailable; } function check_geocoder_credits() { $url="http://geocoder.us/member/account"; // HTTP authentication $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $cookie = 'cookies.txt'; $timeout = 30; curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt($ch, CURLOPT_USERPWD, "matraex:zipdisk"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec($ch); curl_close($ch); //echo $result; ob_start(); $out=ob_get_clean(); $credits= parse_geocoder_scrapedhtml_forcreditsavailable("Lookup Credits.div.b",$result); return $credits; } /** * geocode_parseaddress($address,$city,$state,$zip) * @name geocode_parseaddress * @return array result */ function geocode_parseaddress($address,$city,$state,$zip,$skipordinal=0) { /* Result will be array of elements first member is always original data Array ( [0] => Array ( [number] => 3502 [prefix] => [street] => Bannock [type] => [suffix] => [city] => Boise [state] => ID [zip] => 83702 [gc] => original address ) [1] => Array ( [lat] => 43.623489 [long] => -116.225152 [number] => 2801 [prefix] => [street] => Bannock [type] => St [suffix] => [city] => Boise City [state] => ID [zip] => 83702 [gc] => geocoder modified ) [2] => Array ( [lat] => 43.623489 [long] => -116.223852 [number] => 2701 [prefix] => W [street] => Bannock [type] => St [suffix] => [city] => Boise City [state] => ID [zip] => 83702 [gc] => geocoder modified ) ) */ timetrack(geocode_getcoordinates); if (strlen($zip)<5) // this is a fix for empty return, now we will get an error=2: couldn't find this address! sorry as response for invalid data. $zip=" "; // lets see if we have any credits before actually sending the request if(!check_geocoder_credits()) { //developer_error('Geocode is reporting 0 credits available.'); //$address_return[1]=geocode_mapquestparseaddress($address,$city,$state,$zip,$skipordinal=0); //d($address_return,'$address_returned'); //if(!$address_return) return array('system_error' => 'Service currently unavailable.'); //return $address_return; // we need a backup service here so that if the geocode site is down, we have a fallback } geocode_addresscheck($address,$city,$state,$zip,($skipordinal ? 1:0)); $straddress = "$address,$city,$state,$zip"; $url = "http://geocoder.us/member/service/namedcsv?address=" . (urlencode($straddress))."&parse_address=1"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "matraex:zipdisk"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $tmp = curl_exec($ch); dlog_geocodecredits('Function:geocode_parseaddress'); $ret = $tmp; if (strpos($ret, 'Your account does not have sufficient credits to use this feature')) { developer_error('A call to Geocode has been made, but Geocode is reporting insufficient credits.'); return array('system_error' => 'Address validation is not available at this time, please notify your System Administrator.'); } $find = "lat="; $address_return[0] = ""; $not_done = true; while ($not_done) { $br = false; if(strlen($ret)) $br = strpos($ret,$find,1); //have to look for false from strpos //because 0 is the begining of the string, aka valid. if ($br === false) $not_done = false; $address_return[$i] = gc_build_array(explode(",",substr($ret,0,$br))); $tmp = substr($ret,$br); if ($br === false) $address_return[$i]=gc_build_array(explode(",",$ret)); else $ret = $tmp; } dlog("geocode_addressparsed"," Address Parsed for Geocode | URL: ".$url." | Property Address: ".$straddress." Time: ".time().""); timetrack_stop(geocode_getcoordinates); return $address_return; } /** * geocode_alias ($name) * * This function is made to modify results from Geocode for example Boise City becomes Boise. * @param string $name * @return string $alias */ function geocode_alias($name){ $alias = array ("Boise City"=>"Boise"); if ($alias[$name]) return $alias[$name]; else return $name; } /** * gc_build_array($temparr) * * This function formats geocoder output into array * @param [array] $temparr * @return [array] $rebuild */ function gc_build_array($temparr) { foreach ($temparr as $result => $val) { if (strpos($val,"=",0)) $rebuild[substr($val,0,strpos($val,"=",0))] = substr($val,strpos($val,"=",0)+1); else $rebuild["gc"] = $val; } return $rebuild; } /** * geocode_addresscheck(&$address,&city,&$state,&$zip) * * @comment This function does address check and correction. * @commnet IMPORTANT it uses arguments by reference * @depend functions_general.php:addOrdinalNumberSuffix($number) * @param [string] $address * @param [string] $city * @param [string] $state * @param [integer] $zip * @name geocode_addresscheck */ function geocode_addresscheck(&$address,&$city,&$state,&$zip,$skipordinal=0){ if (!$zip) return false; if (strlen(trim($state))>2) { $state_code = db_first("select code from tblstate where name='".db_col(ucwords($state))."'"); $state = $state_code[code]; } $city = ucwords(trim($city)); $tmp_address = explode(" ",trim($address)); unset($found); foreach ($tmp_address as $k=>$element){ if ($k>0 && $k<3 && is_numeric($element) && !$found){ if (!$skipordinal) $tmp_address[$k] = addOrdinalNumberSuffix($element); else $tmp_address[$k] = $element; $found=1; } if (strtolower($element) == "p.o." || strtolower($element) =="po" || strtolower($element) =="p.o. box" || strtolower($element) =="po box"){ $tmp_address[$k] = ""; $tmp_address[$k+1] = ""; } } $address = implode(" ",$tmp_address); //dlog_geocodecredits('Function:geocode_addresscheck'); return; } function get_keywordlabel($key) { $keys[portfolioid]=PORTFOLIOLABEL; $keys[clientcompanyclientid]="Client"; $keys[clientcompanypropertyassignmenttype]="Assignment Type"; if($keys[$key]) $key = $keys[$key]; return $key; } ?>