function get_geolocation($address, $geo_db = array())
{
    global $config;
    $location = array('location' => $address);
    // Init location array
    switch (strtolower($config['geocoding']['api'])) {
        case 'osm':
        case 'openstreetmap':
            $location['location_geoapi'] = 'openstreetmap';
            // Openstreetmap. The usage limits are stricter here. (http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy)
            $url = "http://nominatim.openstreetmap.org/search?format=json&accept-language=en&addressdetails=1&limit=1&q=";
            $reverse_url = "http://nominatim.openstreetmap.org/reverse?format=json&accept-language=en&";
            break;
        case 'google':
            $location['location_geoapi'] = 'google';
            // See documentation here: https:// developers.google.com/maps/documentation/geocoding/
            // Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day.
            $url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=en&address=";
            $reverse_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=en&";
            break;
        case 'yandex':
            $location['location_geoapi'] = 'yandex';
            $url = "http://geocode-maps.yandex.ru/1.x/?format=json&lang=en_US&results=1&geocode=";
            $reverse_url = "http://geocode-maps.yandex.ru/1.x/?format=json&lang=en_US&results=1&sco=latlong&";
            break;
        case 'mapquest':
        default:
            $location['location_geoapi'] = 'mapquest';
            // Mapquest open data. There are no usage limits.
            $url = "http://open.mapquestapi.com/nominatim/v1/search.php?format=json&accept-language=en&addressdetails=1&limit=1&q=";
            $reverse_url = "http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=en&";
    }
    if (isset($config['geocoding']['enable']) && $config['geocoding']['enable']) {
        $reverse = FALSE;
        // by default forward geocoding
        $debug_msg = "Geocoding启用, 尝试定位设备坐标." . PHP_EOL;
        // If device coordinates set manually, use Reverse Geocoding.
        if ($geo_db['location_manual']) {
            $location['location_lat'] = $geo_db['location_lat'];
            $location['location_lon'] = $geo_db['location_lon'];
            $reverse = TRUE;
            $debug_msg .= '  MANUAL coordinates - SET' . PHP_EOL;
        } else {
            if ($config['geocoding']['dns']) {
                /**
                 * Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using
                 * DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual).
                 *
                 * Example LOC:
                 *   "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m"
                 *
                 * From Wikipedia: d1 [m1 [s1]] {"N"|"S"}  d2 [m2 [s2]] {"E"|"W"}
                 *
                 * Parsing this is something for Net_DNS2 as it has the code for it.
                 */
                if ($geo_db['hostname']) {
                    include_once 'Net/DNS2.php';
                    include_once 'Net/DNS2/RR/LOC.php';
                    $resolver = new Net_DNS2_Resolver();
                    try {
                        $response = $resolver->query($geo_db['hostname'], 'LOC', 'IN');
                    } catch (Net_DNS2_Exception $e) {
                        print_debug('  ' . $e->getMessage() . ' (' . $geo_db['hostname'] . ')');
                    }
                } else {
                    $response = FALSE;
                    print_debug("  DNS 位置已激活, 不过设备主机名为空.");
                }
                if ($response) {
                    if (OBS_DEBUG > 1) {
                        var_dump($response->answer);
                    }
                    foreach ($response->answer as $answer) {
                        if (is_numeric($answer->latitude) && is_numeric($answer->longitude)) {
                            $location['location_lat'] = $answer->latitude;
                            $location['location_lon'] = $answer->longitude;
                            $reverse = TRUE;
                            break;
                        } else {
                            if (is_numeric($answer->degree_latitude) && is_numeric($answer->degree_longitude)) {
                                $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1;
                                $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1;
                                $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier;
                                $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier;
                                $reverse = TRUE;
                                break;
                            }
                        }
                    }
                    if (isset($location['location_lat'])) {
                        $debug_msg .= '  通过DNS位置记录 - 找到' . PHP_EOL;
                    } else {
                        $debug_msg .= '  通过DNS位置记录 - 未找到' . PHP_EOL;
                    }
                }
            }
        }
        if ($reverse || !preg_match('/^<?(unknown|none)>?$/i', $address)) {
            /**
             * If location string contains coordinates use Reverse Geocoding.
             * Valid strings:
             *   Some location [33.234, -56.22]
             *   Some location (33.234 -56.22)
             *   Some location [33.234;-56.22]
             *   33.234,-56.22
             */
            $pattern = '/(?:^|[\\[(])\\s*(?<lat>[+-]?\\d+(?:\\.\\d+)*)\\s*[,; ]\\s*(?<lon>[+-]?\\d+(?:\\.\\d+)*)\\s*(?:[\\])]|$)/';
            if (!$reverse && preg_match($pattern, $address, $matches)) {
                if ($matches['lat'] >= -90 && $matches['lat'] <= 90 && $matches['lon'] >= -180 && $matches['lon'] <= 180) {
                    $location['location_lat'] = $matches['lat'];
                    $location['location_lon'] = $matches['lon'];
                    $reverse = TRUE;
                }
            }
            if ($reverse) {
                $debug_msg .= '  by REVERSE query (API: ' . strtoupper($config['geocoding']['api']) . ', LAT: ' . $location['location_lat'] . ', LON: ' . $location['location_lon'] . ') - ';
                if (!is_numeric($location['location_lat']) || !is_numeric($location['location_lat'])) {
                    // Do nothing for empty, skip requests for empty coordinates
                } else {
                    if ($config['geocoding']['api'] == 'google') {
                        // latlng=40.714224,-73.961452
                        $request = $reverse_url . 'latlng=' . $location['location_lat'] . ',' . $location['location_lon'];
                    } else {
                        if ($config['geocoding']['api'] == 'yandex') {
                            // geocode=40.714224,-73.961452
                            $request = $reverse_url . 'geocode=' . $location['location_lat'] . ',' . $location['location_lon'];
                        } else {
                            // lat=51.521435&lon=-0.162714
                            $request = $reverse_url . 'lat=' . $location['location_lat'] . '&lon=' . $location['location_lon'];
                        }
                    }
                }
            } else {
                $debug_msg .= '  by PARSING sysLocation (API: ' . strtoupper($config['geocoding']['api']) . ') - ';
                if ($address != '') {
                    $request = $url . urlencode($address);
                }
            }
            if ($request) {
                // First request
                $mapresponse = get_http_request($request);
                $data = json_decode($mapresponse, TRUE);
                $geo_status = 'NOT FOUND';
                if ($config['geocoding']['api'] == 'google') {
                    if ($data['status'] == 'OVER_QUERY_LIMIT') {
                        $debug_msg .= $geo_status;
                        print_debug($debug_msg);
                        // Return empty array for overquery limit (for later recheck)
                        return array('location_status' => $debug_msg);
                    }
                    // Use google data only with good status response
                    if ($data['status'] == 'OK') {
                        $data = $data['results'][0];
                        if ($data['geometry']['location_type'] == 'APPROXIMATE') {
                            // It might be that the first element of the address is a business name.
                            // Lets drop the first element and see if we get anything better!
                            list(, $address) = explode(',', $address, 2);
                            $request_new = $url . urlencode($address);
                            $mapresponse = get_http_request($request_new);
                            $data_new = json_decode($mapresponse, TRUE);
                            if ($data_new['status'] == 'OK' && $data_new['results'][0]['geometry']['location_type'] != 'APPROXIMATE') {
                                $request = $request_new;
                                $data = $data_new['results'][0];
                            }
                        }
                    }
                } else {
                    if ($config['geocoding']['api'] == 'yandex') {
                        $try_new = FALSE;
                        if ($data['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] > 0) {
                            $data = $data['response']['GeoObjectCollection']['featureMember'][0];
                            if ($data['GeoObject']['metaDataProperty']['GeocoderMetaData']['precision'] == 'other') {
                                $try_new = TRUE;
                            }
                        } else {
                            $try_new = TRUE;
                        }
                        if ($try_new && strpos($address, ',')) {
                            // It might be that the first element of the address is a business name.
                            // Lets drop the first element and see if we get anything better!
                            list(, $address) = explode(',', $address, 2);
                            $request_new = $url . urlencode($address);
                            $mapresponse = get_http_request($request_new);
                            $data_new = json_decode($mapresponse, TRUE);
                            if ($data_new['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] > 0 && $data_new['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['metaDataProperty']['GeocoderMetaData']['precision'] != 'other') {
                                $request = $request_new;
                                $data = $data_new['response']['GeoObjectCollection']['featureMember'][0];
                            }
                        }
                    } else {
                        if (!isset($location['location_lat'])) {
                            $data = $data[0];
                            if (!count($data) && strpos($address, ',')) {
                                // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name.
                                // Lets drop the first element and see if we get anything better! This works more often than one might expect.
                                list(, $address) = explode(',', $address, 2);
                                $request_new = $url . urlencode($address);
                                $mapresponse = get_http_request($request_new);
                                $data_new = json_decode($mapresponse, TRUE);
                                if (count($data_new[0])) {
                                    // We only want the first entry in the returned data.
                                    $data = $data_new[0];
                                    $request = $request_new;
                                }
                            }
                        }
                    }
                }
                if (OBS_DEBUG > 1 && count($data)) {
                    var_dump($data);
                }
            } else {
                $geo_status = '没有要求';
            }
        }
    }
    // Put the values from the data array into the return array where they exist, else replace them with defaults or Unknown.
    if ($config['geocoding']['api'] == 'google') {
        $location['location_lat'] = $data['geometry']['location']['lat'];
        $location['location_lon'] = $data['geometry']['location']['lng'];
        foreach ($data['address_components'] as $entry) {
            switch ($entry['types'][0]) {
                case 'postal_town':
                case 'locality':
                    $location['location_city'] = $entry['long_name'];
                    break;
                case 'administrative_area_level_2':
                    $location['location_county'] = $entry['long_name'];
                    break;
                case 'administrative_area_level_1':
                    $location['location_state'] = $entry['long_name'];
                    break;
                case 'country':
                    $location['location_country'] = strtolower($entry['short_name']);
                    break;
            }
        }
    } else {
        if ($config['geocoding']['api'] == 'yandex') {
            list($location['location_lon'], $location['location_lat']) = explode(' ', $data['GeoObject']['Point']['pos']);
            $data = $data['GeoObject']['metaDataProperty']['GeocoderMetaData']['AddressDetails'];
            $location['location_country'] = strtolower($data['Country']['CountryNameCode']);
            $location['location_state'] = $data['Country']['AdministrativeArea']['AdministrativeAreaName'];
            $location['location_county'] = $data['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'];
            $location['location_city'] = $data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName'];
        } else {
            $location['location_lat'] = $data['lat'];
            $location['location_lon'] = $data['lon'];
            $location['location_city'] = strlen($data['address']['town']) ? $data['address']['town'] : $data['address']['city'];
            // Would be nice to have an array of countries where we want state, and ones where we want County. For example, USA wants state, UK wants county.
            $location['location_county'] = $data['address']['county'];
            $location['location_state'] = $data['address']['state'];
            $location['location_country'] = $data['address']['country_code'];
        }
    }
    // Use defaults if empty values
    if (!strlen($location['location_lat']) || !strlen($location['location_lon'])) {
        // Reset to empty coordinates
        $location['location_lat'] = array('NULL');
        $location['location_lon'] = array('NULL');
        //$location['location_lat'] = $config['geocoding']['default']['lat'];
        //$location['location_lon'] = $config['geocoding']['default']['lon'];
        //if (is_numeric($config['geocoding']['default']['lat']) && is_numeric($config['geocoding']['default']['lon']))
        //{
        //  $location['location_manual']     = 1; // Set manual key for ability reset from WUI
        //}
    } else {
        // Always round lat/lon same as DB precision (DECIMAL(10,7))
        $location['location_lat'] = round($location['location_lat'], 7);
        $location['location_lon'] = round($location['location_lon'], 7);
    }
    if (!strlen($location['location_city'])) {
        $location['location_city'] = '未知的城市';
    }
    if (!strlen($location['location_county'])) {
        $location['location_county'] = '未知的城镇';
    }
    if (!strlen($location['location_state'])) {
        $location['location_state'] = '未知的省份';
    }
    if (!strlen($location['location_country'])) {
        $location['location_country'] = '未知的国家';
    } else {
        $geo_status = 'FOUND';
    }
    // Print some debug informations
    $debug_msg .= $geo_status . PHP_EOL;
    $debug_msg .= '  GEO API REQUEST: ' . $request;
    if ($geo_status == 'FOUND') {
        $debug_msg .= PHP_EOL . '  GEOLOCATION: ';
        $debug_msg .= country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), ';
        $debug_msg .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)';
        $debug_msg .= PHP_EOL . '  GEO COORDINATES: ';
        $debug_msg .= $location['location_lat'] . ' (Latitude), ' . $location['location_lon'] . ' (Longitude)';
    } else {
        $debug_msg .= PHP_EOL . '  QUERY DATE: ' . date('r');
        // This is requered for increase data in DB
    }
    print_debug($debug_msg);
    $location['location_status'] = $debug_msg;
    return $location;
}
示例#2
0
function get_geolocation($address, $geo_db = array(), $dns_only = FALSE)
{
    global $config;
    $ok = FALSE;
    $location = array('location' => $address);
    // Init location array
    $location['location_geoapi'] = strtolower(trim($config['geocoding']['api']));
    if (!isset($config['geo_api'][$location['location_geoapi']])) {
        // Use default if unknown api
        $location['location_geoapi'] = 'openstreetmap';
    }
    $api_params =& $config['geo_api'][$location['location_geoapi']];
    // Link to api specific params
    $params = $api_params['params'];
    // Init base request params
    // GEO API KEY and rate limits
    $ratelimit = FALSE;
    if (strlen($config['geocoding']['api_key']) && isset($api_params['request_params']['key'])) {
        $param = $api_params['request_params']['key'];
        $params[$param] = escape_html($config['geocoding']['api_key']);
        // KEYs is never used special characters
        if (isset($api_params['ratelimit_key'])) {
            $ratelimit = $api_params['ratelimit_key'];
        }
    } else {
        if (isset($api_params['ratelimit'])) {
            $ratelimit = $api_params['ratelimit'];
        }
    }
    if (isset($api_params['request_params']['id'])) {
        $params[$api_params['request_params']['id']] = OBSERVIUM_PRODUCT . '-' . substr(get_unique_id(), 0, 8);
    }
    if (isset($api_params['request_params']['uuid'])) {
        $params[$api_params['request_params']['uuid']] = get_unique_id();
    }
    if (isset($config['geocoding']['enable']) && $config['geocoding']['enable']) {
        $reverse = FALSE;
        // by default forward geocoding
        $debug_msg = "Geocoding ENABLED, try detect device coordinates:" . PHP_EOL;
        // If device coordinates set manually, use Reverse Geocoding.
        if ($geo_db['location_manual']) {
            $location['location_lat'] = $geo_db['location_lat'];
            $location['location_lon'] = $geo_db['location_lon'];
            $reverse = TRUE;
            $debug_msg .= '  MANUAL coordinates - SET' . PHP_EOL;
        } else {
            if ($config['geocoding']['dns']) {
                /**
                 * Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using
                 * DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual).
                 *
                 * Example LOC:
                 *   "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m"
                 *
                 * From Wikipedia: d1 [m1 [s1]] {"N"|"S"}  d2 [m2 [s2]] {"E"|"W"}
                 *
                 * Parsing this is something for Net_DNS2 as it has the code for it.
                 */
                if ($geo_db['hostname']) {
                    //include_once('Net/DNS2.php');
                    //include_once('Net/DNS2/RR/LOC.php');
                    $resolver = new Net_DNS2_Resolver();
                    try {
                        $response = $resolver->query($geo_db['hostname'], 'LOC', 'IN');
                    } catch (Net_DNS2_Exception $e) {
                        print_debug('  ' . $e->getMessage() . ' (' . $geo_db['hostname'] . ')');
                    }
                } else {
                    $response = FALSE;
                    print_debug("  DNS LOC enabled, but device hostname empty.");
                }
                if ($response) {
                    if (OBS_DEBUG > 1) {
                        var_dump($response->answer);
                    }
                    foreach ($response->answer as $answer) {
                        if (is_numeric($answer->latitude) && is_numeric($answer->longitude)) {
                            $location['location_lat'] = $answer->latitude;
                            $location['location_lon'] = $answer->longitude;
                            $reverse = TRUE;
                            break;
                        } else {
                            if (is_numeric($answer->degree_latitude) && is_numeric($answer->degree_longitude)) {
                                $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1;
                                $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1;
                                $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier;
                                $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier;
                                $reverse = TRUE;
                                break;
                            }
                        }
                    }
                    if (isset($location['location_lat'])) {
                        $debug_msg .= '  DNS LOC records - FOUND' . PHP_EOL;
                    } else {
                        $debug_msg .= '  DNS LOC records - NOT FOUND' . PHP_EOL;
                        if ($dns_only) {
                            // If we check only DNS LOC records but it not found, exit
                            print_debug($debug_msg);
                            return FALSE;
                        }
                    }
                }
            }
        }
        if ($reverse || !preg_match('/^<?(unknown|none)>?$/i', $address)) {
            /**
             * If location string contains coordinates use Reverse Geocoding.
             * Valid strings:
             *   Some location [33.234, -56.22]
             *   Some location (33.234 -56.22)
             *   Some location [33.234;-56.22]
             *   33.234,-56.22
             */
            $pattern = '/(?:^|[\\[(])\\s*(?<lat>[+-]?\\d+(?:\\.\\d+)*)\\s*[,; ]\\s*(?<lon>[+-]?\\d+(?:\\.\\d+)*)\\s*(?:[\\])]|$)/';
            if (!$reverse && preg_match($pattern, $address, $matches)) {
                if ($matches['lat'] >= -90 && $matches['lat'] <= 90 && $matches['lon'] >= -180 && $matches['lon'] <= 180) {
                    $location['location_lat'] = $matches['lat'];
                    $location['location_lon'] = $matches['lon'];
                    $reverse = TRUE;
                }
            }
            if ($reverse) {
                $debug_msg .= '  by REVERSE query (API: ' . strtoupper($config['geocoding']['api']) . ', LAT: ' . $location['location_lat'] . ', LON: ' . $location['location_lon'] . ') - ';
                $url = $api_params['reverse_url'];
                if (isset($api_params['reverse_params'])) {
                    // Additional params for reverse query
                    $params = array_merge($params, $api_params['reverse_params']);
                }
                if (!is_numeric($location['location_lat']) || !is_numeric($location['location_lat'])) {
                    // Do nothing for empty, skip requests for empty coordinates
                } else {
                    if (isset($api_params['request_params']['lat']) && isset($api_params['request_params']['lon'])) {
                        $ok = TRUE;
                        $param = $api_params['request_params']['lat'];
                        $params[$param] = $location['location_lat'];
                        $param = $api_params['request_params']['lon'];
                        $params[$param] = $location['location_lon'];
                    } else {
                        if (isset($api_params['request_params']['latlon'])) {
                            $ok = TRUE;
                            $param = $api_params['request_params']['latlon'];
                            $params[$param] = $location['location_lat'] . ',' . $location['location_lon'];
                        }
                    }
                }
            } else {
                $debug_msg .= '  by PARSING sysLocation (API: ' . strtoupper($config['geocoding']['api']) . ') - ';
                $url = $api_params['direct_url'];
                if (isset($api_params['direct_params'])) {
                    // Additional params for reverse query
                    $params = array_merge($params, $api_params['direct_params']);
                }
                if ($address != '') {
                    $ok = TRUE;
                    $param = $api_params['request_params']['address'];
                    $params[$param] = urlencode($address);
                    //$request = $url . urlencode($address);
                }
            }
            if (OBS_DEBUG > 1) {
                print_vars($api_params);
                print_vars($params);
            }
            if ($ok) {
                // Build request query
                $request = build_request_url($url, $params, $api_params['method']);
                // First request
                $mapresponse = get_http_request($request, NULL, $ratelimit);
                switch ($GLOBALS['response_headers']['code'][0]) {
                    case '4':
                        // 4xx (timeout, rate limit, forbidden)
                    // 4xx (timeout, rate limit, forbidden)
                    case '5':
                        // 5xx (server error)
                        $geo_status = strtoupper($GLOBALS['response_headers']['status']);
                        $debug_msg .= $geo_status . PHP_EOL;
                        if (OBS_DEBUG < 2) {
                            // Hide API KEY from output
                            $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request);
                        }
                        $debug_msg .= '  GEO API REQUEST: ' . $request;
                        print_debug($debug_msg);
                        // Return old array with new status (for later recheck)
                        unset($geo_db['hostname'], $geo_db['location_updated']);
                        $location['location_status'] = $debug_msg;
                        $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s');
                        //print_vars($location);
                        //print_vars($geo_db);
                        return array_merge($geo_db, $location);
                }
                $data = json_decode($mapresponse, TRUE);
                //print_vars($data);
                $geo_status = 'NOT FOUND';
                $api_specific = is_file($config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php');
                if ($api_specific) {
                    // API specific parser
                    require_once $config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php';
                    if ($data === FALSE) {
                        // Return old array with new status (for later recheck)
                        unset($geo_db['hostname'], $geo_db['location_updated']);
                        //$location['location_status']  = $debug_msg;
                        $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s');
                        //print_vars($location);
                        //print_vars($geo_db);
                        return array_merge($geo_db, $location);
                    }
                } else {
                    if (!isset($location['location_lat'])) {
                        $data = $data[0];
                        if (!count($data) && strpos($address, ',')) {
                            // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name.
                            // Lets drop the first element and see if we get anything better! This works more often than one might expect.
                            list(, $address_new) = explode(',', $address, 2);
                            //$request_new = $url.urlencode($address);
                            $param = $api_params['request_params']['address'];
                            $params[$param] = urlencode($address_new);
                            $request_new = build_request_url($url, $params, $api_params['method']);
                            $mapresponse = get_http_request($request_new, NULL, $ratelimit);
                            $data_new = json_decode($mapresponse, TRUE);
                            if (count($data_new[0])) {
                                // We only want the first entry in the returned data.
                                $data = $data_new[0];
                                $request = $request_new;
                            }
                        }
                    }
                }
                if (OBS_DEBUG > 1 && count($data)) {
                    var_dump($data);
                }
            } else {
                $geo_status = 'NOT REQUESTED';
            }
        }
    }
    if (!$api_specific) {
        // Nominatum
        if (!$reverse) {
            // If using reverse queries, do not change lat/lon
            $location['location_lat'] = $data['lat'];
            $location['location_lon'] = $data['lon'];
        }
        foreach (array('town', 'city', 'hamlet', 'village') as $param) {
            if (isset($data['address'][$param])) {
                $location['location_city'] = $data['address'][$param];
                break;
            }
        }
        $location['location_state'] = $data['address']['state'];
        $location['location_county'] = isset($data['address']['county']) ? $data['address']['county'] : $data['address']['state_district'];
        $location['location_country'] = $data['address']['country_code'];
    }
    // Use defaults if empty values
    if (!strlen($location['location_lat']) || !strlen($location['location_lon'])) {
        // Reset to empty coordinates
        $location['location_lat'] = array('NULL');
        $location['location_lon'] = array('NULL');
        //$location['location_lat'] = $config['geocoding']['default']['lat'];
        //$location['location_lon'] = $config['geocoding']['default']['lon'];
        //if (is_numeric($config['geocoding']['default']['lat']) && is_numeric($config['geocoding']['default']['lon']))
        //{
        //  $location['location_manual']     = 1; // Set manual key for ability reset from WUI
        //}
    } else {
        // Always round lat/lon same as DB precision (DECIMAL(10,7))
        $location['location_lat'] = round($location['location_lat'], 7);
        $location['location_lon'] = round($location['location_lon'], 7);
    }
    foreach (array('city', 'county', 'state') as $entry) {
        // Remove duplicate County/State words
        $param = 'location_' . $entry;
        $location[$param] = strlen($location[$param]) ? str_ireplace(' ' . $entry, '', $location[$param]) : 'Unknown';
    }
    if (strlen($location['location_country'])) {
        $location['location_country'] = strtolower($location['location_country']);
        $geo_status = 'FOUND';
    } else {
        $location['location_country'] = 'Unknown';
    }
    // Print some debug informations
    $debug_msg .= $geo_status . PHP_EOL;
    if (OBS_DEBUG < 2) {
        // Hide API KEY from output
        $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request);
    }
    $debug_msg .= '  GEO API REQUEST: ' . $request;
    if ($geo_status == 'FOUND') {
        $debug_msg .= PHP_EOL . '  GEO LOCATION: ';
        $debug_msg .= country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), ';
        $debug_msg .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)';
        $debug_msg .= PHP_EOL . '  GEO COORDINATES: ';
        $debug_msg .= $location['location_lat'] . ' (Latitude), ' . $location['location_lon'] . ' (Longitude)';
    } else {
        $debug_msg .= PHP_EOL . '  QUERY DATE: ' . date('r');
        // This is requered for increase data in DB
    }
    print_debug($debug_msg);
    $location['location_status'] = $debug_msg;
    return $location;
}
示例#3
0
 function location_menu($array)
 {
     global $config;
     ksort($array['entries']);
     echo '<ul style="" class="dropdown-menu" style="min-width: 250px;">';
     if (count($array['entries']) > "3") {
         foreach ($array['entries'] as $entry => $entry_data) {
             if ($entry_data['level'] == "location_country") {
                 $code = $entry;
                 $entry = country_from_code($entry);
                 $image = '<i class="flag flag-' . $code . '" alt="' . $entry . '"></i>';
             } elseif ($entry_data['level'] == "location") {
                 echo '            <li><a href="' . generate_url(array('page' => 'devices', 'location' => urlencode($entry))) . '/"><i class="menu-icon oicon-building"></i> ' . $entry . ' (' . $entry_data['count'] . ')</a></li>';
                 continue;
             }
             echo '<li class="dropdown-submenu"><a href="' . generate_url(array('page' => 'devices', $entry_data['level'] => urlencode($entry))) . '/">
         ' . $image . ' ' . $entry . '(' . $entry_data['count'] . ')</a>';
             location_menu($entry_data);
             echo '</li>';
         }
     } else {
         $new_entry_array = array();
         foreach ($array['entries'] as $new_entry => $new_entry_data) {
             if ($new_entry_data['level'] == "location_country") {
                 $code = $new_entry;
                 $new_entry = country_from_code($new_entry);
                 $image = '<i class="flag flag-' . $code . '" alt="' . $new_entry . '"></i> ';
             } elseif ($new_entry_data['level'] == "location") {
                 echo '            <li><a href="' . generate_url(array('page' => 'devices', 'location' => urlencode($new_entry))) . '/"><i class="menu-icon oicon-building"></i> ' . $new_entry . ' (' . $new_entry_data['count'] . ')</a></li>';
                 continue;
             }
             echo '<li class="nav-header">' . $image . $new_entry . '</li>';
             foreach ($new_entry_data['entries'] as $sub_entry => $sub_entry_data) {
                 if (is_array($sub_entry_data['entries'])) {
                     echo '<li class="dropdown-submenu"><a style="" href="' . generate_url(array('page' => 'devices', $sub_entry_data['level'] => urlencode($sub_entry))) . '/">
             <i class="menu-icon oicon-building"></i> ' . $sub_entry . '(' . $sub_entry_data['count'] . ')</a>';
                     location_menu($sub_entry_data);
                 } else {
                     echo '            <li><a href="' . generate_url(array('page' => 'devices', 'location' => urlencode($sub_entry))) . '/"><i class="menu-icon oicon-building"></i> ' . $sub_entry . ' (' . $sub_entry_data['count'] . ')</a></li>';
                 }
                 echo '</li>';
             }
         }
     }
     echo '</ul>';
 }
function navbar_location_menu($array)
{
    global $config;
    ksort($array['entries']);
    echo '<ul class="dropdown-menu">';
    if (count($array['entries']) > "3") {
        foreach ($array['entries'] as $entry => $entry_data) {
            $image = '<i class="menu-icon oicon-building"></i>';
            if ($entry_data['level'] == "location_country") {
                $code = $entry;
                $entry = country_from_code($entry);
                $image = '<i class="flag flag-' . $code . '"></i>';
            } elseif ($entry_data['level'] == "location") {
                $name = $entry === '' ? OBS_VAR_UNSET : escape_html($entry);
                echo '            <li><a href="' . generate_location_url($entry) . '"><i class="menu-icon oicon-building-small"></i> ' . $name . '&nbsp;[' . $entry_data['count'] . ']</a></li>';
                continue;
            }
            $url = $entry_data['level'] == 'location_country' ? $code : $entry;
            echo '<li class="dropdown-submenu"><a href="' . generate_url(array('page' => 'devices', $entry_data['level'] => var_encode($url))) . '">' . $image . ' ' . $entry . '&nbsp;[' . $entry_data['count'] . ']</a>';
            navbar_location_menu($entry_data);
            echo '</li>';
        }
    } else {
        $new_entry_array = array();
        foreach ($array['entries'] as $new_entry => $new_entry_data) {
            if ($new_entry_data['level'] == "location_country") {
                $code = $new_entry;
                $new_entry = country_from_code($new_entry);
                $image = '<i class="flag flag-' . $code . '"></i> ';
            } elseif ($new_entry_data['level'] == "location") {
                $name = $new_entry === '' ? OBS_VAR_UNSET : escape_html($new_entry);
                echo '            <li><a href="' . generate_location_url($new_entry) . '"><i class="menu-icon oicon-building-small"></i> ' . $name . '&nbsp;[' . $new_entry_data['count'] . ']</a></li>';
                continue;
            }
            echo '<li class="nav-header">' . $image . $new_entry . '</li>';
            foreach ($new_entry_data['entries'] as $sub_entry => $sub_entry_data) {
                if (is_array($sub_entry_data['entries'])) {
                    echo '<li class="dropdown-submenu"><a style="" href="' . generate_url(array('page' => 'devices', $sub_entry_data['level'] => var_encode($sub_entry))) . '">
                <i class="menu-icon oicon-building"></i> ' . $sub_entry . '&nbsp;[' . $sub_entry_data['count'] . ']</a>';
                    navbar_location_menu($sub_entry_data);
                } else {
                    $name = $sub_entry === '' ? OBS_VAR_UNSET : escape_html($sub_entry);
                    echo '            <li><a href="' . generate_location_url($sub_entry) . '"><i class="menu-icon oicon-building-small"></i> ' . $name . '&nbsp;[' . $sub_entry_data['count'] . ']</a></li>';
                }
            }
        }
    }
    echo '</ul>';
}
     // Redetect geolocation if coordinates still empty, no more frequently than once a day
     $geo_updated = $config['time']['now'] - strtotime($geo_db['location_updated']);
     $geo_detect = $geo_detect || $geo_updated > 86400;
 }
 $geo_detect = $geo_detect || $poll_device['sysLocation'] && $device['location'] != $poll_device['sysLocation'];
 $geo_detect = $geo_detect || $geo_db['location_geoapi'] != strtolower($config['geocoding']['api']);
 $geo_detect = $geo_detect || $geo_db['location_manual'] && (!$geo_db['location_country'] || $geo_db['location_country'] == 'Unknown');
 if ($geo_detect) {
     $update_geo = get_geolocation($poll_device['sysLocation'], $geo_db);
     if (OBS_DEBUG && count($update_geo)) {
         print_vars($update_geo);
     }
     if (is_numeric($update_geo['location_lat']) && is_numeric($update_geo['location_lon']) && $update_geo['location_country'] != 'Unknown') {
         $geo_msg = 'Geolocation (' . strtoupper($update_geo['location_geoapi']) . ') -> ';
         $geo_msg .= '[' . sprintf('%f', $update_geo['location_lat']) . ', ' . sprintf('%f', $update_geo['location_lon']) . '] ';
         $geo_msg .= country_from_code($update_geo['location_country']) . ' (Country), ' . $update_geo['location_state'] . ' (State), ';
         $geo_msg .= $update_geo['location_county'] . ' (County), ' . $update_geo['location_city'] . ' (City)';
     } else {
         $geo_msg = FALSE;
     }
     if ($db_version < 169) {
         // FIXME. remove this part in r7000
         $update_array = array_merge($update_array, $update_geo);
         log_event("Geolocation -> {$geo_msg}", $device, 'device', $device['device_id']);
     } else {
         if (is_numeric($geo_db['location_id'])) {
             foreach ($update_geo as $k => $value) {
                 if ($geo_db[$k] == $value) {
                     unset($update_geo[$k]);
                 }
             }
        $location['location_text'] = $override_sysLocation_string;
    }
}
if ($location['location_text'] == '') {
    $location['location_text'] = OBS_VAR_UNSET;
}
foreach (array('location_lat', 'location_lon', 'location_city', 'location_county', 'location_state', 'location_country', 'location_geoapi', 'location_status', 'location_manual', 'location_updated') as $param) {
    $location[$param] = $device[$param];
}
if (is_numeric($location['location_lat']) && is_numeric($location['location_lon'])) {
    // Generate link to Google maps
    // http://maps.google.com/maps?q=46.090271,6.657248+description+(name)
    $location['coordinates'] = $location['location_lat'] . ',' . $location['location_lon'];
    $location['coordinates_manual'] = $location['coordinates'];
    $location['location_link'] = '<a target="_blank" href="http://maps.google.com/maps?q=' . urlencode($location['coordinates']) . '"><i class="oicon-map"></i> View this location on a map</a>';
    $location['location_geo'] = country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), ';
    $location['location_geo'] .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)';
    switch ($location['location_geoapi']) {
        //case 'yandex':
        //  // Generate link to Yandex maps
        //  $location['location_link'] = '<a target="_blank" href="http://maps.google.com/maps?q='.urlencode($location['coordinates']).'"><i class="oicon-map"></i> View this location on a map</a>';
        //  break;
        default:
            // Generate link to Google maps
            // http://maps.google.com/maps?q=46.090271,6.657248+description+(name)
            $location['location_link'] = '<a target="_blank" href="http://maps.google.com/maps?q=' . urlencode($location['coordinates']) . '"><i class="oicon-map"></i> View this location on a map</a>';
    }
} else {
    $location['coordinates_manual'] = $config['geocoding']['default']['lat'] . ',' . $config['geocoding']['default']['lon'];
}
if ($updated && $update_message) {
示例#7
0
function navbar_location_menu($array)
{
    global $config;
    ksort($array['entries']);
    echo '<ul role="menu" class="dropdown-menu">';
    if (count($array['entries']) > "5") {
        foreach ($array['entries'] as $entry => $entry_data) {
            $image = '<i class="menu-icon oicon-building"></i>';
            if ($entry_data['level'] == "location_country") {
                $code = $entry;
                $entry = country_from_code($entry);
                $image = '<i class="flag flag-' . $code . '"></i>';
            } else {
                if ($entry_data['level'] == "location") {
                    $name = $entry === '' ? OBS_VAR_UNSET : escape_html($entry);
                    echo '            <li>' . generate_menu_link(generate_location_url($entry), '<i class="menu-icon oicon-building-small"></i>&nbsp;' . $name, $entry_data['count']) . '</li>';
                    continue;
                }
            }
            if ($entry_data['level'] == "location_country") {
                $url = $code;
                // Attach country code to sublevel
                $entry_data['country'] = strtolower($code);
            } else {
                $url = $entry;
                // Attach country code to sublevel
                $entry_data['country'] = $array['country'];
            }
            if ($url === '') {
                $url = array('');
            }
            $link_array = array('page' => 'devices', $entry_data['level'] => var_encode($url));
            if (isset($array['country'])) {
                $link_array['location_country'] = var_encode($array['country']);
            }
            echo '<li class="dropdown-submenu">' . generate_menu_link(generate_url($link_array), $image . '&nbsp;' . $entry, $entry_data['count']);
            navbar_location_menu($entry_data);
            echo '</li>';
        }
    } else {
        $new_entry_array = array();
        foreach ($array['entries'] as $new_entry => $new_entry_data) {
            if ($new_entry_data['level'] == "location_country") {
                $code = $new_entry;
                $new_entry = country_from_code($new_entry);
                $image = '<i class="flag flag-' . $code . '"></i> ';
            } elseif ($new_entry_data['level'] == "location") {
                $name = $new_entry === '' ? OBS_VAR_UNSET : escape_html($new_entry);
                echo '            <li>' . generate_menu_link(generate_location_url($new_entry), '<i class="menu-icon oicon-building-small"></i>&nbsp;' . $name, $new_entry_data['count']) . '</li>';
                continue;
            }
            echo '<li class="nav-header">' . $image . $new_entry . '</li>';
            foreach ($new_entry_data['entries'] as $sub_entry => $sub_entry_data) {
                if (is_array($sub_entry_data['entries'])) {
                    $link_array = array('page' => 'devices', $sub_entry_data['level'] => var_encode($sub_entry));
                    if (isset($array['country'])) {
                        $link_array['location_country'] = var_encode($array['country']);
                    }
                    echo '<li class="dropdown-submenu">' . generate_menu_link(generate_url($link_array), '<i class="menu-icon oicon-building"></i>&nbsp;' . $sub_entry, $sub_entry_data['count']);
                    navbar_location_menu($sub_entry_data);
                } else {
                    $name = $sub_entry === '' ? OBS_VAR_UNSET : escape_html($sub_entry);
                    echo '            <li>' . generate_menu_link(generate_location_url($sub_entry), '<i class="menu-icon oicon-building-small"></i>&nbsp;' . $name, $sub_entry_data['count']) . '</li>';
                }
            }
        }
    }
    echo '</ul>';
}