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 access is denied.
28 class APIAccessDenied < RuntimeError
38 # Raised when an API object is not found.
39 class APINotFoundError < APIError
49 # Raised when a precondition to an API action fails sanity check.
50 class APIPreconditionFailedError < APIError
51 def initialize(message = "")
60 "Precondition failed: #{@message}"
64 # Raised when to delete an already-deleted object.
65 class APIAlreadyDeletedError < APIError
66 def initialize(object = "object", object_id = "")
67 @object, @object_id = object, object_id
70 attr_reader :object, :object_id
77 "The #{object} with the id #{object_id} has already been deleted"
81 # Raised when the user logged in isn't the same as the changeset
82 class APIUserChangesetMismatchError < APIError
88 "The user doesn't own that changeset"
92 # Raised when the changeset provided is already closed
93 class APIChangesetAlreadyClosedError < APIError
94 def initialize(changeset)
95 @changeset = changeset
98 attr_reader :changeset
105 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
109 # Raised when a change is expecting a changeset, but the changeset doesn't exist
110 class APIChangesetMissingError < APIError
116 "You need to supply a changeset to be able to make a change"
120 # Raised when a diff is uploaded containing many changeset IDs which don't match
121 # the changeset ID that the diff was uploaded to.
122 class APIChangesetMismatchError < APIError
123 def initialize(provided, allowed)
124 @provided, @allowed = provided, allowed
132 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
136 # Raised when a diff upload has an unknown action. You can only have create,
138 class APIChangesetActionInvalid < APIError
139 def initialize(provided)
148 "Unknown action #{@provided}, choices are create, modify, delete"
152 # Raised when bad XML is encountered which stops things parsing as
154 class APIBadXMLError < APIError
155 def initialize(model, xml, message="")
156 @model, @xml, @message = model, xml, message
164 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
168 # Raised when the provided version is not equal to the latest in the db.
169 class APIVersionMismatchError < APIError
170 def initialize(id, type, provided, latest)
171 @id, @type, @provided, @latest = id, type, provided, latest
174 attr_reader :provided, :latest, :id, :type
181 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
185 # raised when a two tags have a duplicate key string in an element.
186 # this is now forbidden by the API.
187 class APIDuplicateTagsError < APIError
188 def initialize(type, id, tag_key)
189 @type, @id, @tag_key = type, id, tag_key
192 attr_reader :type, :id, :tag_key
199 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
203 # Raised when a way has more than the configured number of way nodes.
204 # This prevents ways from being to long and difficult to work with
205 class APITooManyWayNodesError < APIError
206 def initialize(id, provided, max)
207 @id, @provided, @max = id, provided, max
210 attr_reader :id, :provided, :max
217 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
222 # raised when user input couldn't be parsed
223 class APIBadUserInput < APIError
224 def initialize(message)
238 # raised when bounding box is invalid
239 class APIBadBoundingBox < APIError
240 def initialize(message)
254 # raised when an API call is made using a method not supported on that URI
255 class APIBadMethodError < APIError
256 def initialize(supported_method)
257 @supported_method = supported_method
265 "Only method #{@supported_method} is supported on this URI"
270 # raised when an API call takes too long
271 class APITimeoutError < APIError
282 # raised when someone tries to redact a current version of
283 # an element - only historical versions can be redacted.
284 class APICannotRedactError < APIError
290 "Cannot redact current version of element, only historical versions may be redacted."
294 # Raised when the note provided is already closed
295 class APINoteAlreadyClosedError < APIError
307 "The note #{@note.id} was closed at #{@note.closed_at}"
311 # Raised when the note provided is already open
312 class APINoteAlreadyOpenError < APIError
324 "The note #{@note.id} is already open"
328 # raised when a two preferences have a duplicate key string.
329 class APIDuplicatePreferenceError < APIError
341 "Duplicate preferences with key #{@key}"
345 # Helper methods for going to/from mercator and lat/lng.
349 #init me with your bounding box and the size of your image
350 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
351 xsize = xsheet(max_lon) - xsheet(min_lon)
352 ysize = ysheet(max_lat) - ysheet(min_lat)
353 xscale = xsize / width
354 yscale = ysize / height
355 scale = [xscale, yscale].max
357 xpad = width * scale - xsize
358 ypad = height * scale - ysize
363 @tx = xsheet(min_lon) - xpad / 2
364 @ty = ysheet(min_lat) - ypad / 2
366 @bx = xsheet(max_lon) + xpad / 2
367 @by = ysheet(max_lat) + ypad / 2
370 #the following two functions will give you the x/y on the entire sheet
373 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
380 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
383 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
387 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
394 # initialise with a base position
395 def initialize(lat, lon)
396 @lat = lat * PI / 180
397 @lon = lon * PI / 180
400 # get the distance from the base position to a given position
401 def distance(lat, lon)
404 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
407 # get the worst case bounds for a given radius from the base position
409 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
412 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
413 rescue Errno::EDOM, Math::DomainError
417 minlat = (@lat - latradius) * 180 / PI
418 maxlat = (@lat + latradius) * 180 / PI
419 minlon = (@lon - lonradius) * 180 / PI
420 maxlon = (@lon + lonradius) * 180 / PI
422 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
425 # get the SQL to use to calculate distance
426 def sql_for_distance(lat_field, lon_field)
427 "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)))"
433 doc = XML::Document.new
434 doc.encoding = XML::Encoding::UTF_8
435 root = XML::Node.new 'osm'
436 root['version'] = API_VERSION.to_s
437 root['generator'] = GENERATOR
438 root['copyright'] = COPYRIGHT_OWNER
439 root['attribution'] = ATTRIBUTION_URL
440 root['license'] = LICENSE_URL
446 def self.IPToCountry(ip_address)
448 ipinfo = Quova::IpInfo.new(ip_address)
450 if ipinfo.status == Quova::Success then
451 country = ipinfo.country_code
453 Net::HTTP.start('api.hostip.info') do |http|
454 country = http.get("/country.php?ip=#{ip_address}").body
455 country = "GB" if country == "UK"
459 return country.upcase
467 def self.IPLocation(ip_address)
468 code = OSM.IPToCountry(ip_address)
470 if code and country = Country.find_by_code(code)
471 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
477 # Parse a float, raising a specified exception on failure
478 def self.parse_float(str, klass, *args)
481 raise klass.new(*args)
484 # Construct a random token of a given length
485 def self.make_token(length = 30)
486 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
490 token += chars[(rand * chars.length).to_i].chr
496 # Return an SQL fragment to select a given area of the globe
497 def self.sql_for_area(bbox, prefix = nil)
498 tilesql = QuadTile.sql_for_area(bbox, prefix)
499 bbox = bbox.to_scaled
501 return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
502 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
505 def self.legal_text_for_country(country_code)
506 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
507 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
508 YAML::load_file(file_name)