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 the changeset provided is not yet closed
110 class APIChangesetNotYetClosedError < APIError
111 def initialize(changeset)
112 @changeset = changeset
115 attr_reader :changeset
122 "The changeset #{@changeset.id} is not yet closed."
126 # Raised when a user is already subscribed to the changeset
127 class APIChangesetAlreadySubscribedError < APIError
128 def initialize(changeset)
129 @changeset = changeset
132 attr_reader :changeset
139 "You are already subscribed to changeset #{@changeset.id}."
143 # Raised when a user is not subscribed to the changeset
144 class APIChangesetNotSubscribedError < APIError
145 def initialize(changeset)
146 @changeset = changeset
149 attr_reader :changeset
156 "You are not subscribed to changeset #{@changeset.id}."
160 # Raised when a change is expecting a changeset, but the changeset doesn't exist
161 class APIChangesetMissingError < APIError
167 "You need to supply a changeset to be able to make a change"
171 # Raised when a diff is uploaded containing many changeset IDs which don't match
172 # the changeset ID that the diff was uploaded to.
173 class APIChangesetMismatchError < APIError
174 def initialize(provided, allowed)
175 @provided, @allowed = provided, allowed
183 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
187 # Raised when a diff upload has an unknown action. You can only have create,
189 class APIChangesetActionInvalid < APIError
190 def initialize(provided)
199 "Unknown action #{@provided}, choices are create, modify, delete"
203 # Raised when bad XML is encountered which stops things parsing as
205 class APIBadXMLError < APIError
206 def initialize(model, xml, message="")
207 @model, @xml, @message = model, xml, message
215 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
219 # Raised when the provided version is not equal to the latest in the db.
220 class APIVersionMismatchError < APIError
221 def initialize(id, type, provided, latest)
222 @id, @type, @provided, @latest = id, type, provided, latest
225 attr_reader :provided, :latest, :id, :type
232 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
236 # raised when a two tags have a duplicate key string in an element.
237 # this is now forbidden by the API.
238 class APIDuplicateTagsError < APIError
239 def initialize(type, id, tag_key)
240 @type, @id, @tag_key = type, id, tag_key
243 attr_reader :type, :id, :tag_key
250 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
254 # Raised when a way has more than the configured number of way nodes.
255 # This prevents ways from being to long and difficult to work with
256 class APITooManyWayNodesError < APIError
257 def initialize(id, provided, max)
258 @id, @provided, @max = id, provided, max
261 attr_reader :id, :provided, :max
268 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
273 # raised when user input couldn't be parsed
274 class APIBadUserInput < APIError
275 def initialize(message)
289 # raised when bounding box is invalid
290 class APIBadBoundingBox < APIError
291 def initialize(message)
305 # raised when an API call is made using a method not supported on that URI
306 class APIBadMethodError < APIError
307 def initialize(supported_method)
308 @supported_method = supported_method
316 "Only method #{@supported_method} is supported on this URI"
321 # raised when an API call takes too long
322 class APITimeoutError < APIError
333 # raised when someone tries to redact a current version of
334 # an element - only historical versions can be redacted.
335 class APICannotRedactError < APIError
341 "Cannot redact current version of element, only historical versions may be redacted."
345 # Raised when the note provided is already closed
346 class APINoteAlreadyClosedError < APIError
358 "The note #{@note.id} was closed at #{@note.closed_at}"
362 # Raised when the note provided is already open
363 class APINoteAlreadyOpenError < APIError
375 "The note #{@note.id} is already open"
379 # raised when a two preferences have a duplicate key string.
380 class APIDuplicatePreferenceError < APIError
392 "Duplicate preferences with key #{@key}"
396 # Helper methods for going to/from mercator and lat/lng.
400 #init me with your bounding box and the size of your image
401 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
402 xsize = xsheet(max_lon) - xsheet(min_lon)
403 ysize = ysheet(max_lat) - ysheet(min_lat)
404 xscale = xsize / width
405 yscale = ysize / height
406 scale = [xscale, yscale].max
408 xpad = width * scale - xsize
409 ypad = height * scale - ysize
414 @tx = xsheet(min_lon) - xpad / 2
415 @ty = ysheet(min_lat) - ypad / 2
417 @bx = xsheet(max_lon) + xpad / 2
418 @by = ysheet(max_lat) + ypad / 2
421 #the following two functions will give you the x/y on the entire sheet
424 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
431 #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
434 return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
438 return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
445 # initialise with a base position
446 def initialize(lat, lon)
447 @lat = lat * PI / 180
448 @lon = lon * PI / 180
451 # get the distance from the base position to a given position
452 def distance(lat, lon)
455 return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
458 # get the worst case bounds for a given radius from the base position
460 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
463 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
464 rescue Errno::EDOM, Math::DomainError
468 minlat = (@lat - latradius) * 180 / PI
469 maxlat = (@lat + latradius) * 180 / PI
470 minlon = (@lon - lonradius) * 180 / PI
471 maxlon = (@lon + lonradius) * 180 / PI
473 return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
476 # get the SQL to use to calculate distance
477 def sql_for_distance(lat_field, lon_field)
478 "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)))"
484 doc = XML::Document.new
485 doc.encoding = XML::Encoding::UTF_8
486 root = XML::Node.new 'osm'
487 root['version'] = API_VERSION.to_s
488 root['generator'] = GENERATOR
489 root['copyright'] = COPYRIGHT_OWNER
490 root['attribution'] = ATTRIBUTION_URL
491 root['license'] = LICENSE_URL
497 def self.IPToCountry(ip_address)
499 ipinfo = Quova::IpInfo.new(ip_address)
501 if ipinfo.status == Quova::Success then
502 country = ipinfo.country_code
504 Net::HTTP.start('api.hostip.info') do |http|
505 country = http.get("/country.php?ip=#{ip_address}").body
506 country = "GB" if country == "UK"
510 return country.upcase
518 def self.IPLocation(ip_address)
519 code = OSM.IPToCountry(ip_address)
521 if code and country = Country.find_by_code(code)
522 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
528 # Parse a float, raising a specified exception on failure
529 def self.parse_float(str, klass, *args)
532 raise klass.new(*args)
535 # Construct a random token of a given length
536 def self.make_token(length = 30)
537 chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
541 token += chars[(rand * chars.length).to_i].chr
547 # Return an SQL fragment to select a given area of the globe
548 def self.sql_for_area(bbox, prefix = nil)
549 tilesql = QuadTile.sql_for_area(bbox, prefix)
550 bbox = bbox.to_scaled
552 return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
553 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
556 def self.legal_text_for_country(country_code)
557 file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
558 file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
559 YAML::load_file(file_name)