1 # The OSM module provides support functions for OSM.
4 require 'rexml/parsers/sax2parser'
8 if defined?(SystemTimer)
15 # The base class for API Errors.
16 class APIError < RuntimeError
18 :internal_server_error
26 # Raised when access is denied.
27 class APIAccessDenied < RuntimeError
37 # Raised when an API object is not found.
38 class APINotFoundError < APIError
48 # Raised when a precondition to an API action fails sanity check.
49 class APIPreconditionFailedError < APIError
50 def initialize(message = "")
59 "Precondition failed: #{@message}"
63 # Raised when to delete an already-deleted object.
64 class APIAlreadyDeletedError < APIError
65 def initialize(object = "object", object_id = "")
66 @object, @object_id = object, object_id
69 attr_reader :object, :object_id
76 "The #{object} with the id #{object_id} has already been deleted"
80 # Raised when the user logged in isn't the same as the changeset
81 class APIUserChangesetMismatchError < APIError
87 "The user doesn't own that changeset"
91 # Raised when the changeset provided is already closed
92 class APIChangesetAlreadyClosedError < APIError
93 def initialize(changeset)
94 @changeset = changeset
97 attr_reader :changeset
104 "The changeset #{@changeset.id} was closed at #{@changeset.closed_at}"
108 # Raised when the changeset provided is not yet closed
109 class APIChangesetNotYetClosedError < APIError
110 def initialize(changeset)
111 @changeset = changeset
114 attr_reader :changeset
121 "The changeset #{@changeset.id} is not yet closed."
125 # Raised when a user is already subscribed to the changeset
126 class APIChangesetAlreadySubscribedError < APIError
127 def initialize(changeset)
128 @changeset = changeset
131 attr_reader :changeset
138 "You are already subscribed to changeset #{@changeset.id}."
142 # Raised when a user is not subscribed to the changeset
143 class APIChangesetNotSubscribedError < APIError
144 def initialize(changeset)
145 @changeset = changeset
148 attr_reader :changeset
155 "You are not subscribed to changeset #{@changeset.id}."
159 # Raised when a change is expecting a changeset, but the changeset doesn't exist
160 class APIChangesetMissingError < APIError
166 "You need to supply a changeset to be able to make a change"
170 # Raised when a diff is uploaded containing many changeset IDs which don't match
171 # the changeset ID that the diff was uploaded to.
172 class APIChangesetMismatchError < APIError
173 def initialize(provided, allowed)
174 @provided, @allowed = provided, allowed
182 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
186 # Raised when a diff upload has an unknown action. You can only have create,
188 class APIChangesetActionInvalid < APIError
189 def initialize(provided)
198 "Unknown action #{@provided}, choices are create, modify, delete"
202 # Raised when bad XML is encountered which stops things parsing as
204 class APIBadXMLError < APIError
205 def initialize(model, xml, message = "")
206 @model, @xml, @message = model, xml, message
214 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
218 # Raised when the provided version is not equal to the latest in the db.
219 class APIVersionMismatchError < APIError
220 def initialize(id, type, provided, latest)
221 @id, @type, @provided, @latest = id, type, provided, latest
224 attr_reader :provided, :latest, :id, :type
231 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
235 # raised when a two tags have a duplicate key string in an element.
236 # this is now forbidden by the API.
237 class APIDuplicateTagsError < APIError
238 def initialize(type, id, tag_key)
239 @type, @id, @tag_key = type, id, tag_key
242 attr_reader :type, :id, :tag_key
249 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
253 # Raised when a way has more than the configured number of way nodes.
254 # This prevents ways from being to long and difficult to work with
255 class APITooManyWayNodesError < APIError
256 def initialize(id, provided, max)
257 @id, @provided, @max = id, provided, max
260 attr_reader :id, :provided, :max
267 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
272 # raised when user input couldn't be parsed
273 class APIBadUserInput < APIError
274 def initialize(message)
288 # raised when bounding box is invalid
289 class APIBadBoundingBox < APIError
290 def initialize(message)
304 # raised when an API call is made using a method not supported on that URI
305 class APIBadMethodError < APIError
306 def initialize(supported_method)
307 @supported_method = supported_method
315 "Only method #{@supported_method} is supported on this URI"
320 # raised when an API call takes too long
321 class APITimeoutError < APIError
332 # raised when someone tries to redact a current version of
333 # an element - only historical versions can be redacted.
334 class APICannotRedactError < APIError
340 "Cannot redact current version of element, only historical versions may be redacted."
344 # Raised when the note provided is already closed
345 class APINoteAlreadyClosedError < APIError
357 "The note #{@note.id} was closed at #{@note.closed_at}"
361 # Raised when the note provided is already open
362 class APINoteAlreadyOpenError < APIError
374 "The note #{@note.id} is already open"
378 # raised when a two preferences have a duplicate key string.
379 class APIDuplicatePreferenceError < APIError
391 "Duplicate preferences with key #{@key}"
395 # Helper methods for going to/from mercator and lat/lng.
399 # init me with your bounding box and the size of your image
400 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
401 xsize = xsheet(max_lon) - xsheet(min_lon)
402 ysize = ysheet(max_lat) - ysheet(min_lat)
403 xscale = xsize / width
404 yscale = ysize / height
405 scale = [xscale, yscale].max
407 xpad = width * scale - xsize
408 ypad = height * scale - ysize
413 @tx = xsheet(min_lon) - xpad / 2
414 @ty = ysheet(min_lat) - ypad / 2
416 @bx = xsheet(max_lon) + xpad / 2
417 @by = ysheet(max_lat) + ypad / 2
420 # the following two functions will give you the x/y on the entire sheet
423 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
430 # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
433 @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
437 ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
444 # initialise with a base position
445 def initialize(lat, lon)
446 @lat = lat * PI / 180
447 @lon = lon * PI / 180
450 # get the distance from the base position to a given position
451 def distance(lat, lon)
454 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2)**2 + cos(@lat) * cos(lat) * sin((lon - @lon) / 2)**2))
457 # get the worst case bounds for a given radius from the base position
459 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
462 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2 / cos(@lat)**2))
463 rescue Errno::EDOM, Math::DomainError
467 minlat = (@lat - latradius) * 180 / PI
468 maxlat = (@lat + latradius) * 180 / PI
469 minlon = (@lon - lonradius) * 180 / PI
470 maxlon = (@lon + lonradius) * 180 / PI
472 { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
475 # get the SQL to use to calculate distance
476 def sql_for_distance(lat_field, lon_field)
477 "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)))"
483 doc = XML::Document.new
484 doc.encoding = XML::Encoding::UTF_8
485 root = XML::Node.new 'osm'
486 root['version'] = API_VERSION.to_s
487 root['generator'] = GENERATOR
488 root['copyright'] = COPYRIGHT_OWNER
489 root['attribution'] = ATTRIBUTION_URL
490 root['license'] = LICENSE_URL
496 def self.ip_to_country(ip_address)
498 ipinfo = Quova::IpInfo.new(ip_address)
500 if ipinfo.status == Quova::SUCCESS
501 country = ipinfo.country_code
503 Net::HTTP.start('api.hostip.info') do |http|
504 country = http.get("/country.php?ip=#{ip_address}").body
505 country = "GB" if country == "UK"
509 return country.upcase
517 def self.ip_location(ip_address)
518 code = OSM.ip_to_country(ip_address)
520 if code && country = Country.find_by_code(code)
521 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
527 # Parse a float, raising a specified exception on failure
528 def self.parse_float(str, klass, *args)
531 raise klass.new(*args)
534 # Construct a random token of a given length
535 def self.make_token(length = 30)
536 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
540 token += chars[(rand * chars.length).to_i].chr
546 # Return an SQL fragment to select a given area of the globe
547 def self.sql_for_area(bbox, prefix = nil)
548 tilesql = QuadTile.sql_for_area(bbox, prefix)
549 bbox = bbox.to_scaled
551 "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
552 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
555 def self.legal_text_for_country(country_code)
556 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
557 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
558 YAML.load_file(file_name)