function yahoo_geo($location) { // setup your own yahoo application ID here $yahoo_appid = "dMlbxCLV34HsZfAP6i5HRYEqr8qHW2Navz_lrTvag2tN8dZJ9L4vA_uLGLEni65X"; $q = 'http://local.yahooapis.com/MapsService/V1/geocode'; $q .= '?appid=' . $yahoo_appid . '&location=' . rawurlencode($location); $tmp = '/tmp/yws_geo_' . md5($q); request_cache($q, $tmp, 43200); libxml_use_internal_errors(true); $xml = simplexml_load_file($tmp); $ret['precision'] = (string) $xml->Result['precision']; foreach ($xml->Result->children() as $key => $val) { if (strlen($val)) { $ret[(string) $key] = (string) $val; } } return $ret; }
function request_cache($request, $force_fetch = false) { $max_cache_lifetime = 7 * 86400; /* max cache lifetime in seconds before refreshing from source */ /* membership_cache table exists? if not, create it */ static $cache_table_exists = false; if (!$cache_table_exists && !$force_fetch) { $te = sqlValue("show tables like 'membership_cache'"); if (!$te) { if (!sql("CREATE TABLE `membership_cache` (`request` VARCHAR(100) NOT NULL, `request_ts` INT, `response` TEXT NOT NULL, PRIMARY KEY (`request`))", $eo)) { /* table can't be created, so force fetching request */ return request_cache($request, true); } } $cache_table_exists = true; } /* retrieve response from cache if exists */ if (!$force_fetch) { $res = sql("select response, request_ts from membership_cache where request='" . md5($request) . "'", $eo); if (!($row = db_fetch_array($res))) { return request_cache($request, true); } $response = $row[0]; $response_ts = $row[1]; if ($response_ts < time() - $max_cache_lifetime) { return request_cache($request, true); } } /* if no response in cache, issue a request */ if (!$response || $force_fetch) { $response = @file_get_contents($request); if ($response === false) { $error = error_get_last(); $error_message = preg_replace('/.*: (.*)/', '$1', $error['message']); return $error_message; } elseif ($cache_table_exists) { /* store response in cache */ $ts = time(); sql("replace into membership_cache set request='" . md5($request) . "', request_ts='{$ts}', response='" . makeSafe($response, false) . "'", $eo); } } return $response; }