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 = "")
67 @object_id = 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)
184 "Changeset mismatch: Provided #{@provided} but only #{@allowed} is allowed"
188 # Raised when a diff upload has an unknown action. You can only have create,
190 class APIChangesetActionInvalid < APIError
191 def initialize(provided)
200 "Unknown action #{@provided}, choices are create, modify, delete"
204 # Raised when bad XML is encountered which stops things parsing as
206 class APIBadXMLError < APIError
207 def initialize(model, xml, message = "")
218 "Cannot parse valid #{@model} from xml string #{@xml}. #{@message}"
222 # Raised when the provided version is not equal to the latest in the db.
223 class APIVersionMismatchError < APIError
224 def initialize(id, type, provided, latest)
231 attr_reader :provided, :latest, :id, :type
238 "Version mismatch: Provided #{provided}, server had: #{latest} of #{type} #{id}"
242 # raised when a two tags have a duplicate key string in an element.
243 # this is now forbidden by the API.
244 class APIDuplicateTagsError < APIError
245 def initialize(type, id, tag_key)
251 attr_reader :type, :id, :tag_key
258 "Element #{@type}/#{@id} has duplicate tags with key #{@tag_key}"
262 # Raised when a way has more than the configured number of way nodes.
263 # This prevents ways from being to long and difficult to work with
264 class APITooManyWayNodesError < APIError
265 def initialize(id, provided, max)
271 attr_reader :id, :provided, :max
278 "You tried to add #{provided} nodes to way #{id}, however only #{max} are allowed"
283 # raised when user input couldn't be parsed
284 class APIBadUserInput < APIError
285 def initialize(message)
299 # raised when bounding box is invalid
300 class APIBadBoundingBox < APIError
301 def initialize(message)
315 # raised when an API call is made using a method not supported on that URI
316 class APIBadMethodError < APIError
317 def initialize(supported_method)
318 @supported_method = supported_method
326 "Only method #{@supported_method} is supported on this URI"
331 # raised when an API call takes too long
332 class APITimeoutError < APIError
343 # raised when someone tries to redact a current version of
344 # an element - only historical versions can be redacted.
345 class APICannotRedactError < APIError
351 "Cannot redact current version of element, only historical versions may be redacted."
355 # Raised when the note provided is already closed
356 class APINoteAlreadyClosedError < APIError
368 "The note #{@note.id} was closed at #{@note.closed_at}"
372 # Raised when the note provided is already open
373 class APINoteAlreadyOpenError < APIError
385 "The note #{@note.id} is already open"
389 # raised when a two preferences have a duplicate key string.
390 class APIDuplicatePreferenceError < APIError
402 "Duplicate preferences with key #{@key}"
406 # Helper methods for going to/from mercator and lat/lng.
410 # init me with your bounding box and the size of your image
411 def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
412 xsize = xsheet(max_lon) - xsheet(min_lon)
413 ysize = ysheet(max_lat) - ysheet(min_lat)
414 xscale = xsize / width
415 yscale = ysize / height
416 scale = [xscale, yscale].max
418 xpad = width * scale - xsize
419 ypad = height * scale - ysize
424 @tx = xsheet(min_lon) - xpad / 2
425 @ty = ysheet(min_lat) - ypad / 2
427 @bx = xsheet(max_lon) + xpad / 2
428 @by = ysheet(max_lat) + ypad / 2
431 # the following two functions will give you the x/y on the entire sheet
434 log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
441 # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
444 @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
448 ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
455 # initialise with a base position
456 def initialize(lat, lon)
457 @lat = lat * PI / 180
458 @lon = lon * PI / 180
461 # get the distance from the base position to a given position
462 def distance(lat, lon)
465 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2)**2 + cos(@lat) * cos(lat) * sin((lon - @lon) / 2)**2))
468 # get the worst case bounds for a given radius from the base position
470 latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
473 lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2 / cos(@lat)**2))
474 rescue Errno::EDOM, Math::DomainError
478 minlat = [(@lat - latradius) * 180 / PI, -90].max
479 maxlat = [(@lat + latradius) * 180 / PI, 90].min
480 minlon = [(@lon - lonradius) * 180 / PI, -180].max
481 maxlon = [(@lon + lonradius) * 180 / PI, 180].min
483 BoundingBox.new(minlon, minlat, maxlon, maxlat)
486 # get the SQL to use to calculate distance
487 def sql_for_distance(lat_field, lon_field)
488 "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)))"
494 doc = XML::Document.new
495 doc.encoding = XML::Encoding::UTF_8
496 root = XML::Node.new "osm"
497 root["version"] = API_VERSION.to_s
498 root["generator"] = GENERATOR
499 root["copyright"] = COPYRIGHT_OWNER
500 root["attribution"] = ATTRIBUTION_URL
501 root["license"] = LICENSE_URL
507 def self.ip_to_country(ip_address)
508 ipinfo = geoip_database.country(ip_address) if defined?(GEOIP_DATABASE)
511 country = ipinfo.country_code2
513 country = http_client.get("http://api.hostip.info/country.php?ip=#{ip_address}").body
514 country = "GB" if country == "UK"
522 def self.ip_location(ip_address)
523 code = OSM.ip_to_country(ip_address)
525 if code && country = Country.find(code)
526 return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
532 # Parse a float, raising a specified exception on failure
533 def self.parse_float(str, klass, *args)
536 raise klass.new(*args)
539 # Construct a random token of a given length
540 def self.make_token(length = 30)
541 chars = "abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
545 token += chars[(rand * chars.length).to_i].chr
551 # Return an SQL fragment to select a given area of the globe
552 def self.sql_for_area(bbox, prefix = nil)
553 tilesql = QuadTile.sql_for_area(bbox, prefix)
554 bbox = bbox.to_scaled
556 "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " \
557 "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
560 # Return the terms and conditions text for a given country
561 def self.legal_text_for_country(country_code)
562 file_name = Rails.root.join("config", "legales", country_code.to_s + ".yml")
563 file_name = Rails.root.join("config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
564 YAML.load_file(file_name)
567 # Return the HTTP client to use
569 @http_client ||= Faraday.new
572 # Return the GeoIP database handle
573 def self.geoip_database
574 @geoip_database ||= GeoIP.new(GEOIP_DATABASE) if defined?(GEOIP_DATABASE)