1 # The OSM module provides support functions for OSM.
 
   5   require 'rexml/parsers/sax2parser'
 
   9   if defined?(SystemTimer)
 
  16   # The base class for API Errors.
 
  17   class APIError < RuntimeError
 
  19       :internal_server_error
 
  27   # Raised when an API object is not found.
 
  28   class APINotFoundError < APIError
 
  38   # Raised when a precondition to an API action fails sanity check.
 
  39   class APIPreconditionFailedError < APIError
 
  40     def initialize(message = "")
 
  49       "Precondition failed: #{@message}"
 
  53   # Raised when to delete an already-deleted object.
 
  54   class APIAlreadyDeletedError < APIError
 
  55     def initialize(object = "object", object_id = "")
 
  56       @object, @object_id = object, object_id
 
  59     attr_reader :object, :object_id
 
  66       "The #{object} with the id #{object_id} has already been deleted"
 
  70   # Raised when the user logged in isn't the same as the changeset
 
  71   class APIUserChangesetMismatchError < APIError
 
  77       "The user doesn't own that changeset"
 
  81   # Raised when the changeset provided is already closed
 
  82   class APIChangesetAlreadyClosedError < APIError
 
  83     def initialize(changeset)
 
  84       @changeset = changeset
 
  87     attr_reader :changeset
 
  94       "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
 
  98   # Raised when a change is expecting a changeset, but the changeset doesn't exist
 
  99   class APIChangesetMissingError < APIError
 
 105       "You need to supply a changeset to be able to make a change"
 
 109   # Raised when a diff is uploaded containing many changeset IDs which don't match
 
 110   # the changeset ID that the diff was uploaded to.
 
 111   class APIChangesetMismatchError < APIError
 
 112     def initialize(provided, allowed)
 
 113       @provided, @allowed = provided, allowed
 
 121       "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
 
 125   # Raised when a diff upload has an unknown action. You can only have create,
 
 127   class APIChangesetActionInvalid < APIError
 
 128     def initialize(provided)
 
 137       "Unknown action #{@provided}, choices are create, modify, delete"
 
 141   # Raised when bad XML is encountered which stops things parsing as
 
 143   class APIBadXMLError < APIError
 
 144     def initialize(model, xml, message="")
 
 145       @model, @xml, @message = model, xml, message
 
 153       "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
 
 157   # Raised when the provided version is not equal to the latest in the db.
 
 158   class APIVersionMismatchError < APIError
 
 159     def initialize(id, type, provided, latest)
 
 160       @id, @type, @provided, @latest = id, type, provided, latest
 
 163     attr_reader :provided, :latest, :id, :type
 
 170       "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
 
 174   # raised when a two tags have a duplicate key string in an element.
 
 175   # this is now forbidden by the API.
 
 176   class APIDuplicateTagsError < APIError
 
 177     def initialize(type, id, tag_key)
 
 178       @type, @id, @tag_key = type, id, tag_key
 
 181     attr_reader :type, :id, :tag_key
 
 188       "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
 
 192   # Raised when a way has more than the configured number of way nodes.
 
 193   # This prevents ways from being to long and difficult to work with
 
 194   class APITooManyWayNodesError < APIError
 
 195     def initialize(id, provided, max)
 
 196       @id, @provided, @max = id, provided, max
 
 199     attr_reader :id, :provided, :max
 
 206       "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
 
 211   # raised when user input couldn't be parsed
 
 212   class APIBadUserInput < APIError
 
 213     def initialize(message)
 
 227   # raised when bounding box is invalid
 
 228   class APIBadBoundingBox < APIError
 
 229     def initialize(message)
 
 243   # raised when an API call is made using a method not supported on that URI
 
 244   class APIBadMethodError < APIError
 
 245     def initialize(supported_method)
 
 246       @supported_method = supported_method
 
 254       "Only method #{@supported_method} is supported on this URI"
 
 259   # raised when an API call takes too long
 
 260   class APITimeoutError < APIError
 
 271   # raised when someone tries to redact a current version of
 
 272   # an element - only historical versions can be redacted.
 
 273   class APICannotRedactError < APIError
 
 279       "Cannot redact current version of element, only historical versions may be redacted."
 
 283   # Raised when the note provided is already closed
 
 284   class APINoteAlreadyClosedError < APIError
 
 296       "The note #{@note.id} was closed at #{@note.closed_at}"
 
 300   # Raised when the note provided is already open
 
 301   class APINoteAlreadyOpenError < APIError
 
 313       "The note #{@note.id} is already open"
 
 317   # raised when a two preferences have a duplicate key string.
 
 318   class APIDuplicatePreferenceError < APIError
 
 330       "Duplicate preferences with key #{@key}"
 
 334   # Helper methods for going to/from mercator and lat/lng.
 
 338     #init me with your bounding box and the size of your image
 
 339     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
 
 340       xsize = xsheet(max_lon) - xsheet(min_lon)
 
 341       ysize = ysheet(max_lat) - ysheet(min_lat)
 
 342       xscale = xsize / width
 
 343       yscale = ysize / height
 
 344       scale = [xscale, yscale].max
 
 346       xpad = width * scale - xsize
 
 347       ypad = height * scale - ysize
 
 352       @tx = xsheet(min_lon) - xpad / 2
 
 353       @ty = ysheet(min_lat) - ypad / 2
 
 355       @bx = xsheet(max_lon) + xpad / 2
 
 356       @by = ysheet(max_lat) + ypad / 2
 
 359     #the following two functions will give you the x/y on the entire sheet
 
 362       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
 
 369     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
 
 372       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
 
 376       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
 
 383     # initialise with a base position
 
 384     def initialize(lat, lon)
 
 385       @lat = lat * PI / 180
 
 386       @lon = lon * PI / 180
 
 389     # get the distance from the base position to a given position
 
 390     def distance(lat, lon)
 
 393       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
 
 396     # get the worst case bounds for a given radius from the base position
 
 398       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
 
 401         lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
 
 406       minlat = (@lat - latradius) * 180 / PI
 
 407       maxlat = (@lat + latradius) * 180 / PI
 
 408       minlon = (@lon - lonradius) * 180 / PI
 
 409       maxlon = (@lon + lonradius) * 180 / PI
 
 411       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
 
 414     # get the SQL to use to calculate distance
 
 415     def sql_for_distance(lat_field, lon_field)
 
 416       "6372.795 * 2 * asin(sqrt(power(sin((radians(#{lat_field}) - #{@lat}) / 2), 2) + cos(#{@lat}) * cos(radians(#{lat_field})) * power(sin((radians(#{lon_field}) - #{@lon})/2), 2)))"
 
 422       doc = XML::Document.new
 
 423       doc.encoding = XML::Encoding::UTF_8
 
 424       root = XML::Node.new 'osm'
 
 425       root['version'] = API_VERSION.to_s
 
 426       root['generator'] = GENERATOR
 
 427       root['copyright'] = COPYRIGHT_OWNER
 
 428       root['attribution'] = ATTRIBUTION_URL
 
 429       root['license'] =  LICENSE_URL
 
 435   def self.IPToCountry(ip_address)
 
 437       ipinfo = Quova::IpInfo.new(ip_address)
 
 439       if ipinfo.status == Quova::Success then
 
 440         country = ipinfo.country_code
 
 442         Net::HTTP.start('api.hostip.info') do |http|
 
 443           country = http.get("/country.php?ip=#{ip_address}").body
 
 444           country = "GB" if country == "UK"
 
 448       return country.upcase
 
 456   def self.IPLocation(ip_address)
 
 457     code = OSM.IPToCountry(ip_address)
 
 459     if code and country = Country.find_by_code(code)
 
 460       return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
 
 466   # Parse a float, raising a specified exception on failure
 
 467   def self.parse_float(str, klass, *args)
 
 470     raise klass.new(*args)
 
 473   # Construct a random token of a given length
 
 474   def self.make_token(length = 30)
 
 475     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
 
 479       token += chars[(rand * chars.length).to_i].chr
 
 485   # Return an SQL fragment to select a given area of the globe
 
 486   def self.sql_for_area(bbox, prefix = nil)
 
 487     tilesql = QuadTile.sql_for_area(bbox, prefix)
 
 488     bbox = bbox.to_scaled
 
 490     return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
 
 491                       "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
 
 494   def self.legal_text_for_country(country_code)
 
 495     file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
 
 496     file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
 
 497     YAML::load_file(file_name)